path
stringlengths 5
300
| repo_name
stringlengths 6
76
| content
stringlengths 26
1.05M
|
---|---|---|
src/parser/warrior/arms/CHANGELOG.js | sMteX/WoWAnalyzer | import React from 'react';
import { Aelexe, Zerotorescue, Sharrq, Matardarix, Korebian } from 'CONTRIBUTORS';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
export default [
{
date: new Date('2019-02-03'),
changes: <>Added a suggestion to not use <SpellLink id={SPELLS.SWEEPING_STRIKES.id} /> during <SpellLink id={SPELLS.COLOSSUS_SMASH.id} /> / <SpellLink id={SPELLS.WARBREAKER_TALENT.id} />.</>,
contributors: [Korebian],
},
{
date: new Date('2019-02-02'),
changes: <>Added more information to the <SpellLink id={SPELLS.CRUSHING_ASSAULT_TRAIT.id} /> module. Added <SpellLink id={SPELLS.LORD_OF_WAR.id} /> module.</>,
contributors: [Korebian],
},
{
date: new Date('2018-12-12'),
changes: <>Updated for patch 8.1, <SpellLink id={SPELLS.CHARGE.id} /> is no longer on the GCD and <SpellLink id={SPELLS.EXECUTIONERS_PRECISION_TRAIT.id} /> have been replaced by <SpellLink id={SPELLS.STRIKING_THE_ANVIL.id} />.</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-28'),
changes: <>Added <SpellLink id={SPELLS.CRUSHING_ASSAULT_TRAIT.id} /> module.</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-15'),
changes: <>Fixed Overpower events where stacks were applied before casts</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-14'),
changes: <>Added a suggestion on using <SpellLink id={SPELLS.SLAM.id} /> while <SpellLink id={SPELLS.MORTAL_STRIKE.id} /> is available.</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-12'),
changes: <>Added <SpellLink id={SPELLS.FERVOR_OF_BATTLE_TALENT.id} /> in Talents module.</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-10'),
changes: <>Modified <SpellLink id={SPELLS.MORTAL_STRIKE.id} /> analysis to get it more accurate with the execution phase.</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-07'),
changes: <>Added Rage usage tab and suggestions on rage wast, removed the doughnut chart for rage usage</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-06'),
changes: <>Added cooldown tracker tab</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-05'),
changes: <>New:<ul><li>Checklist</li><li>Talents module</li><li><SpellLink id={SPELLS.EXECUTIONERS_PRECISION_TRAIT.id} /> module</li><li><SpellLink id={SPELLS.SEISMIC_WAVE.id} /> module</li><li><SpellLink id={SPELLS.TEST_OF_MIGHT.id} /> module</li><li>rage usage module</li><li>suggestions regarding <SpellLink id={SPELLS.DEFENSIVE_STANCE_TALENT.id} /></li></ul>Fixed:<ul><li><SpellLink id={SPELLS.ANGER_MANAGEMENT_TALENT.id} /> cooldown reduction calculation</li></ul></>,
contributors: [Matardarix],
},
{
date: new Date('2018-10-12'),
changes: <>Fixed some spell IDs and ability information. Updated Config.</>,
contributors: [Sharrq],
},
{
date: new Date('2018-06-30'),
changes: <>Update all abilities to new BFA values, removed incompatible modules and added an <SpellLink id={SPELLS.ANGER_MANAGEMENT_TALENT.id} /> statistic.</>,
contributors: [Zerotorescue],
},
{
date: new Date('2018-06-16'),
changes: <>Fixed a rare crash when casting <SpellLink id={SPELLS.EXECUTE.id} /> on a non-boss target.</>,
contributors: [Aelexe],
},
];
|
ajax/libs/jquery-mobile/1.3.2/jquery.mobile.js | stephenmathieson/cdnjs | /*!
* jQuery Mobile 1.3.2
* Git HEAD hash: 528cf0e96940644ea644096bfeb913ed920ffaef <> Date: Fri Jul 19 2013 22:17:57 UTC
* http://jquerymobile.com
*
* Copyright 2010, 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
*/
(function ( root, doc, factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery" ], function ( $ ) {
factory( $, root, doc );
return $.mobile;
});
} else {
// Browser globals
factory( root.jQuery, root, doc );
}
}( this, document, function ( jQuery, window, document, undefined ) {
(function( $ ) {
$.mobile = {};
}( jQuery ));
(function( $, window, undefined ) {
var nsNormalizeDict = {};
// jQuery.mobile configurable options
$.mobile = $.extend($.mobile, {
// Version of the jQuery Mobile Framework
version: "1.3.2",
// Namespace used framework-wide for data-attrs. Default is no namespace
ns: "",
// Define the url parameter used for referencing widget-generated sub-pages.
// Translates to to example.html&ui-page=subpageIdentifier
// hash segment before &ui-page= is used to make Ajax request
subPageUrlKey: "ui-page",
// Class assigned to page currently in view, and during transitions
activePageClass: "ui-page-active",
// Class used for "active" button state, from CSS framework
activeBtnClass: "ui-btn-active",
// Class used for "focus" form element state, from CSS framework
focusClass: "ui-focus",
// Automatically handle clicks and form submissions through Ajax, when same-domain
ajaxEnabled: true,
// Automatically load and show pages based on location.hash
hashListeningEnabled: true,
// disable to prevent jquery from bothering with links
linkBindingEnabled: true,
// Set default page transition - 'none' for no transitions
defaultPageTransition: "fade",
// Set maximum window width for transitions to apply - 'false' for no limit
maxTransitionWidth: false,
// Minimum scroll distance that will be remembered when returning to a page
minScrollBack: 250,
// DEPRECATED: the following property is no longer in use, but defined until 2.0 to prevent conflicts
touchOverflowEnabled: false,
// Set default dialog transition - 'none' for no transitions
defaultDialogTransition: "pop",
// Error response message - appears when an Ajax page request fails
pageLoadErrorMessage: "Error Loading Page",
// For error messages, which theme does the box uses?
pageLoadErrorMessageTheme: "e",
// replace calls to window.history.back with phonegaps navigation helper
// where it is provided on the window object
phonegapNavigationEnabled: false,
//automatically initialize the DOM when it's ready
autoInitializePage: true,
pushStateEnabled: true,
// allows users to opt in to ignoring content by marking a parent element as
// data-ignored
ignoreContentEnabled: false,
// turn of binding to the native orientationchange due to android orientation behavior
orientationChangeEnabled: true,
buttonMarkup: {
hoverDelay: 200
},
// define the window and the document objects
window: $( window ),
document: $( document ),
// TODO might be useful upstream in jquery itself ?
keyCode: {
ALT: 18,
BACKSPACE: 8,
CAPS_LOCK: 20,
COMMA: 188,
COMMAND: 91,
COMMAND_LEFT: 91, // COMMAND
COMMAND_RIGHT: 93,
CONTROL: 17,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
MENU: 93, // COMMAND_RIGHT
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SHIFT: 16,
SPACE: 32,
TAB: 9,
UP: 38,
WINDOWS: 91 // COMMAND
},
// Place to store various widget extensions
behaviors: {},
// Scroll page vertically: scroll to 0 to hide iOS address bar, or pass a Y value
silentScroll: function( ypos ) {
if ( $.type( ypos ) !== "number" ) {
ypos = $.mobile.defaultHomeScroll;
}
// prevent scrollstart and scrollstop events
$.event.special.scrollstart.enabled = false;
setTimeout( function() {
window.scrollTo( 0, ypos );
$.mobile.document.trigger( "silentscroll", { x: 0, y: ypos });
}, 20 );
setTimeout( function() {
$.event.special.scrollstart.enabled = true;
}, 150 );
},
// Expose our cache for testing purposes.
nsNormalizeDict: nsNormalizeDict,
// Take a data attribute property, prepend the namespace
// and then camel case the attribute string. Add the result
// to our nsNormalizeDict so we don't have to do this again.
nsNormalize: function( prop ) {
if ( !prop ) {
return;
}
return nsNormalizeDict[ prop ] || ( nsNormalizeDict[ prop ] = $.camelCase( $.mobile.ns + prop ) );
},
// Find the closest parent with a theme class on it. Note that
// we are not using $.fn.closest() on purpose here because this
// method gets called quite a bit and we need it to be as fast
// as possible.
getInheritedTheme: function( el, defaultTheme ) {
var e = el[ 0 ],
ltr = "",
re = /ui-(bar|body|overlay)-([a-z])\b/,
c, m;
while ( e ) {
c = e.className || "";
if ( c && ( m = re.exec( c ) ) && ( ltr = m[ 2 ] ) ) {
// We found a parent with a theme class
// on it so bail from this loop.
break;
}
e = e.parentNode;
}
// Return the theme letter we found, if none, return the
// specified default.
return ltr || defaultTheme || "a";
},
// TODO the following $ and $.fn extensions can/probably should be moved into jquery.mobile.core.helpers
//
// Find the closest javascript page element to gather settings data jsperf test
// http://jsperf.com/single-complex-selector-vs-many-complex-selectors/edit
// possibly naive, but it shows that the parsing overhead for *just* the page selector vs
// the page and dialog selector is negligable. This could probably be speed up by
// doing a similar parent node traversal to the one found in the inherited theme code above
closestPageData: function( $target ) {
return $target
.closest( ':jqmData(role="page"), :jqmData(role="dialog")' )
.data( "mobile-page" );
},
enhanceable: function( $set ) {
return this.haveParents( $set, "enhance" );
},
hijackable: function( $set ) {
return this.haveParents( $set, "ajax" );
},
haveParents: function( $set, attr ) {
if ( !$.mobile.ignoreContentEnabled ) {
return $set;
}
var count = $set.length,
$newSet = $(),
e, $element, excluded;
for ( var i = 0; i < count; i++ ) {
$element = $set.eq( i );
excluded = false;
e = $set[ i ];
while ( e ) {
var c = e.getAttribute ? e.getAttribute( "data-" + $.mobile.ns + attr ) : "";
if ( c === "false" ) {
excluded = true;
break;
}
e = e.parentNode;
}
if ( !excluded ) {
$newSet = $newSet.add( $element );
}
}
return $newSet;
},
getScreenHeight: function() {
// Native innerHeight returns more accurate value for this across platforms,
// jQuery version is here as a normalized fallback for platforms like Symbian
return window.innerHeight || $.mobile.window.height();
}
}, $.mobile );
// Mobile version of data and removeData and hasData methods
// ensures all data is set and retrieved using jQuery Mobile's data namespace
$.fn.jqmData = function( prop, value ) {
var result;
if ( typeof prop !== "undefined" ) {
if ( prop ) {
prop = $.mobile.nsNormalize( prop );
}
// undefined is permitted as an explicit input for the second param
// in this case it returns the value and does not set it to undefined
if( arguments.length < 2 || value === undefined ){
result = this.data( prop );
} else {
result = this.data( prop, value );
}
}
return result;
};
$.jqmData = function( elem, prop, value ) {
var result;
if ( typeof prop !== "undefined" ) {
result = $.data( elem, prop ? $.mobile.nsNormalize( prop ) : prop, value );
}
return result;
};
$.fn.jqmRemoveData = function( prop ) {
return this.removeData( $.mobile.nsNormalize( prop ) );
};
$.jqmRemoveData = function( elem, prop ) {
return $.removeData( elem, $.mobile.nsNormalize( prop ) );
};
$.fn.removeWithDependents = function() {
$.removeWithDependents( this );
};
$.removeWithDependents = function( elem ) {
var $elem = $( elem );
( $elem.jqmData( 'dependents' ) || $() ).remove();
$elem.remove();
};
$.fn.addDependents = function( newDependents ) {
$.addDependents( $( this ), newDependents );
};
$.addDependents = function( elem, newDependents ) {
var dependents = $( elem ).jqmData( 'dependents' ) || $();
$( elem ).jqmData( 'dependents', $.merge( dependents, newDependents ) );
};
// note that this helper doesn't attempt to handle the callback
// or setting of an html element's text, its only purpose is
// to return the html encoded version of the text in all cases. (thus the name)
$.fn.getEncodedText = function() {
return $( "<div/>" ).text( $( this ).text() ).html();
};
// fluent helper function for the mobile namespaced equivalent
$.fn.jqmEnhanceable = function() {
return $.mobile.enhanceable( this );
};
$.fn.jqmHijackable = function() {
return $.mobile.hijackable( this );
};
// Monkey-patching Sizzle to filter the :jqmData selector
var oldFind = $.find,
jqmDataRE = /:jqmData\(([^)]*)\)/g;
$.find = function( selector, context, ret, extra ) {
selector = selector.replace( jqmDataRE, "[data-" + ( $.mobile.ns || "" ) + "$1]" );
return oldFind.call( this, selector, context, ret, extra );
};
$.extend( $.find, oldFind );
$.find.matches = function( expr, set ) {
return $.find( expr, null, null, set );
};
$.find.matchesSelector = function( node, expr ) {
return $.find( expr, null, null, [ node ] ).length > 0;
};
})( jQuery, this );
/*!
* jQuery UI Widget v1.10.0pre - 2012-11-13 (ff055a0c353c3c8ce6e5bfa07ad7cb03e8885bc5)
* http://jqueryui.com
*
* Copyright 2010, 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/jQuery.widget/
*/
(function( $, undefined ) {
var uuid = 0,
slice = Array.prototype.slice,
_cleanData = $.cleanData;
$.cleanData = function( elems ) {
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
try {
$( elem ).triggerHandler( "remove" );
// http://bugs.jquery.com/ticket/8235
} catch( e ) {}
}
_cleanData( elems );
};
$.widget = function( name, base, prototype ) {
var fullName, existingConstructor, constructor, basePrototype,
namespace = name.split( "." )[ 0 ];
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
return !!$.data( elem, fullName );
};
$[ namespace ] = $[ namespace ] || {};
existingConstructor = $[ namespace ][ name ];
constructor = $[ namespace ][ name ] = function( options, element ) {
// allow instantiation without "new" keyword
if ( !this._createWidget ) {
return new constructor( options, element );
}
// allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if ( arguments.length ) {
this._createWidget( options, element );
}
};
// extend with the existing constructor to carry over any static properties
$.extend( constructor, existingConstructor, {
version: prototype.version,
// copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend( {}, prototype ),
// track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
});
basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( $.isFunction( value ) ) {
prototype[ prop ] = (function() {
var _super = function() {
return base.prototype[ prop ].apply( this, arguments );
},
_superApply = function( args ) {
return base.prototype[ prop ].apply( this, args );
};
return function() {
var __super = this._super,
__superApply = this._superApply,
returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply( this, arguments );
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
})();
}
});
constructor.prototype = $.widget.extend( basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name
}, prototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
widgetFullName: fullName
});
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if ( existingConstructor ) {
$.each( existingConstructor._childConstructors, function( i, child ) {
var childPrototype = child.prototype;
// redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
});
// remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push( constructor );
}
$.widget.bridge( name, constructor );
};
$.widget.extend = function( target ) {
var input = slice.call( arguments, 1 ),
inputIndex = 0,
inputLength = input.length,
key,
value;
for ( ; inputIndex < inputLength; inputIndex++ ) {
for ( key in input[ inputIndex ] ) {
value = input[ inputIndex ][ key ];
if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
// Clone objects
if ( $.isPlainObject( value ) ) {
target[ key ] = $.isPlainObject( target[ key ] ) ?
$.widget.extend( {}, target[ key ], value ) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend( {}, value );
// Copy everything else by reference
} else {
target[ key ] = value;
}
}
}
}
return target;
};
$.widget.bridge = function( name, object ) {
var fullName = object.prototype.widgetFullName || name;
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string",
args = slice.call( arguments, 1 ),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.widget.extend.apply( null, [ options ].concat(args) ) :
options;
if ( isMethodCall ) {
this.each(function() {
var methodValue,
instance = $.data( this, fullName );
if ( !instance ) {
return $.error( "cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'" );
}
if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
return $.error( "no such method '" + options + "' for " + name + " widget instance" );
}
methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack( methodValue.get() ) :
methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, fullName );
if ( instance ) {
instance.option( options || {} )._init();
} else {
$.data( this, fullName, new object( options, this ) );
}
});
}
return returnValue;
};
};
$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: false,
// callbacks
create: null
},
_createWidget: function( options, element ) {
element = $( element || this.defaultElement || this )[ 0 ];
this.element = $( element );
this.uuid = uuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.options = $.widget.extend( {},
this.options,
this._getCreateOptions(),
options );
this.bindings = $();
this.hoverable = $();
this.focusable = $();
if ( element !== this ) {
$.data( element, this.widgetFullName, this );
this._on( true, this.element, {
remove: function( event ) {
if ( event.target === element ) {
this.destroy();
}
}
});
this.document = $( element.style ?
// element within the document
element.ownerDocument :
// element is window or document
element.document || element );
this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
}
this._create();
this._trigger( "create", null, this._getCreateEventData() );
this._init();
},
_getCreateOptions: $.noop,
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function() {
this._destroy();
// we can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.unbind( this.eventNamespace )
// 1.9 BC for #7810
// TODO remove dual storage
.removeData( this.widgetName )
.removeData( this.widgetFullName )
// support: jquery <1.6.3
// http://bugs.jquery.com/ticket/9413
.removeData( $.camelCase( this.widgetFullName ) );
this.widget()
.unbind( this.eventNamespace )
.removeAttr( "aria-disabled" )
.removeClass(
this.widgetFullName + "-disabled " +
"ui-state-disabled" );
// clean up events and states
this.bindings.unbind( this.eventNamespace );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
},
_destroy: $.noop,
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key,
parts,
curOption,
i;
if ( arguments.length === 0 ) {
// don't return a reference to the internal hash
return $.widget.extend( {}, this.options );
}
if ( typeof key === "string" ) {
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split( "." );
key = parts.shift();
if ( parts.length ) {
curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
for ( i = 0; i < parts.length - 1; i++ ) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if ( value === undefined ) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if ( value === undefined ) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var key;
for ( key in options ) {
this._setOption( key, options[ key ] );
}
return this;
},
_setOption: function( key, value ) {
this.options[ key ] = value;
if ( key === "disabled" ) {
this.widget()
.toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
.attr( "aria-disabled", value );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
}
return this;
},
enable: function() {
return this._setOption( "disabled", false );
},
disable: function() {
return this._setOption( "disabled", true );
},
_on: function( suppressDisabledCheck, element, handlers ) {
var delegateElement,
instance = this;
// no suppressDisabledCheck flag, shuffle arguments
if ( typeof suppressDisabledCheck !== "boolean" ) {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// no element argument, shuffle and use this.element
if ( !handlers ) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
// accept selectors, DOM elements
element = delegateElement = $( element );
this.bindings = this.bindings.add( element );
}
$.each( handlers, function( event, handler ) {
function handlerProxy() {
// allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if ( !suppressDisabledCheck &&
( instance.options.disabled === true ||
$( this ).hasClass( "ui-state-disabled" ) ) ) {
return;
}
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
// copy the guid so direct unbinding works
if ( typeof handler !== "string" ) {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match( /^(\w+)\s*(.*)$/ ),
eventName = match[1] + instance.eventNamespace,
selector = match[2];
if ( selector ) {
delegateElement.delegate( selector, eventName, handlerProxy );
} else {
element.bind( eventName, handlerProxy );
}
});
},
_off: function( element, eventName ) {
eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
element.unbind( eventName ).undelegate( eventName );
},
_delay: function( handler, delay ) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var instance = this;
return setTimeout( handlerProxy, delay || 0 );
},
_hoverable: function( element ) {
this.hoverable = this.hoverable.add( element );
this._on( element, {
mouseenter: function( event ) {
$( event.currentTarget ).addClass( "ui-state-hover" );
},
mouseleave: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-hover" );
}
});
},
_focusable: function( element ) {
this.focusable = this.focusable.add( element );
this._on( element, {
focusin: function( event ) {
$( event.currentTarget ).addClass( "ui-state-focus" );
},
focusout: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-focus" );
}
});
},
_trigger: function( type, event, data ) {
var prop, orig,
callback = this.options[ type ];
data = data || {};
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// the original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// copy original event properties over to the new event
orig = event.originalEvent;
if ( orig ) {
for ( prop in orig ) {
if ( !( prop in event ) ) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger( event, data );
return !( $.isFunction( callback ) &&
callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
event.isDefaultPrevented() );
}
};
$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
if ( typeof options === "string" ) {
options = { effect: options };
}
var hasOptions,
effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if ( typeof options === "number" ) {
options = { duration: options };
}
hasOptions = !$.isEmptyObject( options );
options.complete = callback;
if ( options.delay ) {
element.delay( options.delay );
}
if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
element[ method ]( options );
} else if ( effectName !== method && element[ effectName ] ) {
element[ effectName ]( options.duration, options.easing, callback );
} else {
element.queue(function( next ) {
$( this )[ method ]();
if ( callback ) {
callback.call( element[ 0 ] );
}
next();
});
}
};
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.widget", {
// decorate the parent _createWidget to trigger `widgetinit` for users
// who wish to do post post `widgetcreate` alterations/additions
//
// TODO create a pull request for jquery ui to trigger this event
// in the original _createWidget
_createWidget: function() {
$.Widget.prototype._createWidget.apply( this, arguments );
this._trigger( 'init' );
},
_getCreateOptions: function() {
var elem = this.element,
options = {};
$.each( this.options, function( option ) {
var value = elem.jqmData( option.replace( /[A-Z]/g, function( c ) {
return "-" + c.toLowerCase();
})
);
if ( value !== undefined ) {
options[ option ] = value;
}
});
return options;
},
enhanceWithin: function( target, useKeepNative ) {
this.enhance( $( this.options.initSelector, $( target )), useKeepNative );
},
enhance: function( targets, useKeepNative ) {
var page, keepNative, $widgetElements = $( targets ), self = this;
// if ignoreContentEnabled is set to true the framework should
// only enhance the selected elements when they do NOT have a
// parent with the data-namespace-ignore attribute
$widgetElements = $.mobile.enhanceable( $widgetElements );
if ( useKeepNative && $widgetElements.length ) {
// TODO remove dependency on the page widget for the keepNative.
// Currently the keepNative value is defined on the page prototype so
// the method is as well
page = $.mobile.closestPageData( $widgetElements );
keepNative = ( page && page.keepNativeSelector()) || "";
$widgetElements = $widgetElements.not( keepNative );
}
$widgetElements[ this.widgetName ]();
},
raise: function( msg ) {
throw "Widget [" + this.widgetName + "]: " + msg;
}
});
})( jQuery );
(function( $, window ) {
// DEPRECATED
// NOTE global mobile object settings
$.extend( $.mobile, {
// DEPRECATED Should the text be visble in the loading message?
loadingMessageTextVisible: undefined,
// DEPRECATED When the text is visible, what theme does the loading box use?
loadingMessageTheme: undefined,
// DEPRECATED default message setting
loadingMessage: undefined,
// DEPRECATED
// Turn on/off page loading message. Theme doubles as an object argument
// with the following shape: { theme: '', text: '', html: '', textVisible: '' }
// NOTE that the $.mobile.loading* settings and params past the first are deprecated
showPageLoadingMsg: function( theme, msgText, textonly ) {
$.mobile.loading( 'show', theme, msgText, textonly );
},
// DEPRECATED
hidePageLoadingMsg: function() {
$.mobile.loading( 'hide' );
},
loading: function() {
this.loaderWidget.loader.apply( this.loaderWidget, arguments );
}
});
// TODO move loader class down into the widget settings
var loaderClass = "ui-loader", $html = $( "html" ), $window = $.mobile.window;
$.widget( "mobile.loader", {
// NOTE if the global config settings are defined they will override these
// options
options: {
// the theme for the loading message
theme: "a",
// whether the text in the loading message is shown
textVisible: false,
// custom html for the inner content of the loading message
html: "",
// the text to be displayed when the popup is shown
text: "loading"
},
defaultHtml: "<div class='" + loaderClass + "'>" +
"<span class='ui-icon ui-icon-loading'></span>" +
"<h1></h1>" +
"</div>",
// For non-fixed supportin browsers. Position at y center (if scrollTop supported), above the activeBtn (if defined), or just 100px from top
fakeFixLoader: function() {
var activeBtn = $( "." + $.mobile.activeBtnClass ).first();
this.element
.css({
top: $.support.scrollTop && $window.scrollTop() + $window.height() / 2 ||
activeBtn.length && activeBtn.offset().top || 100
});
},
// check position of loader to see if it appears to be "fixed" to center
// if not, use abs positioning
checkLoaderPosition: function() {
var offset = this.element.offset(),
scrollTop = $window.scrollTop(),
screenHeight = $.mobile.getScreenHeight();
if ( offset.top < scrollTop || ( offset.top - scrollTop ) > screenHeight ) {
this.element.addClass( "ui-loader-fakefix" );
this.fakeFixLoader();
$window
.unbind( "scroll", this.checkLoaderPosition )
.bind( "scroll", $.proxy( this.fakeFixLoader, this ) );
}
},
resetHtml: function() {
this.element.html( $( this.defaultHtml ).html() );
},
// Turn on/off page loading message. Theme doubles as an object argument
// with the following shape: { theme: '', text: '', html: '', textVisible: '' }
// NOTE that the $.mobile.loading* settings and params past the first are deprecated
// TODO sweet jesus we need to break some of this out
show: function( theme, msgText, textonly ) {
var textVisible, message, $header, loadSettings;
this.resetHtml();
// use the prototype options so that people can set them globally at
// mobile init. Consistency, it's what's for dinner
if ( $.type(theme) === "object" ) {
loadSettings = $.extend( {}, this.options, theme );
// prefer object property from the param then the old theme setting
theme = loadSettings.theme || $.mobile.loadingMessageTheme;
} else {
loadSettings = this.options;
// here we prefer the them value passed as a string argument, then
// we prefer the global option because we can't use undefined default
// prototype options, then the prototype option
theme = theme || $.mobile.loadingMessageTheme || loadSettings.theme;
}
// set the message text, prefer the param, then the settings object
// then loading message
message = msgText || $.mobile.loadingMessage || loadSettings.text;
// prepare the dom
$html.addClass( "ui-loading" );
if ( $.mobile.loadingMessage !== false || loadSettings.html ) {
// boolean values require a bit more work :P, supports object properties
// and old settings
if ( $.mobile.loadingMessageTextVisible !== undefined ) {
textVisible = $.mobile.loadingMessageTextVisible;
} else {
textVisible = loadSettings.textVisible;
}
// add the proper css given the options (theme, text, etc)
// Force text visibility if the second argument was supplied, or
// if the text was explicitly set in the object args
this.element.attr("class", loaderClass +
" ui-corner-all ui-body-" + theme +
" ui-loader-" + ( textVisible || msgText || theme.text ? "verbose" : "default" ) +
( loadSettings.textonly || textonly ? " ui-loader-textonly" : "" ) );
// TODO verify that jquery.fn.html is ok to use in both cases here
// this might be overly defensive in preventing unknowing xss
// if the html attribute is defined on the loading settings, use that
// otherwise use the fallbacks from above
if ( loadSettings.html ) {
this.element.html( loadSettings.html );
} else {
this.element.find( "h1" ).text( message );
}
// attach the loader to the DOM
this.element.appendTo( $.mobile.pageContainer );
// check that the loader is visible
this.checkLoaderPosition();
// on scroll check the loader position
$window.bind( "scroll", $.proxy( this.checkLoaderPosition, this ) );
}
},
hide: function() {
$html.removeClass( "ui-loading" );
if ( $.mobile.loadingMessage ) {
this.element.removeClass( "ui-loader-fakefix" );
}
$.mobile.window.unbind( "scroll", this.fakeFixLoader );
$.mobile.window.unbind( "scroll", this.checkLoaderPosition );
}
});
$window.bind( 'pagecontainercreate', function() {
$.mobile.loaderWidget = $.mobile.loaderWidget || $( $.mobile.loader.prototype.defaultHtml ).loader();
});
})(jQuery, this);
// Script: jQuery hashchange event
//
// *Version: 1.3, Last updated: 7/21/2010*
//
// Project Home - http://benalman.com/projects/jquery-hashchange-plugin/
// GitHub - http://github.com/cowboy/jquery-hashchange/
// Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js
// (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped)
//
// About: License
//
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
//
// About: Examples
//
// These working examples, complete with fully commented code, illustrate a few
// ways in which this plugin can be used.
//
// hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
// document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/
//
// About: Support and Testing
//
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
//
// jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5,
// Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5.
// Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/
//
// About: Known issues
//
// While this jQuery hashchange event implementation is quite stable and
// robust, there are a few unfortunate browser bugs surrounding expected
// hashchange event-based behaviors, independent of any JavaScript
// window.onhashchange abstraction. See the following examples for more
// information:
//
// Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/
// Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/
// WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/
// Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/
//
// Also note that should a browser natively support the window.onhashchange
// event, but not report that it does, the fallback polling loop will be used.
//
// About: Release History
//
// 1.3 - (7/21/2010) Reorganized IE6/7 Iframe code to make it more
// "removable" for mobile-only development. Added IE6/7 document.title
// support. Attempted to make Iframe as hidden as possible by using
// techniques from http://www.paciellogroup.com/blog/?p=604. Added
// support for the "shortcut" format $(window).hashchange( fn ) and
// $(window).hashchange() like jQuery provides for built-in events.
// Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and
// lowered its default value to 50. Added <jQuery.fn.hashchange.domain>
// and <jQuery.fn.hashchange.src> properties plus document-domain.html
// file to address access denied issues when setting document.domain in
// IE6/7.
// 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin
// from a page on another domain would cause an error in Safari 4. Also,
// IE6/7 Iframe is now inserted after the body (this actually works),
// which prevents the page from scrolling when the event is first bound.
// Event can also now be bound before DOM ready, but it won't be usable
// before then in IE6/7.
// 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug
// where browser version is incorrectly reported as 8.0, despite
// inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag.
// 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special
// window.onhashchange functionality into a separate plugin for users
// who want just the basic event & back button support, without all the
// extra awesomeness that BBQ provides. This plugin will be included as
// part of jQuery BBQ, but also be available separately.
(function( $, window, undefined ) {
// Reused string.
var str_hashchange = 'hashchange',
// Method / object references.
doc = document,
fake_onhashchange,
special = $.event.special,
// Does the browser support window.onhashchange? Note that IE8 running in
// IE7 compatibility mode reports true for 'onhashchange' in window, even
// though the event isn't supported, so also test document.documentMode.
doc_mode = doc.documentMode,
supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 );
// Get location.hash (or what you'd expect location.hash to be) sans any
// leading #. Thanks for making this necessary, Firefox!
function get_fragment( url ) {
url = url || location.href;
return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' );
};
// Method: jQuery.fn.hashchange
//
// Bind a handler to the window.onhashchange event or trigger all bound
// window.onhashchange event handlers. This behavior is consistent with
// jQuery's built-in event handlers.
//
// Usage:
//
// > jQuery(window).hashchange( [ handler ] );
//
// Arguments:
//
// handler - (Function) Optional handler to be bound to the hashchange
// event. This is a "shortcut" for the more verbose form:
// jQuery(window).bind( 'hashchange', handler ). If handler is omitted,
// all bound window.onhashchange event handlers will be triggered. This
// is a shortcut for the more verbose
// jQuery(window).trigger( 'hashchange' ). These forms are described in
// the <hashchange event> section.
//
// Returns:
//
// (jQuery) The initial jQuery collection of elements.
// Allow the "shortcut" format $(elem).hashchange( fn ) for binding and
// $(elem).hashchange() for triggering, like jQuery does for built-in events.
$.fn[ str_hashchange ] = function( fn ) {
return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange );
};
// Property: jQuery.fn.hashchange.delay
//
// The numeric interval (in milliseconds) at which the <hashchange event>
// polling loop executes. Defaults to 50.
// Property: jQuery.fn.hashchange.domain
//
// If you're setting document.domain in your JavaScript, and you want hash
// history to work in IE6/7, not only must this property be set, but you must
// also set document.domain BEFORE jQuery is loaded into the page. This
// property is only applicable if you are supporting IE6/7 (or IE8 operating
// in "IE7 compatibility" mode).
//
// In addition, the <jQuery.fn.hashchange.src> property must be set to the
// path of the included "document-domain.html" file, which can be renamed or
// modified if necessary (note that the document.domain specified must be the
// same in both your main JavaScript as well as in this file).
//
// Usage:
//
// jQuery.fn.hashchange.domain = document.domain;
// Property: jQuery.fn.hashchange.src
//
// If, for some reason, you need to specify an Iframe src file (for example,
// when setting document.domain as in <jQuery.fn.hashchange.domain>), you can
// do so using this property. Note that when using this property, history
// won't be recorded in IE6/7 until the Iframe src file loads. This property
// is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7
// compatibility" mode).
//
// Usage:
//
// jQuery.fn.hashchange.src = 'path/to/file.html';
$.fn[ str_hashchange ].delay = 50;
/*
$.fn[ str_hashchange ].domain = null;
$.fn[ str_hashchange ].src = null;
*/
// Event: hashchange event
//
// Fired when location.hash changes. In browsers that support it, the native
// HTML5 window.onhashchange event is used, otherwise a polling loop is
// initialized, running every <jQuery.fn.hashchange.delay> milliseconds to
// see if the hash has changed. In IE6/7 (and IE8 operating in "IE7
// compatibility" mode), a hidden Iframe is created to allow the back button
// and hash-based history to work.
//
// Usage as described in <jQuery.fn.hashchange>:
//
// > // Bind an event handler.
// > jQuery(window).hashchange( function(e) {
// > var hash = location.hash;
// > ...
// > });
// >
// > // Manually trigger the event handler.
// > jQuery(window).hashchange();
//
// A more verbose usage that allows for event namespacing:
//
// > // Bind an event handler.
// > jQuery(window).bind( 'hashchange', function(e) {
// > var hash = location.hash;
// > ...
// > });
// >
// > // Manually trigger the event handler.
// > jQuery(window).trigger( 'hashchange' );
//
// Additional Notes:
//
// * The polling loop and Iframe are not created until at least one handler
// is actually bound to the 'hashchange' event.
// * If you need the bound handler(s) to execute immediately, in cases where
// a location.hash exists on page load, via bookmark or page refresh for
// example, use jQuery(window).hashchange() or the more verbose
// jQuery(window).trigger( 'hashchange' ).
// * The event can be bound before DOM ready, but since it won't be usable
// before then in IE6/7 (due to the necessary Iframe), recommended usage is
// to bind it inside a DOM ready handler.
// Override existing $.event.special.hashchange methods (allowing this plugin
// to be defined after jQuery BBQ in BBQ's source code).
special[ str_hashchange ] = $.extend( special[ str_hashchange ], {
// Called only when the first 'hashchange' event is bound to window.
setup: function() {
// If window.onhashchange is supported natively, there's nothing to do..
if ( supports_onhashchange ) { return false; }
// Otherwise, we need to create our own. And we don't want to call this
// until the user binds to the event, just in case they never do, since it
// will create a polling loop and possibly even a hidden Iframe.
$( fake_onhashchange.start );
},
// Called only when the last 'hashchange' event is unbound from window.
teardown: function() {
// If window.onhashchange is supported natively, there's nothing to do..
if ( supports_onhashchange ) { return false; }
// Otherwise, we need to stop ours (if possible).
$( fake_onhashchange.stop );
}
});
// fake_onhashchange does all the work of triggering the window.onhashchange
// event for browsers that don't natively support it, including creating a
// polling loop to watch for hash changes and in IE 6/7 creating a hidden
// Iframe to enable back and forward.
fake_onhashchange = (function() {
var self = {},
timeout_id,
// Remember the initial hash so it doesn't get triggered immediately.
last_hash = get_fragment(),
fn_retval = function( val ) { return val; },
history_set = fn_retval,
history_get = fn_retval;
// Start the polling loop.
self.start = function() {
timeout_id || poll();
};
// Stop the polling loop.
self.stop = function() {
timeout_id && clearTimeout( timeout_id );
timeout_id = undefined;
};
// This polling loop checks every $.fn.hashchange.delay milliseconds to see
// if location.hash has changed, and triggers the 'hashchange' event on
// window when necessary.
function poll() {
var hash = get_fragment(),
history_hash = history_get( last_hash );
if ( hash !== last_hash ) {
history_set( last_hash = hash, history_hash );
$(window).trigger( str_hashchange );
} else if ( history_hash !== last_hash ) {
location.href = location.href.replace( /#.*/, '' ) + history_hash;
}
timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay );
};
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
// vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
window.attachEvent && !window.addEventListener && !supports_onhashchange && (function() {
// Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8
// when running in "IE7 compatibility" mode.
var iframe,
iframe_src;
// When the event is bound and polling starts in IE 6/7, create a hidden
// Iframe for history handling.
self.start = function() {
if ( !iframe ) {
iframe_src = $.fn[ str_hashchange ].src;
iframe_src = iframe_src && iframe_src + get_fragment();
// Create hidden Iframe. Attempt to make Iframe as hidden as possible
// by using techniques from http://www.paciellogroup.com/blog/?p=604.
iframe = $('<iframe tabindex="-1" title="empty"/>').hide()
// When Iframe has completely loaded, initialize the history and
// start polling.
.one( 'load', function() {
iframe_src || history_set( get_fragment() );
poll();
})
// Load Iframe src if specified, otherwise nothing.
.attr( 'src', iframe_src || 'javascript:0' )
// Append Iframe after the end of the body to prevent unnecessary
// initial page scrolling (yes, this works).
.insertAfter( 'body' )[0].contentWindow;
// Whenever `document.title` changes, update the Iframe's title to
// prettify the back/next history menu entries. Since IE sometimes
// errors with "Unspecified error" the very first time this is set
// (yes, very useful) wrap this with a try/catch block.
doc.onpropertychange = function() {
try {
if ( event.propertyName === 'title' ) {
iframe.document.title = doc.title;
}
} catch(e) {}
};
}
};
// Override the "stop" method since an IE6/7 Iframe was created. Even
// if there are no longer any bound event handlers, the polling loop
// is still necessary for back/next to work at all!
self.stop = fn_retval;
// Get history by looking at the hidden Iframe's location.hash.
history_get = function() {
return get_fragment( iframe.location.href );
};
// Set a new history item by opening and then closing the Iframe
// document, *then* setting its location.hash. If document.domain has
// been set, update that as well.
history_set = function( hash, history_hash ) {
var iframe_doc = iframe.document,
domain = $.fn[ str_hashchange ].domain;
if ( hash !== history_hash ) {
// Update Iframe with any initial `document.title` that might be set.
iframe_doc.title = doc.title;
// Opening the Iframe's document after it has been closed is what
// actually adds a history entry.
iframe_doc.open();
// Set document.domain for the Iframe document as well, if necessary.
domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' );
iframe_doc.close();
// Update the Iframe's hash, for great justice.
iframe.location.hash = hash;
}
};
})();
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
return self;
})();
})(jQuery,this);
(function( $, undefined ) {
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
window.matchMedia = window.matchMedia || (function( doc, undefined ) {
var bool,
docElem = doc.documentElement,
refNode = docElem.firstElementChild || docElem.firstChild,
// fakeBody required for <FF4 when executed in <head>
fakeBody = doc.createElement( "body" ),
div = doc.createElement( "div" );
div.id = "mq-test-1";
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
return function(q){
div.innerHTML = "­<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>";
docElem.insertBefore( fakeBody, refNode );
bool = div.offsetWidth === 42;
docElem.removeChild( fakeBody );
return {
matches: bool,
media: q
};
};
}( document ));
// $.mobile.media uses matchMedia to return a boolean.
$.mobile.media = function( q ) {
return window.matchMedia( q ).matches;
};
})(jQuery);
(function( $, undefined ) {
var support = {
touch: "ontouchend" in document
};
$.mobile.support = $.mobile.support || {};
$.extend( $.support, support );
$.extend( $.mobile.support, support );
}( jQuery ));
(function( $, undefined ) {
$.extend( $.support, {
orientation: "orientation" in window && "onorientationchange" in window
});
}( jQuery ));
(function( $, undefined ) {
// thx Modernizr
function propExists( prop ) {
var uc_prop = prop.charAt( 0 ).toUpperCase() + prop.substr( 1 ),
props = ( prop + " " + vendors.join( uc_prop + " " ) + uc_prop ).split( " " );
for ( var v in props ) {
if ( fbCSS[ props[ v ] ] !== undefined ) {
return true;
}
}
}
var fakeBody = $( "<body>" ).prependTo( "html" ),
fbCSS = fakeBody[ 0 ].style,
vendors = [ "Webkit", "Moz", "O" ],
webos = "palmGetResource" in window, //only used to rule out scrollTop
opera = window.opera,
operamini = window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]",
bb = window.blackberry && !propExists( "-webkit-transform" ); //only used to rule out box shadow, as it's filled opaque on BB 5 and lower
function validStyle( prop, value, check_vend ) {
var div = document.createElement( 'div' ),
uc = function( txt ) {
return txt.charAt( 0 ).toUpperCase() + txt.substr( 1 );
},
vend_pref = function( vend ) {
if( vend === "" ) {
return "";
} else {
return "-" + vend.charAt( 0 ).toLowerCase() + vend.substr( 1 ) + "-";
}
},
check_style = function( vend ) {
var vend_prop = vend_pref( vend ) + prop + ": " + value + ";",
uc_vend = uc( vend ),
propStyle = uc_vend + ( uc_vend === "" ? prop : uc( prop ) );
div.setAttribute( "style", vend_prop );
if ( !!div.style[ propStyle ] ) {
ret = true;
}
},
check_vends = check_vend ? check_vend : vendors,
ret;
for( var i = 0; i < check_vends.length; i++ ) {
check_style( check_vends[i] );
}
return !!ret;
}
function transform3dTest() {
var mqProp = "transform-3d",
// Because the `translate3d` test below throws false positives in Android:
ret = $.mobile.media( "(-" + vendors.join( "-" + mqProp + "),(-" ) + "-" + mqProp + "),(" + mqProp + ")" );
if( ret ) {
return !!ret;
}
var el = document.createElement( "div" ),
transforms = {
// We’re omitting Opera for the time being; MS uses unprefixed.
'MozTransform':'-moz-transform',
'transform':'transform'
};
fakeBody.append( el );
for ( var t in transforms ) {
if( el.style[ t ] !== undefined ){
el.style[ t ] = 'translate3d( 100px, 1px, 1px )';
ret = window.getComputedStyle( el ).getPropertyValue( transforms[ t ] );
}
}
return ( !!ret && ret !== "none" );
}
// Test for dynamic-updating base tag support ( allows us to avoid href,src attr rewriting )
function baseTagTest() {
var fauxBase = location.protocol + "//" + location.host + location.pathname + "ui-dir/",
base = $( "head base" ),
fauxEle = null,
href = "",
link, rebase;
if ( !base.length ) {
base = fauxEle = $( "<base>", { "href": fauxBase }).appendTo( "head" );
} else {
href = base.attr( "href" );
}
link = $( "<a href='testurl' />" ).prependTo( fakeBody );
rebase = link[ 0 ].href;
base[ 0 ].href = href || location.pathname;
if ( fauxEle ) {
fauxEle.remove();
}
return rebase.indexOf( fauxBase ) === 0;
}
// Thanks Modernizr
function cssPointerEventsTest() {
var element = document.createElement( 'x' ),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if ( !( 'pointerEvents' in element.style ) ) {
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild( element );
supports = getComputedStyle &&
getComputedStyle( element, '' ).pointerEvents === 'auto';
documentElement.removeChild( element );
return !!supports;
}
function boundingRect() {
var div = document.createElement( "div" );
return typeof div.getBoundingClientRect !== "undefined";
}
// non-UA-based IE version check by James Padolsey, modified by jdalton - from http://gist.github.com/527683
// allows for inclusion of IE 6+, including Windows Mobile 7
$.extend( $.mobile, { browser: {} } );
$.mobile.browser.oldIE = (function() {
var v = 3,
div = document.createElement( "div" ),
a = div.all || [];
do {
div.innerHTML = "<!--[if gt IE " + ( ++v ) + "]><br><![endif]-->";
} while( a[0] );
return v > 4 ? v : !v;
})();
function fixedPosition() {
var w = window,
ua = navigator.userAgent,
platform = navigator.platform,
// Rendering engine is Webkit, and capture major version
wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ),
wkversion = !!wkmatch && wkmatch[ 1 ],
ffmatch = ua.match( /Fennec\/([0-9]+)/ ),
ffversion = !!ffmatch && ffmatch[ 1 ],
operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ ),
omversion = !!operammobilematch && operammobilematch[ 1 ];
if(
// iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5)
( ( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534 ) ||
// Opera Mini
( w.operamini && ({}).toString.call( w.operamini ) === "[object OperaMini]" ) ||
( operammobilematch && omversion < 7458 ) ||
//Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2)
( ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533 ) ||
// Firefox Mobile before 6.0 -
( ffversion && ffversion < 6 ) ||
// WebOS less than 3
( "palmGetResource" in window && wkversion && wkversion < 534 ) ||
// MeeGo
( ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1 ) ) {
return false;
}
return true;
}
$.extend( $.support, {
cssTransitions: "WebKitTransitionEvent" in window ||
validStyle( 'transition', 'height 100ms linear', [ "Webkit", "Moz", "" ] ) &&
!$.mobile.browser.oldIE && !opera,
// Note, Chrome for iOS has an extremely quirky implementation of popstate.
// We've chosen to take the shortest path to a bug fix here for issue #5426
// See the following link for information about the regex chosen
// https://developers.google.com/chrome/mobile/docs/user-agent#chrome_for_ios_user-agent
pushState: "pushState" in history &&
"replaceState" in history &&
// When running inside a FF iframe, calling replaceState causes an error
!( window.navigator.userAgent.indexOf( "Firefox" ) >= 0 && window.top !== window ) &&
( window.navigator.userAgent.search(/CriOS/) === -1 ),
mediaquery: $.mobile.media( "only all" ),
cssPseudoElement: !!propExists( "content" ),
touchOverflow: !!propExists( "overflowScrolling" ),
cssTransform3d: transform3dTest(),
boxShadow: !!propExists( "boxShadow" ) && !bb,
fixedPosition: fixedPosition(),
scrollTop: ("pageXOffset" in window ||
"scrollTop" in document.documentElement ||
"scrollTop" in fakeBody[ 0 ]) && !webos && !operamini,
dynamicBaseTag: baseTagTest(),
cssPointerEvents: cssPointerEventsTest(),
boundingRect: boundingRect()
});
fakeBody.remove();
// $.mobile.ajaxBlacklist is used to override ajaxEnabled on platforms that have known conflicts with hash history updates (BB5, Symbian)
// or that generally work better browsing in regular http for full page refreshes (Opera Mini)
// Note: This detection below is used as a last resort.
// We recommend only using these detection methods when all other more reliable/forward-looking approaches are not possible
var nokiaLTE7_3 = (function() {
var ua = window.navigator.userAgent;
//The following is an attempt to match Nokia browsers that are running Symbian/s60, with webkit, version 7.3 or older
return ua.indexOf( "Nokia" ) > -1 &&
( ua.indexOf( "Symbian/3" ) > -1 || ua.indexOf( "Series60/5" ) > -1 ) &&
ua.indexOf( "AppleWebKit" ) > -1 &&
ua.match( /(BrowserNG|NokiaBrowser)\/7\.[0-3]/ );
})();
// Support conditions that must be met in order to proceed
// default enhanced qualifications are media query support OR IE 7+
$.mobile.gradeA = function() {
return ( $.support.mediaquery || $.mobile.browser.oldIE && $.mobile.browser.oldIE >= 7 ) && ( $.support.boundingRect || $.fn.jquery.match(/1\.[0-7+]\.[0-9+]?/) !== null );
};
$.mobile.ajaxBlacklist =
// BlackBerry browsers, pre-webkit
window.blackberry && !window.WebKitPoint ||
// Opera Mini
operamini ||
// Symbian webkits pre 7.3
nokiaLTE7_3;
// Lastly, this workaround is the only way we've found so far to get pre 7.3 Symbian webkit devices
// to render the stylesheets when they're referenced before this script, as we'd recommend doing.
// This simply reappends the CSS in place, which for some reason makes it apply
if ( nokiaLTE7_3 ) {
$(function() {
$( "head link[rel='stylesheet']" ).attr( "rel", "alternate stylesheet" ).attr( "rel", "stylesheet" );
});
}
// For ruling out shadows via css
if ( !$.support.boxShadow ) {
$( "html" ).addClass( "ui-mobile-nosupport-boxshadow" );
}
})( jQuery );
(function( $, undefined ) {
var $win = $.mobile.window, self, history;
$.event.special.navigate = self = {
bound: false,
pushStateEnabled: true,
originalEventName: undefined,
// If pushstate support is present and push state support is defined to
// be true on the mobile namespace.
isPushStateEnabled: function() {
return $.support.pushState &&
$.mobile.pushStateEnabled === true &&
this.isHashChangeEnabled();
},
// !! assumes mobile namespace is present
isHashChangeEnabled: function() {
return $.mobile.hashListeningEnabled === true;
},
// TODO a lot of duplication between popstate and hashchange
popstate: function( event ) {
var newEvent = new $.Event( "navigate" ),
beforeNavigate = new $.Event( "beforenavigate" ),
state = event.originalEvent.state || {},
href = location.href;
$win.trigger( beforeNavigate );
if( beforeNavigate.isDefaultPrevented() ){
return;
}
if( event.historyState ){
$.extend(state, event.historyState);
}
// Make sure the original event is tracked for the end
// user to inspect incase they want to do something special
newEvent.originalEvent = event;
// NOTE we let the current stack unwind because any assignment to
// location.hash will stop the world and run this event handler. By
// doing this we create a similar behavior to hashchange on hash
// assignment
setTimeout(function() {
$win.trigger( newEvent, {
state: state
});
}, 0);
},
hashchange: function( event, data ) {
var newEvent = new $.Event( "navigate" ),
beforeNavigate = new $.Event( "beforenavigate" );
$win.trigger( beforeNavigate );
if( beforeNavigate.isDefaultPrevented() ){
return;
}
// Make sure the original event is tracked for the end
// user to inspect incase they want to do something special
newEvent.originalEvent = event;
// Trigger the hashchange with state provided by the user
// that altered the hash
$win.trigger( newEvent, {
// Users that want to fully normalize the two events
// will need to do history management down the stack and
// add the state to the event before this binding is fired
// TODO consider allowing for the explicit addition of callbacks
// to be fired before this value is set to avoid event timing issues
state: event.hashchangeState || {}
});
},
// TODO We really only want to set this up once
// but I'm not clear if there's a beter way to achieve
// this with the jQuery special event structure
setup: function( data, namespaces ) {
if( self.bound ) {
return;
}
self.bound = true;
if( self.isPushStateEnabled() ) {
self.originalEventName = "popstate";
$win.bind( "popstate.navigate", self.popstate );
} else if ( self.isHashChangeEnabled() ){
self.originalEventName = "hashchange";
$win.bind( "hashchange.navigate", self.hashchange );
}
}
};
})( jQuery );
(function( $, undefined ) {
var path, documentBase, $base, dialogHashKey = "&ui-state=dialog";
$.mobile.path = path = {
uiStateKey: "&ui-state",
// This scary looking regular expression parses an absolute URL or its relative
// variants (protocol, site, document, query, and hash), into the various
// components (protocol, host, path, query, fragment, etc that make up the
// URL as well as some other commonly used sub-parts. When used with RegExp.exec()
// or String.match, it parses the URL into a results array that looks like this:
//
// [0]: http://jblas:[email protected]:8080/mail/inbox?msg=1234&type=unread#msg-content
// [1]: http://jblas:[email protected]:8080/mail/inbox?msg=1234&type=unread
// [2]: http://jblas:[email protected]:8080/mail/inbox
// [3]: http://jblas:[email protected]:8080
// [4]: http:
// [5]: //
// [6]: jblas:[email protected]:8080
// [7]: jblas:password
// [8]: jblas
// [9]: password
// [10]: mycompany.com:8080
// [11]: mycompany.com
// [12]: 8080
// [13]: /mail/inbox
// [14]: /mail/
// [15]: inbox
// [16]: ?msg=1234&type=unread
// [17]: #msg-content
//
urlParseRE: /^\s*(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/,
// Abstraction to address xss (Issue #4787) by removing the authority in
// browsers that auto decode it. All references to location.href should be
// replaced with a call to this method so that it can be dealt with properly here
getLocation: function( url ) {
var uri = url ? this.parseUrl( url ) : location,
hash = this.parseUrl( url || location.href ).hash;
// mimic the browser with an empty string when the hash is empty
hash = hash === "#" ? "" : hash;
// Make sure to parse the url or the location object for the hash because using location.hash
// is autodecoded in firefox, the rest of the url should be from the object (location unless
// we're testing) to avoid the inclusion of the authority
return uri.protocol + "//" + uri.host + uri.pathname + uri.search + hash;
},
parseLocation: function() {
return this.parseUrl( this.getLocation() );
},
//Parse a URL into a structure that allows easy access to
//all of the URL components by name.
parseUrl: function( url ) {
// If we're passed an object, we'll assume that it is
// a parsed url object and just return it back to the caller.
if ( $.type( url ) === "object" ) {
return url;
}
var matches = path.urlParseRE.exec( url || "" ) || [];
// Create an object that allows the caller to access the sub-matches
// by name. Note that IE returns an empty string instead of undefined,
// like all other browsers do, so we normalize everything so its consistent
// no matter what browser we're running on.
return {
href: matches[ 0 ] || "",
hrefNoHash: matches[ 1 ] || "",
hrefNoSearch: matches[ 2 ] || "",
domain: matches[ 3 ] || "",
protocol: matches[ 4 ] || "",
doubleSlash: matches[ 5 ] || "",
authority: matches[ 6 ] || "",
username: matches[ 8 ] || "",
password: matches[ 9 ] || "",
host: matches[ 10 ] || "",
hostname: matches[ 11 ] || "",
port: matches[ 12 ] || "",
pathname: matches[ 13 ] || "",
directory: matches[ 14 ] || "",
filename: matches[ 15 ] || "",
search: matches[ 16 ] || "",
hash: matches[ 17 ] || ""
};
},
//Turn relPath into an asbolute path. absPath is
//an optional absolute path which describes what
//relPath is relative to.
makePathAbsolute: function( relPath, absPath ) {
if ( relPath && relPath.charAt( 0 ) === "/" ) {
return relPath;
}
relPath = relPath || "";
absPath = absPath ? absPath.replace( /^\/|(\/[^\/]*|[^\/]+)$/g, "" ) : "";
var absStack = absPath ? absPath.split( "/" ) : [],
relStack = relPath.split( "/" );
for ( var i = 0; i < relStack.length; i++ ) {
var d = relStack[ i ];
switch ( d ) {
case ".":
break;
case "..":
if ( absStack.length ) {
absStack.pop();
}
break;
default:
absStack.push( d );
break;
}
}
return "/" + absStack.join( "/" );
},
//Returns true if both urls have the same domain.
isSameDomain: function( absUrl1, absUrl2 ) {
return path.parseUrl( absUrl1 ).domain === path.parseUrl( absUrl2 ).domain;
},
//Returns true for any relative variant.
isRelativeUrl: function( url ) {
// All relative Url variants have one thing in common, no protocol.
return path.parseUrl( url ).protocol === "";
},
//Returns true for an absolute url.
isAbsoluteUrl: function( url ) {
return path.parseUrl( url ).protocol !== "";
},
//Turn the specified realtive URL into an absolute one. This function
//can handle all relative variants (protocol, site, document, query, fragment).
makeUrlAbsolute: function( relUrl, absUrl ) {
if ( !path.isRelativeUrl( relUrl ) ) {
return relUrl;
}
if ( absUrl === undefined ) {
absUrl = this.documentBase;
}
var relObj = path.parseUrl( relUrl ),
absObj = path.parseUrl( absUrl ),
protocol = relObj.protocol || absObj.protocol,
doubleSlash = relObj.protocol ? relObj.doubleSlash : ( relObj.doubleSlash || absObj.doubleSlash ),
authority = relObj.authority || absObj.authority,
hasPath = relObj.pathname !== "",
pathname = path.makePathAbsolute( relObj.pathname || absObj.filename, absObj.pathname ),
search = relObj.search || ( !hasPath && absObj.search ) || "",
hash = relObj.hash;
return protocol + doubleSlash + authority + pathname + search + hash;
},
//Add search (aka query) params to the specified url.
addSearchParams: function( url, params ) {
var u = path.parseUrl( url ),
p = ( typeof params === "object" ) ? $.param( params ) : params,
s = u.search || "?";
return u.hrefNoSearch + s + ( s.charAt( s.length - 1 ) !== "?" ? "&" : "" ) + p + ( u.hash || "" );
},
convertUrlToDataUrl: function( absUrl ) {
var u = path.parseUrl( absUrl );
if ( path.isEmbeddedPage( u ) ) {
// For embedded pages, remove the dialog hash key as in getFilePath(),
// and remove otherwise the Data Url won't match the id of the embedded Page.
return u.hash
.split( dialogHashKey )[0]
.replace( /^#/, "" )
.replace( /\?.*$/, "" );
} else if ( path.isSameDomain( u, this.documentBase ) ) {
return u.hrefNoHash.replace( this.documentBase.domain, "" ).split( dialogHashKey )[0];
}
return window.decodeURIComponent(absUrl);
},
//get path from current hash, or from a file path
get: function( newPath ) {
if ( newPath === undefined ) {
newPath = path.parseLocation().hash;
}
return path.stripHash( newPath ).replace( /[^\/]*\.[^\/*]+$/, '' );
},
//set location hash to path
set: function( path ) {
location.hash = path;
},
//test if a given url (string) is a path
//NOTE might be exceptionally naive
isPath: function( url ) {
return ( /\// ).test( url );
},
//return a url path with the window's location protocol/hostname/pathname removed
clean: function( url ) {
return url.replace( this.documentBase.domain, "" );
},
//just return the url without an initial #
stripHash: function( url ) {
return url.replace( /^#/, "" );
},
stripQueryParams: function( url ) {
return url.replace( /\?.*$/, "" );
},
//remove the preceding hash, any query params, and dialog notations
cleanHash: function( hash ) {
return path.stripHash( hash.replace( /\?.*$/, "" ).replace( dialogHashKey, "" ) );
},
isHashValid: function( hash ) {
return ( /^#[^#]+$/ ).test( hash );
},
//check whether a url is referencing the same domain, or an external domain or different protocol
//could be mailto, etc
isExternal: function( url ) {
var u = path.parseUrl( url );
return u.protocol && u.domain !== this.documentUrl.domain ? true : false;
},
hasProtocol: function( url ) {
return ( /^(:?\w+:)/ ).test( url );
},
isEmbeddedPage: function( url ) {
var u = path.parseUrl( url );
//if the path is absolute, then we need to compare the url against
//both the this.documentUrl and the documentBase. The main reason for this
//is that links embedded within external documents will refer to the
//application document, whereas links embedded within the application
//document will be resolved against the document base.
if ( u.protocol !== "" ) {
return ( !this.isPath(u.hash) && u.hash && ( u.hrefNoHash === this.documentUrl.hrefNoHash || ( this.documentBaseDiffers && u.hrefNoHash === this.documentBase.hrefNoHash ) ) );
}
return ( /^#/ ).test( u.href );
},
squash: function( url, resolutionUrl ) {
var state, href, cleanedUrl, search, stateIndex,
isPath = this.isPath( url ),
uri = this.parseUrl( url ),
preservedHash = uri.hash,
uiState = "";
// produce a url against which we can resole the provided path
resolutionUrl = resolutionUrl || (path.isPath(url) ? path.getLocation() : path.getDocumentUrl());
// If the url is anything but a simple string, remove any preceding hash
// eg #foo/bar -> foo/bar
// #foo -> #foo
cleanedUrl = isPath ? path.stripHash( url ) : url;
// If the url is a full url with a hash check if the parsed hash is a path
// if it is, strip the #, and use it otherwise continue without change
cleanedUrl = path.isPath( uri.hash ) ? path.stripHash( uri.hash ) : cleanedUrl;
// Split the UI State keys off the href
stateIndex = cleanedUrl.indexOf( this.uiStateKey );
// store the ui state keys for use
if( stateIndex > -1 ){
uiState = cleanedUrl.slice( stateIndex );
cleanedUrl = cleanedUrl.slice( 0, stateIndex );
}
// make the cleanedUrl absolute relative to the resolution url
href = path.makeUrlAbsolute( cleanedUrl, resolutionUrl );
// grab the search from the resolved url since parsing from
// the passed url may not yield the correct result
search = this.parseUrl( href ).search;
// TODO all this crap is terrible, clean it up
if ( isPath ) {
// reject the hash if it's a path or it's just a dialog key
if( path.isPath( preservedHash ) || preservedHash.replace("#", "").indexOf( this.uiStateKey ) === 0) {
preservedHash = "";
}
// Append the UI State keys where it exists and it's been removed
// from the url
if( uiState && preservedHash.indexOf( this.uiStateKey ) === -1){
preservedHash += uiState;
}
// make sure that pound is on the front of the hash
if( preservedHash.indexOf( "#" ) === -1 && preservedHash !== "" ){
preservedHash = "#" + preservedHash;
}
// reconstruct each of the pieces with the new search string and hash
href = path.parseUrl( href );
href = href.protocol + "//" + href.host + href.pathname + search + preservedHash;
} else {
href += href.indexOf( "#" ) > -1 ? uiState : "#" + uiState;
}
return href;
},
isPreservableHash: function( hash ) {
return hash.replace( "#", "" ).indexOf( this.uiStateKey ) === 0;
}
};
path.documentUrl = path.parseLocation();
$base = $( "head" ).find( "base" );
path.documentBase = $base.length ?
path.parseUrl( path.makeUrlAbsolute( $base.attr( "href" ), path.documentUrl.href ) ) :
path.documentUrl;
path.documentBaseDiffers = (path.documentUrl.hrefNoHash !== path.documentBase.hrefNoHash);
//return the original document url
path.getDocumentUrl = function( asParsedObject ) {
return asParsedObject ? $.extend( {}, path.documentUrl ) : path.documentUrl.href;
};
//return the original document base url
path.getDocumentBase = function( asParsedObject ) {
return asParsedObject ? $.extend( {}, path.documentBase ) : path.documentBase.href;
};
})( jQuery );
(function( $, undefined ) {
var path = $.mobile.path;
$.mobile.History = function( stack, index ) {
this.stack = stack || [];
this.activeIndex = index || 0;
};
$.extend($.mobile.History.prototype, {
getActive: function() {
return this.stack[ this.activeIndex ];
},
getLast: function() {
return this.stack[ this.previousIndex ];
},
getNext: function() {
return this.stack[ this.activeIndex + 1 ];
},
getPrev: function() {
return this.stack[ this.activeIndex - 1 ];
},
// addNew is used whenever a new page is added
add: function( url, data ){
data = data || {};
//if there's forward history, wipe it
if ( this.getNext() ) {
this.clearForward();
}
// if the hash is included in the data make sure the shape
// is consistent for comparison
if( data.hash && data.hash.indexOf( "#" ) === -1) {
data.hash = "#" + data.hash;
}
data.url = url;
this.stack.push( data );
this.activeIndex = this.stack.length - 1;
},
//wipe urls ahead of active index
clearForward: function() {
this.stack = this.stack.slice( 0, this.activeIndex + 1 );
},
find: function( url, stack, earlyReturn ) {
stack = stack || this.stack;
var entry, i, length = stack.length, index;
for ( i = 0; i < length; i++ ) {
entry = stack[i];
if ( decodeURIComponent(url) === decodeURIComponent(entry.url) ||
decodeURIComponent(url) === decodeURIComponent(entry.hash) ) {
index = i;
if( earlyReturn ) {
return index;
}
}
}
return index;
},
closest: function( url ) {
var closest, a = this.activeIndex;
// First, take the slice of the history stack before the current index and search
// for a url match. If one is found, we'll avoid avoid looking through forward history
// NOTE the preference for backward history movement is driven by the fact that
// most mobile browsers only have a dedicated back button, and users rarely use
// the forward button in desktop browser anyhow
closest = this.find( url, this.stack.slice(0, a) );
// If nothing was found in backward history check forward. The `true`
// value passed as the third parameter causes the find method to break
// on the first match in the forward history slice. The starting index
// of the slice must then be added to the result to get the element index
// in the original history stack :( :(
//
// TODO this is hyper confusing and should be cleaned up (ugh so bad)
if( closest === undefined ) {
closest = this.find( url, this.stack.slice(a), true );
closest = closest === undefined ? closest : closest + a;
}
return closest;
},
direct: function( opts ) {
var newActiveIndex = this.closest( opts.url ), a = this.activeIndex;
// save new page index, null check to prevent falsey 0 result
// record the previous index for reference
if( newActiveIndex !== undefined ) {
this.activeIndex = newActiveIndex;
this.previousIndex = a;
}
// invoke callbacks where appropriate
//
// TODO this is also convoluted and confusing
if ( newActiveIndex < a ) {
( opts.present || opts.back || $.noop )( this.getActive(), 'back' );
} else if ( newActiveIndex > a ) {
( opts.present || opts.forward || $.noop )( this.getActive(), 'forward' );
} else if ( newActiveIndex === undefined && opts.missing ){
opts.missing( this.getActive() );
}
}
});
})( jQuery );
(function( $, undefined ) {
var path = $.mobile.path,
initialHref = location.href;
$.mobile.Navigator = function( history ) {
this.history = history;
this.ignoreInitialHashChange = true;
$.mobile.window.bind({
"popstate.history": $.proxy( this.popstate, this ),
"hashchange.history": $.proxy( this.hashchange, this )
});
};
$.extend($.mobile.Navigator.prototype, {
squash: function( url, data ) {
var state, href, hash = path.isPath(url) ? path.stripHash(url) : url;
href = path.squash( url );
// make sure to provide this information when it isn't explicitly set in the
// data object that was passed to the squash method
state = $.extend({
hash: hash,
url: href
}, data);
// replace the current url with the new href and store the state
// Note that in some cases we might be replacing an url with the
// same url. We do this anyways because we need to make sure that
// all of our history entries have a state object associated with
// them. This allows us to work around the case where $.mobile.back()
// is called to transition from an external page to an embedded page.
// In that particular case, a hashchange event is *NOT* generated by the browser.
// Ensuring each history entry has a state object means that onPopState()
// will always trigger our hashchange callback even when a hashchange event
// is not fired.
window.history.replaceState( state, state.title || document.title, href );
return state;
},
hash: function( url, href ) {
var parsed, loc, hash;
// Grab the hash for recording. If the passed url is a path
// we used the parsed version of the squashed url to reconstruct,
// otherwise we assume it's a hash and store it directly
parsed = path.parseUrl( url );
loc = path.parseLocation();
if( loc.pathname + loc.search === parsed.pathname + parsed.search ) {
// If the pathname and search of the passed url is identical to the current loc
// then we must use the hash. Otherwise there will be no event
// eg, url = "/foo/bar?baz#bang", location.href = "http://example.com/foo/bar?baz"
hash = parsed.hash ? parsed.hash : parsed.pathname + parsed.search;
} else if ( path.isPath(url) ) {
var resolved = path.parseUrl( href );
// If the passed url is a path, make it domain relative and remove any trailing hash
hash = resolved.pathname + resolved.search + (path.isPreservableHash( resolved.hash )? resolved.hash.replace( "#", "" ) : "");
} else {
hash = url;
}
return hash;
},
// TODO reconsider name
go: function( url, data, noEvents ) {
var state, href, hash, popstateEvent,
isPopStateEvent = $.event.special.navigate.isPushStateEnabled();
// Get the url as it would look squashed on to the current resolution url
href = path.squash( url );
// sort out what the hash sould be from the url
hash = this.hash( url, href );
// Here we prevent the next hash change or popstate event from doing any
// history management. In the case of hashchange we don't swallow it
// if there will be no hashchange fired (since that won't reset the value)
// and will swallow the following hashchange
if( noEvents && hash !== path.stripHash(path.parseLocation().hash) ) {
this.preventNextHashChange = noEvents;
}
// IMPORTANT in the case where popstate is supported the event will be triggered
// directly, stopping further execution - ie, interupting the flow of this
// method call to fire bindings at this expression. Below the navigate method
// there is a binding to catch this event and stop its propagation.
//
// We then trigger a new popstate event on the window with a null state
// so that the navigate events can conclude their work properly
//
// if the url is a path we want to preserve the query params that are available on
// the current url.
this.preventHashAssignPopState = true;
window.location.hash = hash;
// If popstate is enabled and the browser triggers `popstate` events when the hash
// is set (this often happens immediately in browsers like Chrome), then the
// this flag will be set to false already. If it's a browser that does not trigger
// a `popstate` on hash assignement or `replaceState` then we need avoid the branch
// that swallows the event created by the popstate generated by the hash assignment
// At the time of this writing this happens with Opera 12 and some version of IE
this.preventHashAssignPopState = false;
state = $.extend({
url: href,
hash: hash,
title: document.title
}, data);
if( isPopStateEvent ) {
popstateEvent = new $.Event( "popstate" );
popstateEvent.originalEvent = {
type: "popstate",
state: null
};
this.squash( url, state );
// Trigger a new faux popstate event to replace the one that we
// caught that was triggered by the hash setting above.
if( !noEvents ) {
this.ignorePopState = true;
$.mobile.window.trigger( popstateEvent );
}
}
// record the history entry so that the information can be included
// in hashchange event driven navigate events in a similar fashion to
// the state that's provided by popstate
this.history.add( state.url, state );
},
// This binding is intended to catch the popstate events that are fired
// when execution of the `$.navigate` method stops at window.location.hash = url;
// and completely prevent them from propagating. The popstate event will then be
// retriggered after execution resumes
//
// TODO grab the original event here and use it for the synthetic event in the
// second half of the navigate execution that will follow this binding
popstate: function( event ) {
var active, hash, state, closestIndex;
// Partly to support our test suite which manually alters the support
// value to test hashchange. Partly to prevent all around weirdness
if( !$.event.special.navigate.isPushStateEnabled() ){
return;
}
// If this is the popstate triggered by the actual alteration of the hash
// prevent it completely. History is tracked manually
if( this.preventHashAssignPopState ) {
this.preventHashAssignPopState = false;
event.stopImmediatePropagation();
return;
}
// if this is the popstate triggered after the `replaceState` call in the go
// method, then simply ignore it. The history entry has already been captured
if( this.ignorePopState ) {
this.ignorePopState = false;
return;
}
// If there is no state, and the history stack length is one were
// probably getting the page load popstate fired by browsers like chrome
// avoid it and set the one time flag to false.
// TODO: Do we really need all these conditions? Comparing location hrefs
// should be sufficient.
if( !event.originalEvent.state &&
this.history.stack.length === 1 &&
this.ignoreInitialHashChange ) {
this.ignoreInitialHashChange = false;
if ( location.href === initialHref ) {
event.preventDefault();
return;
}
}
// account for direct manipulation of the hash. That is, we will receive a popstate
// when the hash is changed by assignment, and it won't have a state associated. We
// then need to squash the hash. See below for handling of hash assignment that
// matches an existing history entry
// TODO it might be better to only add to the history stack
// when the hash is adjacent to the active history entry
hash = path.parseLocation().hash;
if( !event.originalEvent.state && hash ) {
// squash the hash that's been assigned on the URL with replaceState
// also grab the resulting state object for storage
state = this.squash( hash );
// record the new hash as an additional history entry
// to match the browser's treatment of hash assignment
this.history.add( state.url, state );
// pass the newly created state information
// along with the event
event.historyState = state;
// do not alter history, we've added a new history entry
// so we know where we are
return;
}
// If all else fails this is a popstate that comes from the back or forward buttons
// make sure to set the state of our history stack properly, and record the directionality
this.history.direct({
url: (event.originalEvent.state || {}).url || hash,
// When the url is either forward or backward in history include the entry
// as data on the event object for merging as data in the navigate event
present: function( historyEntry, direction ) {
// make sure to create a new object to pass down as the navigate event data
event.historyState = $.extend({}, historyEntry);
event.historyState.direction = direction;
}
});
},
// NOTE must bind before `navigate` special event hashchange binding otherwise the
// navigation data won't be attached to the hashchange event in time for those
// bindings to attach it to the `navigate` special event
// TODO add a check here that `hashchange.navigate` is bound already otherwise it's
// broken (exception?)
hashchange: function( event ) {
var history, hash;
// If hashchange listening is explicitly disabled or pushstate is supported
// avoid making use of the hashchange handler.
if(!$.event.special.navigate.isHashChangeEnabled() ||
$.event.special.navigate.isPushStateEnabled() ) {
return;
}
// On occasion explicitly want to prevent the next hash from propogating because we only
// with to alter the url to represent the new state do so here
if( this.preventNextHashChange ){
this.preventNextHashChange = false;
event.stopImmediatePropagation();
return;
}
history = this.history;
hash = path.parseLocation().hash;
// If this is a hashchange caused by the back or forward button
// make sure to set the state of our history stack properly
this.history.direct({
url: hash,
// When the url is either forward or backward in history include the entry
// as data on the event object for merging as data in the navigate event
present: function( historyEntry, direction ) {
// make sure to create a new object to pass down as the navigate event data
event.hashchangeState = $.extend({}, historyEntry);
event.hashchangeState.direction = direction;
},
// When we don't find a hash in our history clearly we're aiming to go there
// record the entry as new for future traversal
//
// NOTE it's not entirely clear that this is the right thing to do given that we
// can't know the users intention. It might be better to explicitly _not_
// support location.hash assignment in preference to $.navigate calls
// TODO first arg to add should be the href, but it causes issues in identifying
// embeded pages
missing: function() {
history.add( hash, {
hash: hash,
title: document.title
});
}
});
}
});
})( jQuery );
(function( $, undefined ) {
// TODO consider queueing navigation activity until previous activities have completed
// so that end users don't have to think about it. Punting for now
// TODO !! move the event bindings into callbacks on the navigate event
$.mobile.navigate = function( url, data, noEvents ) {
$.mobile.navigate.navigator.go( url, data, noEvents );
};
// expose the history on the navigate method in anticipation of full integration with
// existing navigation functionalty that is tightly coupled to the history information
$.mobile.navigate.history = new $.mobile.History();
// instantiate an instance of the navigator for use within the $.navigate method
$.mobile.navigate.navigator = new $.mobile.Navigator( $.mobile.navigate.history );
var loc = $.mobile.path.parseLocation();
$.mobile.navigate.history.add( loc.href, {hash: loc.hash} );
})( jQuery );
// This plugin is an experiment for abstracting away the touch and mouse
// events so that developers don't have to worry about which method of input
// the device their document is loaded on supports.
//
// The idea here is to allow the developer to register listeners for the
// basic mouse events, such as mousedown, mousemove, mouseup, and click,
// and the plugin will take care of registering the correct listeners
// behind the scenes to invoke the listener at the fastest possible time
// for that device, while still retaining the order of event firing in
// the traditional mouse environment, should multiple handlers be registered
// on the same element for different events.
//
// The current version exposes the following virtual events to jQuery bind methods:
// "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel"
(function( $, window, document, undefined ) {
var dataPropertyName = "virtualMouseBindings",
touchTargetPropertyName = "virtualTouchID",
virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split( " " ),
touchEventProps = "clientX clientY pageX pageY screenX screenY".split( " " ),
mouseHookProps = $.event.mouseHooks ? $.event.mouseHooks.props : [],
mouseEventProps = $.event.props.concat( mouseHookProps ),
activeDocHandlers = {},
resetTimerID = 0,
startX = 0,
startY = 0,
didScroll = false,
clickBlockList = [],
blockMouseTriggers = false,
blockTouchTriggers = false,
eventCaptureSupported = "addEventListener" in document,
$document = $( document ),
nextTouchID = 1,
lastTouchID = 0, threshold;
$.vmouse = {
moveDistanceThreshold: 10,
clickDistanceThreshold: 10,
resetTimerDuration: 1500
};
function getNativeEvent( event ) {
while ( event && typeof event.originalEvent !== "undefined" ) {
event = event.originalEvent;
}
return event;
}
function createVirtualEvent( event, eventType ) {
var t = event.type,
oe, props, ne, prop, ct, touch, i, j, len;
event = $.Event( event );
event.type = eventType;
oe = event.originalEvent;
props = $.event.props;
// addresses separation of $.event.props in to $.event.mouseHook.props and Issue 3280
// https://github.com/jquery/jquery-mobile/issues/3280
if ( t.search( /^(mouse|click)/ ) > -1 ) {
props = mouseEventProps;
}
// copy original event properties over to the new event
// this would happen if we could call $.event.fix instead of $.Event
// but we don't have a way to force an event to be fixed multiple times
if ( oe ) {
for ( i = props.length, prop; i; ) {
prop = props[ --i ];
event[ prop ] = oe[ prop ];
}
}
// make sure that if the mouse and click virtual events are generated
// without a .which one is defined
if ( t.search(/mouse(down|up)|click/) > -1 && !event.which ) {
event.which = 1;
}
if ( t.search(/^touch/) !== -1 ) {
ne = getNativeEvent( oe );
t = ne.touches;
ct = ne.changedTouches;
touch = ( t && t.length ) ? t[0] : ( ( ct && ct.length ) ? ct[ 0 ] : undefined );
if ( touch ) {
for ( j = 0, len = touchEventProps.length; j < len; j++) {
prop = touchEventProps[ j ];
event[ prop ] = touch[ prop ];
}
}
}
return event;
}
function getVirtualBindingFlags( element ) {
var flags = {},
b, k;
while ( element ) {
b = $.data( element, dataPropertyName );
for ( k in b ) {
if ( b[ k ] ) {
flags[ k ] = flags.hasVirtualBinding = true;
}
}
element = element.parentNode;
}
return flags;
}
function getClosestElementWithVirtualBinding( element, eventType ) {
var b;
while ( element ) {
b = $.data( element, dataPropertyName );
if ( b && ( !eventType || b[ eventType ] ) ) {
return element;
}
element = element.parentNode;
}
return null;
}
function enableTouchBindings() {
blockTouchTriggers = false;
}
function disableTouchBindings() {
blockTouchTriggers = true;
}
function enableMouseBindings() {
lastTouchID = 0;
clickBlockList.length = 0;
blockMouseTriggers = false;
// When mouse bindings are enabled, our
// touch bindings are disabled.
disableTouchBindings();
}
function disableMouseBindings() {
// When mouse bindings are disabled, our
// touch bindings are enabled.
enableTouchBindings();
}
function startResetTimer() {
clearResetTimer();
resetTimerID = setTimeout( function() {
resetTimerID = 0;
enableMouseBindings();
}, $.vmouse.resetTimerDuration );
}
function clearResetTimer() {
if ( resetTimerID ) {
clearTimeout( resetTimerID );
resetTimerID = 0;
}
}
function triggerVirtualEvent( eventType, event, flags ) {
var ve;
if ( ( flags && flags[ eventType ] ) ||
( !flags && getClosestElementWithVirtualBinding( event.target, eventType ) ) ) {
ve = createVirtualEvent( event, eventType );
$( event.target).trigger( ve );
}
return ve;
}
function mouseEventCallback( event ) {
var touchID = $.data( event.target, touchTargetPropertyName );
if ( !blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID ) ) {
var ve = triggerVirtualEvent( "v" + event.type, event );
if ( ve ) {
if ( ve.isDefaultPrevented() ) {
event.preventDefault();
}
if ( ve.isPropagationStopped() ) {
event.stopPropagation();
}
if ( ve.isImmediatePropagationStopped() ) {
event.stopImmediatePropagation();
}
}
}
}
function handleTouchStart( event ) {
var touches = getNativeEvent( event ).touches,
target, flags;
if ( touches && touches.length === 1 ) {
target = event.target;
flags = getVirtualBindingFlags( target );
if ( flags.hasVirtualBinding ) {
lastTouchID = nextTouchID++;
$.data( target, touchTargetPropertyName, lastTouchID );
clearResetTimer();
disableMouseBindings();
didScroll = false;
var t = getNativeEvent( event ).touches[ 0 ];
startX = t.pageX;
startY = t.pageY;
triggerVirtualEvent( "vmouseover", event, flags );
triggerVirtualEvent( "vmousedown", event, flags );
}
}
}
function handleScroll( event ) {
if ( blockTouchTriggers ) {
return;
}
if ( !didScroll ) {
triggerVirtualEvent( "vmousecancel", event, getVirtualBindingFlags( event.target ) );
}
didScroll = true;
startResetTimer();
}
function handleTouchMove( event ) {
if ( blockTouchTriggers ) {
return;
}
var t = getNativeEvent( event ).touches[ 0 ],
didCancel = didScroll,
moveThreshold = $.vmouse.moveDistanceThreshold,
flags = getVirtualBindingFlags( event.target );
didScroll = didScroll ||
( Math.abs( t.pageX - startX ) > moveThreshold ||
Math.abs( t.pageY - startY ) > moveThreshold );
if ( didScroll && !didCancel ) {
triggerVirtualEvent( "vmousecancel", event, flags );
}
triggerVirtualEvent( "vmousemove", event, flags );
startResetTimer();
}
function handleTouchEnd( event ) {
if ( blockTouchTriggers ) {
return;
}
disableTouchBindings();
var flags = getVirtualBindingFlags( event.target ),
t;
triggerVirtualEvent( "vmouseup", event, flags );
if ( !didScroll ) {
var ve = triggerVirtualEvent( "vclick", event, flags );
if ( ve && ve.isDefaultPrevented() ) {
// The target of the mouse events that follow the touchend
// event don't necessarily match the target used during the
// touch. This means we need to rely on coordinates for blocking
// any click that is generated.
t = getNativeEvent( event ).changedTouches[ 0 ];
clickBlockList.push({
touchID: lastTouchID,
x: t.clientX,
y: t.clientY
});
// Prevent any mouse events that follow from triggering
// virtual event notifications.
blockMouseTriggers = true;
}
}
triggerVirtualEvent( "vmouseout", event, flags);
didScroll = false;
startResetTimer();
}
function hasVirtualBindings( ele ) {
var bindings = $.data( ele, dataPropertyName ),
k;
if ( bindings ) {
for ( k in bindings ) {
if ( bindings[ k ] ) {
return true;
}
}
}
return false;
}
function dummyMouseHandler() {}
function getSpecialEventObject( eventType ) {
var realType = eventType.substr( 1 );
return {
setup: function( data, namespace ) {
// If this is the first virtual mouse binding for this element,
// add a bindings object to its data.
if ( !hasVirtualBindings( this ) ) {
$.data( this, dataPropertyName, {} );
}
// If setup is called, we know it is the first binding for this
// eventType, so initialize the count for the eventType to zero.
var bindings = $.data( this, dataPropertyName );
bindings[ eventType ] = true;
// If this is the first virtual mouse event for this type,
// register a global handler on the document.
activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1;
if ( activeDocHandlers[ eventType ] === 1 ) {
$document.bind( realType, mouseEventCallback );
}
// Some browsers, like Opera Mini, won't dispatch mouse/click events
// for elements unless they actually have handlers registered on them.
// To get around this, we register dummy handlers on the elements.
$( this ).bind( realType, dummyMouseHandler );
// For now, if event capture is not supported, we rely on mouse handlers.
if ( eventCaptureSupported ) {
// If this is the first virtual mouse binding for the document,
// register our touchstart handler on the document.
activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0) + 1;
if ( activeDocHandlers[ "touchstart" ] === 1 ) {
$document.bind( "touchstart", handleTouchStart )
.bind( "touchend", handleTouchEnd )
// On touch platforms, touching the screen and then dragging your finger
// causes the window content to scroll after some distance threshold is
// exceeded. On these platforms, a scroll prevents a click event from being
// dispatched, and on some platforms, even the touchend is suppressed. To
// mimic the suppression of the click event, we need to watch for a scroll
// event. Unfortunately, some platforms like iOS don't dispatch scroll
// events until *AFTER* the user lifts their finger (touchend). This means
// we need to watch both scroll and touchmove events to figure out whether
// or not a scroll happenens before the touchend event is fired.
.bind( "touchmove", handleTouchMove )
.bind( "scroll", handleScroll );
}
}
},
teardown: function( data, namespace ) {
// If this is the last virtual binding for this eventType,
// remove its global handler from the document.
--activeDocHandlers[ eventType ];
if ( !activeDocHandlers[ eventType ] ) {
$document.unbind( realType, mouseEventCallback );
}
if ( eventCaptureSupported ) {
// If this is the last virtual mouse binding in existence,
// remove our document touchstart listener.
--activeDocHandlers[ "touchstart" ];
if ( !activeDocHandlers[ "touchstart" ] ) {
$document.unbind( "touchstart", handleTouchStart )
.unbind( "touchmove", handleTouchMove )
.unbind( "touchend", handleTouchEnd )
.unbind( "scroll", handleScroll );
}
}
var $this = $( this ),
bindings = $.data( this, dataPropertyName );
// teardown may be called when an element was
// removed from the DOM. If this is the case,
// jQuery core may have already stripped the element
// of any data bindings so we need to check it before
// using it.
if ( bindings ) {
bindings[ eventType ] = false;
}
// Unregister the dummy event handler.
$this.unbind( realType, dummyMouseHandler );
// If this is the last virtual mouse binding on the
// element, remove the binding data from the element.
if ( !hasVirtualBindings( this ) ) {
$this.removeData( dataPropertyName );
}
}
};
}
// Expose our custom events to the jQuery bind/unbind mechanism.
for ( var i = 0; i < virtualEventNames.length; i++ ) {
$.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject( virtualEventNames[ i ] );
}
// Add a capture click handler to block clicks.
// Note that we require event capture support for this so if the device
// doesn't support it, we punt for now and rely solely on mouse events.
if ( eventCaptureSupported ) {
document.addEventListener( "click", function( e ) {
var cnt = clickBlockList.length,
target = e.target,
x, y, ele, i, o, touchID;
if ( cnt ) {
x = e.clientX;
y = e.clientY;
threshold = $.vmouse.clickDistanceThreshold;
// The idea here is to run through the clickBlockList to see if
// the current click event is in the proximity of one of our
// vclick events that had preventDefault() called on it. If we find
// one, then we block the click.
//
// Why do we have to rely on proximity?
//
// Because the target of the touch event that triggered the vclick
// can be different from the target of the click event synthesized
// by the browser. The target of a mouse/click event that is syntehsized
// from a touch event seems to be implementation specific. For example,
// some browsers will fire mouse/click events for a link that is near
// a touch event, even though the target of the touchstart/touchend event
// says the user touched outside the link. Also, it seems that with most
// browsers, the target of the mouse/click event is not calculated until the
// time it is dispatched, so if you replace an element that you touched
// with another element, the target of the mouse/click will be the new
// element underneath that point.
//
// Aside from proximity, we also check to see if the target and any
// of its ancestors were the ones that blocked a click. This is necessary
// because of the strange mouse/click target calculation done in the
// Android 2.1 browser, where if you click on an element, and there is a
// mouse/click handler on one of its ancestors, the target will be the
// innermost child of the touched element, even if that child is no where
// near the point of touch.
ele = target;
while ( ele ) {
for ( i = 0; i < cnt; i++ ) {
o = clickBlockList[ i ];
touchID = 0;
if ( ( ele === target && Math.abs( o.x - x ) < threshold && Math.abs( o.y - y ) < threshold ) ||
$.data( ele, touchTargetPropertyName ) === o.touchID ) {
// XXX: We may want to consider removing matches from the block list
// instead of waiting for the reset timer to fire.
e.preventDefault();
e.stopPropagation();
return;
}
}
ele = ele.parentNode;
}
}
}, true);
}
})( jQuery, window, document );
(function( $, window, undefined ) {
var $document = $( document );
// add new event shortcuts
$.each( ( "touchstart touchmove touchend " +
"tap taphold " +
"swipe swipeleft swiperight " +
"scrollstart scrollstop" ).split( " " ), function( i, name ) {
$.fn[ name ] = function( fn ) {
return fn ? this.bind( name, fn ) : this.trigger( name );
};
// jQuery < 1.8
if ( $.attrFn ) {
$.attrFn[ name ] = true;
}
});
var supportTouch = $.mobile.support.touch,
scrollEvent = "touchmove scroll",
touchStartEvent = supportTouch ? "touchstart" : "mousedown",
touchStopEvent = supportTouch ? "touchend" : "mouseup",
touchMoveEvent = supportTouch ? "touchmove" : "mousemove";
function triggerCustomEvent( obj, eventType, event ) {
var originalType = event.type;
event.type = eventType;
$.event.dispatch.call( obj, event );
event.type = originalType;
}
// also handles scrollstop
$.event.special.scrollstart = {
enabled: true,
setup: function() {
var thisObject = this,
$this = $( thisObject ),
scrolling,
timer;
function trigger( event, state ) {
scrolling = state;
triggerCustomEvent( thisObject, scrolling ? "scrollstart" : "scrollstop", event );
}
// iPhone triggers scroll after a small delay; use touchmove instead
$this.bind( scrollEvent, function( event ) {
if ( !$.event.special.scrollstart.enabled ) {
return;
}
if ( !scrolling ) {
trigger( event, true );
}
clearTimeout( timer );
timer = setTimeout( function() {
trigger( event, false );
}, 50 );
});
}
};
// also handles taphold
$.event.special.tap = {
tapholdThreshold: 750,
setup: function() {
var thisObject = this,
$this = $( thisObject );
$this.bind( "vmousedown", function( event ) {
if ( event.which && event.which !== 1 ) {
return false;
}
var origTarget = event.target,
origEvent = event.originalEvent,
timer;
function clearTapTimer() {
clearTimeout( timer );
}
function clearTapHandlers() {
clearTapTimer();
$this.unbind( "vclick", clickHandler )
.unbind( "vmouseup", clearTapTimer );
$document.unbind( "vmousecancel", clearTapHandlers );
}
function clickHandler( event ) {
clearTapHandlers();
// ONLY trigger a 'tap' event if the start target is
// the same as the stop target.
if ( origTarget === event.target ) {
triggerCustomEvent( thisObject, "tap", event );
}
}
$this.bind( "vmouseup", clearTapTimer )
.bind( "vclick", clickHandler );
$document.bind( "vmousecancel", clearTapHandlers );
timer = setTimeout( function() {
triggerCustomEvent( thisObject, "taphold", $.Event( "taphold", { target: origTarget } ) );
}, $.event.special.tap.tapholdThreshold );
});
}
};
// also handles swipeleft, swiperight
$.event.special.swipe = {
scrollSupressionThreshold: 30, // More than this horizontal displacement, and we will suppress scrolling.
durationThreshold: 1000, // More time than this, and it isn't a swipe.
horizontalDistanceThreshold: 30, // Swipe horizontal displacement must be more than this.
verticalDistanceThreshold: 75, // Swipe vertical displacement must be less than this.
start: function( event ) {
var data = event.originalEvent.touches ?
event.originalEvent.touches[ 0 ] : event;
return {
time: ( new Date() ).getTime(),
coords: [ data.pageX, data.pageY ],
origin: $( event.target )
};
},
stop: function( event ) {
var data = event.originalEvent.touches ?
event.originalEvent.touches[ 0 ] : event;
return {
time: ( new Date() ).getTime(),
coords: [ data.pageX, data.pageY ]
};
},
handleSwipe: function( start, stop ) {
if ( stop.time - start.time < $.event.special.swipe.durationThreshold &&
Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.horizontalDistanceThreshold &&
Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < $.event.special.swipe.verticalDistanceThreshold ) {
start.origin.trigger( "swipe" )
.trigger( start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight" );
}
},
setup: function() {
var thisObject = this,
$this = $( thisObject );
$this.bind( touchStartEvent, function( event ) {
var start = $.event.special.swipe.start( event ),
stop;
function moveHandler( event ) {
if ( !start ) {
return;
}
stop = $.event.special.swipe.stop( event );
// prevent scrolling
if ( Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.scrollSupressionThreshold ) {
event.preventDefault();
}
}
$this.bind( touchMoveEvent, moveHandler )
.one( touchStopEvent, function() {
$this.unbind( touchMoveEvent, moveHandler );
if ( start && stop ) {
$.event.special.swipe.handleSwipe( start, stop );
}
start = stop = undefined;
});
});
}
};
$.each({
scrollstop: "scrollstart",
taphold: "tap",
swipeleft: "swipe",
swiperight: "swipe"
}, function( event, sourceEvent ) {
$.event.special[ event ] = {
setup: function() {
$( this ).bind( sourceEvent, $.noop );
}
};
});
})( jQuery, this );
// throttled resize event
(function( $ ) {
$.event.special.throttledresize = {
setup: function() {
$( this ).bind( "resize", handler );
},
teardown: function() {
$( this ).unbind( "resize", handler );
}
};
var throttle = 250,
handler = function() {
curr = ( new Date() ).getTime();
diff = curr - lastCall;
if ( diff >= throttle ) {
lastCall = curr;
$( this ).trigger( "throttledresize" );
} else {
if ( heldCall ) {
clearTimeout( heldCall );
}
// Promise a held call will still execute
heldCall = setTimeout( handler, throttle - diff );
}
},
lastCall = 0,
heldCall,
curr,
diff;
})( jQuery );
(function( $, window ) {
var win = $( window ),
event_name = "orientationchange",
special_event,
get_orientation,
last_orientation,
initial_orientation_is_landscape,
initial_orientation_is_default,
portrait_map = { "0": true, "180": true };
// It seems that some device/browser vendors use window.orientation values 0 and 180 to
// denote the "default" orientation. For iOS devices, and most other smart-phones tested,
// the default orientation is always "portrait", but in some Android and RIM based tablets,
// the default orientation is "landscape". The following code attempts to use the window
// dimensions to figure out what the current orientation is, and then makes adjustments
// to the to the portrait_map if necessary, so that we can properly decode the
// window.orientation value whenever get_orientation() is called.
//
// Note that we used to use a media query to figure out what the orientation the browser
// thinks it is in:
//
// initial_orientation_is_landscape = $.mobile.media("all and (orientation: landscape)");
//
// but there was an iPhone/iPod Touch bug beginning with iOS 4.2, up through iOS 5.1,
// where the browser *ALWAYS* applied the landscape media query. This bug does not
// happen on iPad.
if ( $.support.orientation ) {
// Check the window width and height to figure out what the current orientation
// of the device is at this moment. Note that we've initialized the portrait map
// values to 0 and 180, *AND* we purposely check for landscape so that if we guess
// wrong, , we default to the assumption that portrait is the default orientation.
// We use a threshold check below because on some platforms like iOS, the iPhone
// form-factor can report a larger width than height if the user turns on the
// developer console. The actual threshold value is somewhat arbitrary, we just
// need to make sure it is large enough to exclude the developer console case.
var ww = window.innerWidth || win.width(),
wh = window.innerHeight || win.height(),
landscape_threshold = 50;
initial_orientation_is_landscape = ww > wh && ( ww - wh ) > landscape_threshold;
// Now check to see if the current window.orientation is 0 or 180.
initial_orientation_is_default = portrait_map[ window.orientation ];
// If the initial orientation is landscape, but window.orientation reports 0 or 180, *OR*
// if the initial orientation is portrait, but window.orientation reports 90 or -90, we
// need to flip our portrait_map values because landscape is the default orientation for
// this device/browser.
if ( ( initial_orientation_is_landscape && initial_orientation_is_default ) || ( !initial_orientation_is_landscape && !initial_orientation_is_default ) ) {
portrait_map = { "-90": true, "90": true };
}
}
$.event.special.orientationchange = $.extend( {}, $.event.special.orientationchange, {
setup: function() {
// If the event is supported natively, return false so that jQuery
// will bind to the event using DOM methods.
if ( $.support.orientation && !$.event.special.orientationchange.disabled ) {
return false;
}
// Get the current orientation to avoid initial double-triggering.
last_orientation = get_orientation();
// Because the orientationchange event doesn't exist, simulate the
// event by testing window dimensions on resize.
win.bind( "throttledresize", handler );
},
teardown: function() {
// If the event is not supported natively, return false so that
// jQuery will unbind the event using DOM methods.
if ( $.support.orientation && !$.event.special.orientationchange.disabled ) {
return false;
}
// Because the orientationchange event doesn't exist, unbind the
// resize event handler.
win.unbind( "throttledresize", handler );
},
add: function( handleObj ) {
// Save a reference to the bound event handler.
var old_handler = handleObj.handler;
handleObj.handler = function( event ) {
// Modify event object, adding the .orientation property.
event.orientation = get_orientation();
// Call the originally-bound event handler and return its result.
return old_handler.apply( this, arguments );
};
}
});
// If the event is not supported natively, this handler will be bound to
// the window resize event to simulate the orientationchange event.
function handler() {
// Get the current orientation.
var orientation = get_orientation();
if ( orientation !== last_orientation ) {
// The orientation has changed, so trigger the orientationchange event.
last_orientation = orientation;
win.trigger( event_name );
}
}
// Get the current page orientation. This method is exposed publicly, should it
// be needed, as jQuery.event.special.orientationchange.orientation()
$.event.special.orientationchange.orientation = get_orientation = function() {
var isPortrait = true, elem = document.documentElement;
// prefer window orientation to the calculation based on screensize as
// the actual screen resize takes place before or after the orientation change event
// has been fired depending on implementation (eg android 2.3 is before, iphone after).
// More testing is required to determine if a more reliable method of determining the new screensize
// is possible when orientationchange is fired. (eg, use media queries + element + opacity)
if ( $.support.orientation ) {
// if the window orientation registers as 0 or 180 degrees report
// portrait, otherwise landscape
isPortrait = portrait_map[ window.orientation ];
} else {
isPortrait = elem && elem.clientWidth / elem.clientHeight < 1.1;
}
return isPortrait ? "portrait" : "landscape";
};
$.fn[ event_name ] = function( fn ) {
return fn ? this.bind( event_name, fn ) : this.trigger( event_name );
};
// jQuery < 1.8
if ( $.attrFn ) {
$.attrFn[ event_name ] = true;
}
}( jQuery, this ));
(function( $, undefined ) {
$.widget( "mobile.page", $.mobile.widget, {
options: {
theme: "c",
domCache: false,
keepNativeDefault: ":jqmData(role='none'), :jqmData(role='nojs')"
},
_create: function() {
// if false is returned by the callbacks do not create the page
if ( this._trigger( "beforecreate" ) === false ) {
return false;
}
this.element
.attr( "tabindex", "0" )
.addClass( "ui-page ui-body-" + this.options.theme );
this._on( this.element, {
pagebeforehide: "removeContainerBackground",
pagebeforeshow: "_handlePageBeforeShow"
});
},
_handlePageBeforeShow: function( e ) {
this.setContainerBackground();
},
removeContainerBackground: function() {
$.mobile.pageContainer.removeClass( "ui-overlay-" + $.mobile.getInheritedTheme( this.element.parent() ) );
},
// set the page container background to the page theme
setContainerBackground: function( theme ) {
if ( this.options.theme ) {
$.mobile.pageContainer.addClass( "ui-overlay-" + ( theme || this.options.theme ) );
}
},
keepNativeSelector: function() {
var options = this.options,
keepNativeDefined = options.keepNative && $.trim( options.keepNative );
if ( keepNativeDefined && options.keepNative !== options.keepNativeDefault ) {
return [options.keepNative, options.keepNativeDefault].join( ", " );
}
return options.keepNativeDefault;
}
});
})( jQuery );
(function( $, window, undefined ) {
var createHandler = function( sequential ) {
// Default to sequential
if ( sequential === undefined ) {
sequential = true;
}
return function( name, reverse, $to, $from ) {
var deferred = new $.Deferred(),
reverseClass = reverse ? " reverse" : "",
active = $.mobile.urlHistory.getActive(),
toScroll = active.lastScroll || $.mobile.defaultHomeScroll,
screenHeight = $.mobile.getScreenHeight(),
maxTransitionOverride = $.mobile.maxTransitionWidth !== false && $.mobile.window.width() > $.mobile.maxTransitionWidth,
none = !$.support.cssTransitions || maxTransitionOverride || !name || name === "none" || Math.max( $.mobile.window.scrollTop(), toScroll ) > $.mobile.getMaxScrollForTransition(),
toPreClass = " ui-page-pre-in",
toggleViewportClass = function() {
$.mobile.pageContainer.toggleClass( "ui-mobile-viewport-transitioning viewport-" + name );
},
scrollPage = function() {
// By using scrollTo instead of silentScroll, we can keep things better in order
// Just to be precautios, disable scrollstart listening like silentScroll would
$.event.special.scrollstart.enabled = false;
window.scrollTo( 0, toScroll );
// reenable scrollstart listening like silentScroll would
setTimeout( function() {
$.event.special.scrollstart.enabled = true;
}, 150 );
},
cleanFrom = function() {
$from
.removeClass( $.mobile.activePageClass + " out in reverse " + name )
.height( "" );
},
startOut = function() {
// if it's not sequential, call the doneOut transition to start the TO page animating in simultaneously
if ( !sequential ) {
doneOut();
}
else {
$from.animationComplete( doneOut );
}
// Set the from page's height and start it transitioning out
// Note: setting an explicit height helps eliminate tiling in the transitions
$from
.height( screenHeight + $.mobile.window.scrollTop() )
.addClass( name + " out" + reverseClass );
},
doneOut = function() {
if ( $from && sequential ) {
cleanFrom();
}
startIn();
},
startIn = function() {
// Prevent flickering in phonegap container: see comments at #4024 regarding iOS
$to.css( "z-index", -10 );
$to.addClass( $.mobile.activePageClass + toPreClass );
// Send focus to page as it is now display: block
$.mobile.focusPage( $to );
// Set to page height
$to.height( screenHeight + toScroll );
scrollPage();
// Restores visibility of the new page: added together with $to.css( "z-index", -10 );
$to.css( "z-index", "" );
if ( !none ) {
$to.animationComplete( doneIn );
}
$to
.removeClass( toPreClass )
.addClass( name + " in" + reverseClass );
if ( none ) {
doneIn();
}
},
doneIn = function() {
if ( !sequential ) {
if ( $from ) {
cleanFrom();
}
}
$to
.removeClass( "out in reverse " + name )
.height( "" );
toggleViewportClass();
// In some browsers (iOS5), 3D transitions block the ability to scroll to the desired location during transition
// This ensures we jump to that spot after the fact, if we aren't there already.
if ( $.mobile.window.scrollTop() !== toScroll ) {
scrollPage();
}
deferred.resolve( name, reverse, $to, $from, true );
};
toggleViewportClass();
if ( $from && !none ) {
startOut();
}
else {
doneOut();
}
return deferred.promise();
};
};
// generate the handlers from the above
var sequentialHandler = createHandler(),
simultaneousHandler = createHandler( false ),
defaultGetMaxScrollForTransition = function() {
return $.mobile.getScreenHeight() * 3;
};
// Make our transition handler the public default.
$.mobile.defaultTransitionHandler = sequentialHandler;
//transition handler dictionary for 3rd party transitions
$.mobile.transitionHandlers = {
"default": $.mobile.defaultTransitionHandler,
"sequential": sequentialHandler,
"simultaneous": simultaneousHandler
};
$.mobile.transitionFallbacks = {};
// If transition is defined, check if css 3D transforms are supported, and if not, if a fallback is specified
$.mobile._maybeDegradeTransition = function( transition ) {
if ( transition && !$.support.cssTransform3d && $.mobile.transitionFallbacks[ transition ] ) {
transition = $.mobile.transitionFallbacks[ transition ];
}
return transition;
};
// Set the getMaxScrollForTransition to default if no implementation was set by user
$.mobile.getMaxScrollForTransition = $.mobile.getMaxScrollForTransition || defaultGetMaxScrollForTransition;
})( jQuery, this );
(function( $, undefined ) {
//define vars for interal use
var $window = $.mobile.window,
$html = $( 'html' ),
$head = $( 'head' ),
// NOTE: path extensions dependent on core attributes. Moved here to remove deps from
// $.mobile.path definition
path = $.extend($.mobile.path, {
//return the substring of a filepath before the sub-page key, for making a server request
getFilePath: function( path ) {
var splitkey = '&' + $.mobile.subPageUrlKey;
return path && path.split( splitkey )[0].split( dialogHashKey )[0];
},
//check if the specified url refers to the first page in the main application document.
isFirstPageUrl: function( url ) {
// We only deal with absolute paths.
var u = path.parseUrl( path.makeUrlAbsolute( url, this.documentBase ) ),
// Does the url have the same path as the document?
samePath = u.hrefNoHash === this.documentUrl.hrefNoHash || ( this.documentBaseDiffers && u.hrefNoHash === this.documentBase.hrefNoHash ),
// Get the first page element.
fp = $.mobile.firstPage,
// Get the id of the first page element if it has one.
fpId = fp && fp[0] ? fp[0].id : undefined;
// The url refers to the first page if the path matches the document and
// it either has no hash value, or the hash is exactly equal to the id of the
// first page element.
return samePath && ( !u.hash || u.hash === "#" || ( fpId && u.hash.replace( /^#/, "" ) === fpId ) );
},
// Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR
// requests if the document doing the request was loaded via the file:// protocol.
// This is usually to allow the application to "phone home" and fetch app specific
// data. We normally let the browser handle external/cross-domain urls, but if the
// allowCrossDomainPages option is true, we will allow cross-domain http/https
// requests to go through our page loading logic.
isPermittedCrossDomainRequest: function( docUrl, reqUrl ) {
return $.mobile.allowCrossDomainPages &&
docUrl.protocol === "file:" &&
reqUrl.search( /^https?:/ ) !== -1;
}
}),
// used to track last vclicked element to make sure its value is added to form data
$lastVClicked = null,
//will be defined when a link is clicked and given an active class
$activeClickedLink = null,
// resolved on domready
domreadyDeferred = $.Deferred(),
//urlHistory is purely here to make guesses at whether the back or forward button was clicked
//and provide an appropriate transition
urlHistory = $.mobile.navigate.history,
//define first selector to receive focus when a page is shown
focusable = "[tabindex],a,button:visible,select:visible,input",
//queue to hold simultanious page transitions
pageTransitionQueue = [],
//indicates whether or not page is in process of transitioning
isPageTransitioning = false,
//nonsense hash change key for dialogs, so they create a history entry
dialogHashKey = "&ui-state=dialog",
//existing base tag?
$base = $head.children( "base" ),
//tuck away the original document URL minus any fragment.
documentUrl = path.documentUrl,
//if the document has an embedded base tag, documentBase is set to its
//initial value. If a base tag does not exist, then we default to the documentUrl.
documentBase = path.documentBase,
//cache the comparison once.
documentBaseDiffers = path.documentBaseDiffers,
getScreenHeight = $.mobile.getScreenHeight;
//base element management, defined depending on dynamic base tag support
var base = $.support.dynamicBaseTag ? {
//define base element, for use in routing asset urls that are referenced in Ajax-requested markup
element: ( $base.length ? $base : $( "<base>", { href: documentBase.hrefNoHash } ).prependTo( $head ) ),
//set the generated BASE element's href attribute to a new page's base path
set: function( href ) {
href = path.parseUrl(href).hrefNoHash;
base.element.attr( "href", path.makeUrlAbsolute( href, documentBase ) );
},
//set the generated BASE element's href attribute to a new page's base path
reset: function() {
base.element.attr( "href", documentBase.hrefNoSearch );
}
} : undefined;
//return the original document url
$.mobile.getDocumentUrl = path.getDocumentUrl;
//return the original document base url
$.mobile.getDocumentBase = path.getDocumentBase;
/* internal utility functions */
// NOTE Issue #4950 Android phonegap doesn't navigate back properly
// when a full page refresh has taken place. It appears that hashchange
// and replacestate history alterations work fine but we need to support
// both forms of history traversal in our code that uses backward history
// movement
$.mobile.back = function() {
var nav = window.navigator;
// if the setting is on and the navigator object is
// available use the phonegap navigation capability
if( this.phonegapNavigationEnabled &&
nav &&
nav.app &&
nav.app.backHistory ){
nav.app.backHistory();
} else {
window.history.back();
}
};
//direct focus to the page title, or otherwise first focusable element
$.mobile.focusPage = function ( page ) {
var autofocus = page.find( "[autofocus]" ),
pageTitle = page.find( ".ui-title:eq(0)" );
if ( autofocus.length ) {
autofocus.focus();
return;
}
if ( pageTitle.length ) {
pageTitle.focus();
} else{
page.focus();
}
};
//remove active classes after page transition or error
function removeActiveLinkClass( forceRemoval ) {
if ( !!$activeClickedLink && ( !$activeClickedLink.closest( "." + $.mobile.activePageClass ).length || forceRemoval ) ) {
$activeClickedLink.removeClass( $.mobile.activeBtnClass );
}
$activeClickedLink = null;
}
function releasePageTransitionLock() {
isPageTransitioning = false;
if ( pageTransitionQueue.length > 0 ) {
$.mobile.changePage.apply( null, pageTransitionQueue.pop() );
}
}
// Save the last scroll distance per page, before it is hidden
var setLastScrollEnabled = true,
setLastScroll, delayedSetLastScroll;
setLastScroll = function() {
// this barrier prevents setting the scroll value based on the browser
// scrolling the window based on a hashchange
if ( !setLastScrollEnabled ) {
return;
}
var active = $.mobile.urlHistory.getActive();
if ( active ) {
var lastScroll = $window.scrollTop();
// Set active page's lastScroll prop.
// If the location we're scrolling to is less than minScrollBack, let it go.
active.lastScroll = lastScroll < $.mobile.minScrollBack ? $.mobile.defaultHomeScroll : lastScroll;
}
};
// bind to scrollstop to gather scroll position. The delay allows for the hashchange
// event to fire and disable scroll recording in the case where the browser scrolls
// to the hash targets location (sometimes the top of the page). once pagechange fires
// getLastScroll is again permitted to operate
delayedSetLastScroll = function() {
setTimeout( setLastScroll, 100 );
};
// disable an scroll setting when a hashchange has been fired, this only works
// because the recording of the scroll position is delayed for 100ms after
// the browser might have changed the position because of the hashchange
$window.bind( $.support.pushState ? "popstate" : "hashchange", function() {
setLastScrollEnabled = false;
});
// handle initial hashchange from chrome :(
$window.one( $.support.pushState ? "popstate" : "hashchange", function() {
setLastScrollEnabled = true;
});
// wait until the mobile page container has been determined to bind to pagechange
$window.one( "pagecontainercreate", function() {
// once the page has changed, re-enable the scroll recording
$.mobile.pageContainer.bind( "pagechange", function() {
setLastScrollEnabled = true;
// remove any binding that previously existed on the get scroll
// which may or may not be different than the scroll element determined for
// this page previously
$window.unbind( "scrollstop", delayedSetLastScroll );
// determine and bind to the current scoll element which may be the window
// or in the case of touch overflow the element with touch overflow
$window.bind( "scrollstop", delayedSetLastScroll );
});
});
// bind to scrollstop for the first page as "pagechange" won't be fired in that case
$window.bind( "scrollstop", delayedSetLastScroll );
// No-op implementation of transition degradation
$.mobile._maybeDegradeTransition = $.mobile._maybeDegradeTransition || function( transition ) {
return transition;
};
//function for transitioning between two existing pages
function transitionPages( toPage, fromPage, transition, reverse ) {
if ( fromPage ) {
//trigger before show/hide events
fromPage.data( "mobile-page" )._trigger( "beforehide", null, { nextPage: toPage } );
}
toPage.data( "mobile-page" )._trigger( "beforeshow", null, { prevPage: fromPage || $( "" ) } );
//clear page loader
$.mobile.hidePageLoadingMsg();
transition = $.mobile._maybeDegradeTransition( transition );
//find the transition handler for the specified transition. If there
//isn't one in our transitionHandlers dictionary, use the default one.
//call the handler immediately to kick-off the transition.
var th = $.mobile.transitionHandlers[ transition || "default" ] || $.mobile.defaultTransitionHandler,
promise = th( transition, reverse, toPage, fromPage );
promise.done(function() {
//trigger show/hide events
if ( fromPage ) {
fromPage.data( "mobile-page" )._trigger( "hide", null, { nextPage: toPage } );
}
//trigger pageshow, define prevPage as either fromPage or empty jQuery obj
toPage.data( "mobile-page" )._trigger( "show", null, { prevPage: fromPage || $( "" ) } );
});
return promise;
}
//simply set the active page's minimum height to screen height, depending on orientation
$.mobile.resetActivePageHeight = function resetActivePageHeight( height ) {
var aPage = $( "." + $.mobile.activePageClass ),
aPagePadT = parseFloat( aPage.css( "padding-top" ) ),
aPagePadB = parseFloat( aPage.css( "padding-bottom" ) ),
aPageBorderT = parseFloat( aPage.css( "border-top-width" ) ),
aPageBorderB = parseFloat( aPage.css( "border-bottom-width" ) );
height = ( typeof height === "number" )? height : getScreenHeight();
aPage.css( "min-height", height - aPagePadT - aPagePadB - aPageBorderT - aPageBorderB );
};
//shared page enhancements
function enhancePage( $page, role ) {
// If a role was specified, make sure the data-role attribute
// on the page element is in sync.
if ( role ) {
$page.attr( "data-" + $.mobile.ns + "role", role );
}
//run page plugin
$page.page();
}
// determine the current base url
function findBaseWithDefault() {
var closestBase = ( $.mobile.activePage && getClosestBaseUrl( $.mobile.activePage ) );
return closestBase || documentBase.hrefNoHash;
}
/* exposed $.mobile methods */
//animation complete callback
$.fn.animationComplete = function( callback ) {
if ( $.support.cssTransitions ) {
return $( this ).one( 'webkitAnimationEnd animationend', callback );
}
else{
// defer execution for consistency between webkit/non webkit
setTimeout( callback, 0 );
return $( this );
}
};
//expose path object on $.mobile
$.mobile.path = path;
//expose base object on $.mobile
$.mobile.base = base;
//history stack
$.mobile.urlHistory = urlHistory;
$.mobile.dialogHashKey = dialogHashKey;
//enable cross-domain page support
$.mobile.allowCrossDomainPages = false;
$.mobile._bindPageRemove = function() {
var page = $( this );
// when dom caching is not enabled or the page is embedded bind to remove the page on hide
if ( !page.data( "mobile-page" ).options.domCache &&
page.is( ":jqmData(external-page='true')" ) ) {
page.bind( 'pagehide.remove', function( e ) {
var $this = $( this ),
prEvent = new $.Event( "pageremove" );
$this.trigger( prEvent );
if ( !prEvent.isDefaultPrevented() ) {
$this.removeWithDependents();
}
});
}
};
// Load a page into the DOM.
$.mobile.loadPage = function( url, options ) {
// This function uses deferred notifications to let callers
// know when the page is done loading, or if an error has occurred.
var deferred = $.Deferred(),
// The default loadPage options with overrides specified by
// the caller.
settings = $.extend( {}, $.mobile.loadPage.defaults, options ),
// The DOM element for the page after it has been loaded.
page = null,
// If the reloadPage option is true, and the page is already
// in the DOM, dupCachedPage will be set to the page element
// so that it can be removed after the new version of the
// page is loaded off the network.
dupCachedPage = null,
// The absolute version of the URL passed into the function. This
// version of the URL may contain dialog/subpage params in it.
absUrl = path.makeUrlAbsolute( url, findBaseWithDefault() );
// If the caller provided data, and we're using "get" request,
// append the data to the URL.
if ( settings.data && settings.type === "get" ) {
absUrl = path.addSearchParams( absUrl, settings.data );
settings.data = undefined;
}
// If the caller is using a "post" request, reloadPage must be true
if ( settings.data && settings.type === "post" ) {
settings.reloadPage = true;
}
// The absolute version of the URL minus any dialog/subpage params.
// In otherwords the real URL of the page to be loaded.
var fileUrl = path.getFilePath( absUrl ),
// The version of the Url actually stored in the data-url attribute of
// the page. For embedded pages, it is just the id of the page. For pages
// within the same domain as the document base, it is the site relative
// path. For cross-domain pages (Phone Gap only) the entire absolute Url
// used to load the page.
dataUrl = path.convertUrlToDataUrl( absUrl );
// Make sure we have a pageContainer to work with.
settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
// Check to see if the page already exists in the DOM.
// NOTE do _not_ use the :jqmData psuedo selector because parenthesis
// are a valid url char and it breaks on the first occurence
page = settings.pageContainer.children( "[data-" + $.mobile.ns +"url='" + dataUrl + "']" );
// If we failed to find the page, check to see if the url is a
// reference to an embedded page. If so, it may have been dynamically
// injected by a developer, in which case it would be lacking a data-url
// attribute and in need of enhancement.
if ( page.length === 0 && dataUrl && !path.isPath( dataUrl ) ) {
page = settings.pageContainer.children( "#" + dataUrl )
.attr( "data-" + $.mobile.ns + "url", dataUrl )
.jqmData( "url", dataUrl );
}
// If we failed to find a page in the DOM, check the URL to see if it
// refers to the first page in the application. If it isn't a reference
// to the first page and refers to non-existent embedded page, error out.
if ( page.length === 0 ) {
if ( $.mobile.firstPage && path.isFirstPageUrl( fileUrl ) ) {
// Check to make sure our cached-first-page is actually
// in the DOM. Some user deployed apps are pruning the first
// page from the DOM for various reasons, we check for this
// case here because we don't want a first-page with an id
// falling through to the non-existent embedded page error
// case. If the first-page is not in the DOM, then we let
// things fall through to the ajax loading code below so
// that it gets reloaded.
if ( $.mobile.firstPage.parent().length ) {
page = $( $.mobile.firstPage );
}
} else if ( path.isEmbeddedPage( fileUrl ) ) {
deferred.reject( absUrl, options );
return deferred.promise();
}
}
// If the page we are interested in is already in the DOM,
// and the caller did not indicate that we should force a
// reload of the file, we are done. Otherwise, track the
// existing page as a duplicated.
if ( page.length ) {
if ( !settings.reloadPage ) {
enhancePage( page, settings.role );
deferred.resolve( absUrl, options, page );
//if we are reloading the page make sure we update the base if its not a prefetch
if( base && !options.prefetch ){
base.set(url);
}
return deferred.promise();
}
dupCachedPage = page;
}
var mpc = settings.pageContainer,
pblEvent = new $.Event( "pagebeforeload" ),
triggerData = { url: url, absUrl: absUrl, dataUrl: dataUrl, deferred: deferred, options: settings };
// Let listeners know we're about to load a page.
mpc.trigger( pblEvent, triggerData );
// If the default behavior is prevented, stop here!
if ( pblEvent.isDefaultPrevented() ) {
return deferred.promise();
}
if ( settings.showLoadMsg ) {
// This configurable timeout allows cached pages a brief delay to load without showing a message
var loadMsgDelay = setTimeout(function() {
$.mobile.showPageLoadingMsg();
}, settings.loadMsgDelay ),
// Shared logic for clearing timeout and removing message.
hideMsg = function() {
// Stop message show timer
clearTimeout( loadMsgDelay );
// Hide loading message
$.mobile.hidePageLoadingMsg();
};
}
// Reset base to the default document base.
// only reset if we are not prefetching
if ( base && ( typeof options === "undefined" || typeof options.prefetch === "undefined" ) ) {
base.reset();
}
if ( !( $.mobile.allowCrossDomainPages || path.isSameDomain( documentUrl, absUrl ) ) ) {
deferred.reject( absUrl, options );
} else {
// Load the new page.
$.ajax({
url: fileUrl,
type: settings.type,
data: settings.data,
contentType: settings.contentType,
dataType: "html",
success: function( html, textStatus, xhr ) {
//pre-parse html to check for a data-url,
//use it as the new fileUrl, base path, etc
var all = $( "<div></div>" ),
//page title regexp
newPageTitle = html.match( /<title[^>]*>([^<]*)/ ) && RegExp.$1,
// TODO handle dialogs again
pageElemRegex = new RegExp( "(<[^>]+\\bdata-" + $.mobile.ns + "role=[\"']?page[\"']?[^>]*>)" ),
dataUrlRegex = new RegExp( "\\bdata-" + $.mobile.ns + "url=[\"']?([^\"'>]*)[\"']?" );
// data-url must be provided for the base tag so resource requests can be directed to the
// correct url. loading into a temprorary element makes these requests immediately
if ( pageElemRegex.test( html ) &&
RegExp.$1 &&
dataUrlRegex.test( RegExp.$1 ) &&
RegExp.$1 ) {
url = fileUrl = path.getFilePath( $( "<div>" + RegExp.$1 + "</div>" ).text() );
}
//dont update the base tag if we are prefetching
if ( base && ( typeof options === "undefined" || typeof options.prefetch === "undefined" )) {
base.set( fileUrl );
}
//workaround to allow scripts to execute when included in page divs
all.get( 0 ).innerHTML = html;
page = all.find( ":jqmData(role='page'), :jqmData(role='dialog')" ).first();
//if page elem couldn't be found, create one and insert the body element's contents
if ( !page.length ) {
page = $( "<div data-" + $.mobile.ns + "role='page'>" + ( html.split( /<\/?body[^>]*>/gmi )[1] || "" ) + "</div>" );
}
if ( newPageTitle && !page.jqmData( "title" ) ) {
if ( ~newPageTitle.indexOf( "&" ) ) {
newPageTitle = $( "<div>" + newPageTitle + "</div>" ).text();
}
page.jqmData( "title", newPageTitle );
}
//rewrite src and href attrs to use a base url
if ( !$.support.dynamicBaseTag ) {
var newPath = path.get( fileUrl );
page.find( "[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]" ).each(function() {
var thisAttr = $( this ).is( '[href]' ) ? 'href' :
$( this ).is( '[src]' ) ? 'src' : 'action',
thisUrl = $( this ).attr( thisAttr );
// XXX_jblas: We need to fix this so that it removes the document
// base URL, and then prepends with the new page URL.
//if full path exists and is same, chop it - helps IE out
thisUrl = thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' );
if ( !/^(\w+:|#|\/)/.test( thisUrl ) ) {
$( this ).attr( thisAttr, newPath + thisUrl );
}
});
}
//append to page and enhance
// TODO taging a page with external to make sure that embedded pages aren't removed
// by the various page handling code is bad. Having page handling code in many
// places is bad. Solutions post 1.0
page
.attr( "data-" + $.mobile.ns + "url", path.convertUrlToDataUrl( fileUrl ) )
.attr( "data-" + $.mobile.ns + "external-page", true )
.appendTo( settings.pageContainer );
// wait for page creation to leverage options defined on widget
page.one( 'pagecreate', $.mobile._bindPageRemove );
enhancePage( page, settings.role );
// Enhancing the page may result in new dialogs/sub pages being inserted
// into the DOM. If the original absUrl refers to a sub-page, that is the
// real page we are interested in.
if ( absUrl.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ) {
page = settings.pageContainer.children( "[data-" + $.mobile.ns +"url='" + dataUrl + "']" );
}
// Remove loading message.
if ( settings.showLoadMsg ) {
hideMsg();
}
// Add the page reference and xhr to our triggerData.
triggerData.xhr = xhr;
triggerData.textStatus = textStatus;
triggerData.page = page;
// Let listeners know the page loaded successfully.
settings.pageContainer.trigger( "pageload", triggerData );
deferred.resolve( absUrl, options, page, dupCachedPage );
},
error: function( xhr, textStatus, errorThrown ) {
//set base back to current path
if ( base ) {
base.set( path.get() );
}
// Add error info to our triggerData.
triggerData.xhr = xhr;
triggerData.textStatus = textStatus;
triggerData.errorThrown = errorThrown;
var plfEvent = new $.Event( "pageloadfailed" );
// Let listeners know the page load failed.
settings.pageContainer.trigger( plfEvent, triggerData );
// If the default behavior is prevented, stop here!
// Note that it is the responsibility of the listener/handler
// that called preventDefault(), to resolve/reject the
// deferred object within the triggerData.
if ( plfEvent.isDefaultPrevented() ) {
return;
}
// Remove loading message.
if ( settings.showLoadMsg ) {
// Remove loading message.
hideMsg();
// show error message
$.mobile.showPageLoadingMsg( $.mobile.pageLoadErrorMessageTheme, $.mobile.pageLoadErrorMessage, true );
// hide after delay
setTimeout( $.mobile.hidePageLoadingMsg, 1500 );
}
deferred.reject( absUrl, options );
}
});
}
return deferred.promise();
};
$.mobile.loadPage.defaults = {
type: "get",
data: undefined,
reloadPage: false,
role: undefined, // By default we rely on the role defined by the @data-role attribute.
showLoadMsg: false,
pageContainer: undefined,
loadMsgDelay: 50 // This delay allows loads that pull from browser cache to occur without showing the loading message.
};
// Show a specific page in the page container.
$.mobile.changePage = function( toPage, options ) {
// If we are in the midst of a transition, queue the current request.
// We'll call changePage() once we're done with the current transition to
// service the request.
if ( isPageTransitioning ) {
pageTransitionQueue.unshift( arguments );
return;
}
var settings = $.extend( {}, $.mobile.changePage.defaults, options ), isToPageString;
// Make sure we have a pageContainer to work with.
settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
// Make sure we have a fromPage.
settings.fromPage = settings.fromPage || $.mobile.activePage;
isToPageString = (typeof toPage === "string");
var mpc = settings.pageContainer,
pbcEvent = new $.Event( "pagebeforechange" ),
triggerData = { toPage: toPage, options: settings };
// NOTE: preserve the original target as the dataUrl value will be simplified
// eg, removing ui-state, and removing query params from the hash
// this is so that users who want to use query params have access to them
// in the event bindings for the page life cycle See issue #5085
if ( isToPageString ) {
// if the toPage is a string simply convert it
triggerData.absUrl = path.makeUrlAbsolute( toPage, findBaseWithDefault() );
} else {
// if the toPage is a jQuery object grab the absolute url stored
// in the loadPage callback where it exists
triggerData.absUrl = toPage.data( 'absUrl' );
}
// Let listeners know we're about to change the current page.
mpc.trigger( pbcEvent, triggerData );
// If the default behavior is prevented, stop here!
if ( pbcEvent.isDefaultPrevented() ) {
return;
}
// We allow "pagebeforechange" observers to modify the toPage in the trigger
// data to allow for redirects. Make sure our toPage is updated.
//
// We also need to re-evaluate whether it is a string, because an object can
// also be replaced by a string
toPage = triggerData.toPage;
isToPageString = (typeof toPage === "string");
// Set the isPageTransitioning flag to prevent any requests from
// entering this method while we are in the midst of loading a page
// or transitioning.
isPageTransitioning = true;
// If the caller passed us a url, call loadPage()
// to make sure it is loaded into the DOM. We'll listen
// to the promise object it returns so we know when
// it is done loading or if an error ocurred.
if ( isToPageString ) {
// preserve the original target as the dataUrl value will be simplified
// eg, removing ui-state, and removing query params from the hash
// this is so that users who want to use query params have access to them
// in the event bindings for the page life cycle See issue #5085
settings.target = toPage;
$.mobile.loadPage( toPage, settings )
.done(function( url, options, newPage, dupCachedPage ) {
isPageTransitioning = false;
options.duplicateCachedPage = dupCachedPage;
// store the original absolute url so that it can be provided
// to events in the triggerData of the subsequent changePage call
newPage.data( 'absUrl', triggerData.absUrl );
$.mobile.changePage( newPage, options );
})
.fail(function( url, options ) {
//clear out the active button state
removeActiveLinkClass( true );
//release transition lock so navigation is free again
releasePageTransitionLock();
settings.pageContainer.trigger( "pagechangefailed", triggerData );
});
return;
}
// If we are going to the first-page of the application, we need to make
// sure settings.dataUrl is set to the application document url. This allows
// us to avoid generating a document url with an id hash in the case where the
// first-page of the document has an id attribute specified.
if ( toPage[ 0 ] === $.mobile.firstPage[ 0 ] && !settings.dataUrl ) {
settings.dataUrl = documentUrl.hrefNoHash;
}
// The caller passed us a real page DOM element. Update our
// internal state and then trigger a transition to the page.
var fromPage = settings.fromPage,
url = ( settings.dataUrl && path.convertUrlToDataUrl( settings.dataUrl ) ) || toPage.jqmData( "url" ),
// The pageUrl var is usually the same as url, except when url is obscured as a dialog url. pageUrl always contains the file path
pageUrl = url,
fileUrl = path.getFilePath( url ),
active = urlHistory.getActive(),
activeIsInitialPage = urlHistory.activeIndex === 0,
historyDir = 0,
pageTitle = document.title,
isDialog = settings.role === "dialog" || toPage.jqmData( "role" ) === "dialog";
// By default, we prevent changePage requests when the fromPage and toPage
// are the same element, but folks that generate content manually/dynamically
// and reuse pages want to be able to transition to the same page. To allow
// this, they will need to change the default value of allowSamePageTransition
// to true, *OR*, pass it in as an option when they manually call changePage().
// It should be noted that our default transition animations assume that the
// formPage and toPage are different elements, so they may behave unexpectedly.
// It is up to the developer that turns on the allowSamePageTransitiona option
// to either turn off transition animations, or make sure that an appropriate
// animation transition is used.
if ( fromPage && fromPage[0] === toPage[0] && !settings.allowSamePageTransition ) {
isPageTransitioning = false;
mpc.trigger( "pagechange", triggerData );
// Even if there is no page change to be done, we should keep the urlHistory in sync with the hash changes
if ( settings.fromHashChange ) {
urlHistory.direct({ url: url });
}
return;
}
// We need to make sure the page we are given has already been enhanced.
enhancePage( toPage, settings.role );
// If the changePage request was sent from a hashChange event, check to see if the
// page is already within the urlHistory stack. If so, we'll assume the user hit
// the forward/back button and will try to match the transition accordingly.
if ( settings.fromHashChange ) {
historyDir = options.direction === "back" ? -1 : 1;
}
// Kill the keyboard.
// XXX_jblas: We need to stop crawling the entire document to kill focus. Instead,
// we should be tracking focus with a delegate() handler so we already have
// the element in hand at this point.
// Wrap this in a try/catch block since IE9 throw "Unspecified error" if document.activeElement
// is undefined when we are in an IFrame.
try {
if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== 'body' ) {
$( document.activeElement ).blur();
} else {
$( "input:focus, textarea:focus, select:focus" ).blur();
}
} catch( e ) {}
// Record whether we are at a place in history where a dialog used to be - if so, do not add a new history entry and do not change the hash either
var alreadyThere = false;
// If we're displaying the page as a dialog, we don't want the url
// for the dialog content to be used in the hash. Instead, we want
// to append the dialogHashKey to the url of the current page.
if ( isDialog && active ) {
// on the initial page load active.url is undefined and in that case should
// be an empty string. Moving the undefined -> empty string back into
// urlHistory.addNew seemed imprudent given undefined better represents
// the url state
// If we are at a place in history that once belonged to a dialog, reuse
// this state without adding to urlHistory and without modifying the hash.
// However, if a dialog is already displayed at this point, and we're
// about to display another dialog, then we must add another hash and
// history entry on top so that one may navigate back to the original dialog
if ( active.url &&
active.url.indexOf( dialogHashKey ) > -1 &&
$.mobile.activePage &&
!$.mobile.activePage.is( ".ui-dialog" ) &&
urlHistory.activeIndex > 0 ) {
settings.changeHash = false;
alreadyThere = true;
}
// Normally, we tack on a dialog hash key, but if this is the location of a stale dialog,
// we reuse the URL from the entry
url = ( active.url || "" );
// account for absolute urls instead of just relative urls use as hashes
if( !alreadyThere && url.indexOf("#") > -1 ) {
url += dialogHashKey;
} else {
url += "#" + dialogHashKey;
}
// tack on another dialogHashKey if this is the same as the initial hash
// this makes sure that a history entry is created for this dialog
if ( urlHistory.activeIndex === 0 && url === urlHistory.initialDst ) {
url += dialogHashKey;
}
}
// if title element wasn't found, try the page div data attr too
// If this is a deep-link or a reload ( active === undefined ) then just use pageTitle
var newPageTitle = ( !active )? pageTitle : toPage.jqmData( "title" ) || toPage.children( ":jqmData(role='header')" ).find( ".ui-title" ).text();
if ( !!newPageTitle && pageTitle === document.title ) {
pageTitle = newPageTitle;
}
if ( !toPage.jqmData( "title" ) ) {
toPage.jqmData( "title", pageTitle );
}
// Make sure we have a transition defined.
settings.transition = settings.transition ||
( ( historyDir && !activeIsInitialPage ) ? active.transition : undefined ) ||
( isDialog ? $.mobile.defaultDialogTransition : $.mobile.defaultPageTransition );
//add page to history stack if it's not back or forward
if ( !historyDir && alreadyThere ) {
urlHistory.getActive().pageUrl = pageUrl;
}
// Set the location hash.
if ( url && !settings.fromHashChange ) {
var params;
// rebuilding the hash here since we loose it earlier on
// TODO preserve the originally passed in path
if( !path.isPath( url ) && url.indexOf( "#" ) < 0 ) {
url = "#" + url;
}
// TODO the property names here are just silly
params = {
transition: settings.transition,
title: pageTitle,
pageUrl: pageUrl,
role: settings.role
};
if ( settings.changeHash !== false && $.mobile.hashListeningEnabled ) {
$.mobile.navigate( url, params, true);
} else if ( toPage[ 0 ] !== $.mobile.firstPage[ 0 ] ) {
$.mobile.navigate.history.add( url, params );
}
}
//set page title
document.title = pageTitle;
//set "toPage" as activePage
$.mobile.activePage = toPage;
// If we're navigating back in the URL history, set reverse accordingly.
settings.reverse = settings.reverse || historyDir < 0;
transitionPages( toPage, fromPage, settings.transition, settings.reverse )
.done(function( name, reverse, $to, $from, alreadyFocused ) {
removeActiveLinkClass();
//if there's a duplicateCachedPage, remove it from the DOM now that it's hidden
if ( settings.duplicateCachedPage ) {
settings.duplicateCachedPage.remove();
}
// Send focus to the newly shown page. Moved from promise .done binding in transitionPages
// itself to avoid ie bug that reports offsetWidth as > 0 (core check for visibility)
// despite visibility: hidden addresses issue #2965
// https://github.com/jquery/jquery-mobile/issues/2965
if ( !alreadyFocused ) {
$.mobile.focusPage( toPage );
}
releasePageTransitionLock();
mpc.trigger( "pagechange", triggerData );
});
};
$.mobile.changePage.defaults = {
transition: undefined,
reverse: false,
changeHash: true,
fromHashChange: false,
role: undefined, // By default we rely on the role defined by the @data-role attribute.
duplicateCachedPage: undefined,
pageContainer: undefined,
showLoadMsg: true, //loading message shows by default when pages are being fetched during changePage
dataUrl: undefined,
fromPage: undefined,
allowSamePageTransition: false
};
/* Event Bindings - hashchange, submit, and click */
function findClosestLink( ele )
{
while ( ele ) {
// Look for the closest element with a nodeName of "a".
// Note that we are checking if we have a valid nodeName
// before attempting to access it. This is because the
// node we get called with could have originated from within
// an embedded SVG document where some symbol instance elements
// don't have nodeName defined on them, or strings are of type
// SVGAnimatedString.
if ( ( typeof ele.nodeName === "string" ) && ele.nodeName.toLowerCase() === "a" ) {
break;
}
ele = ele.parentNode;
}
return ele;
}
// The base URL for any given element depends on the page it resides in.
function getClosestBaseUrl( ele )
{
// Find the closest page and extract out its url.
var url = $( ele ).closest( ".ui-page" ).jqmData( "url" ),
base = documentBase.hrefNoHash;
if ( !url || !path.isPath( url ) ) {
url = base;
}
return path.makeUrlAbsolute( url, base);
}
//The following event bindings should be bound after mobileinit has been triggered
//the following deferred is resolved in the init file
$.mobile.navreadyDeferred = $.Deferred();
$.mobile._registerInternalEvents = function() {
var getAjaxFormData = function( $form, calculateOnly ) {
var url, ret = true, formData, vclickedName, method;
if ( !$.mobile.ajaxEnabled ||
// test that the form is, itself, ajax false
$form.is( ":jqmData(ajax='false')" ) ||
// test that $.mobile.ignoreContentEnabled is set and
// the form or one of it's parents is ajax=false
!$form.jqmHijackable().length ||
$form.attr( "target" ) ) {
return false;
}
url = $form.attr( "action" );
method = ( $form.attr( "method" ) || "get" ).toLowerCase();
// If no action is specified, browsers default to using the
// URL of the document containing the form. Since we dynamically
// pull in pages from external documents, the form should submit
// to the URL for the source document of the page containing
// the form.
if ( !url ) {
// Get the @data-url for the page containing the form.
url = getClosestBaseUrl( $form );
// NOTE: If the method is "get", we need to strip off the query string
// because it will get replaced with the new form data. See issue #5710.
if ( method === "get" ) {
url = path.parseUrl( url ).hrefNoSearch;
}
if ( url === documentBase.hrefNoHash ) {
// The url we got back matches the document base,
// which means the page must be an internal/embedded page,
// so default to using the actual document url as a browser
// would.
url = documentUrl.hrefNoSearch;
}
}
url = path.makeUrlAbsolute( url, getClosestBaseUrl( $form ) );
if ( ( path.isExternal( url ) && !path.isPermittedCrossDomainRequest( documentUrl, url ) ) ) {
return false;
}
if ( !calculateOnly ) {
formData = $form.serializeArray();
if ( $lastVClicked && $lastVClicked[ 0 ].form === $form[ 0 ] ) {
vclickedName = $lastVClicked.attr( "name" );
if ( vclickedName ) {
// Make sure the last clicked element is included in the form
$.each( formData, function( key, value ) {
if ( value.name === vclickedName ) {
// Unset vclickedName - we've found it in the serialized data already
vclickedName = "";
return false;
}
});
if ( vclickedName ) {
formData.push( { name: vclickedName, value: $lastVClicked.attr( "value" ) } );
}
}
}
ret = {
url: url,
options: {
type: method,
data: $.param( formData ),
transition: $form.jqmData( "transition" ),
reverse: $form.jqmData( "direction" ) === "reverse",
reloadPage: true
}
};
}
return ret;
};
//bind to form submit events, handle with Ajax
$.mobile.document.delegate( "form", "submit", function( event ) {
var formData = getAjaxFormData( $( this ) );
if ( formData ) {
$.mobile.changePage( formData.url, formData.options );
event.preventDefault();
}
});
//add active state on vclick
$.mobile.document.bind( "vclick", function( event ) {
var $btn, btnEls, target = event.target, needClosest = false;
// if this isn't a left click we don't care. Its important to note
// that when the virtual event is generated it will create the which attr
if ( event.which > 1 || !$.mobile.linkBindingEnabled ) {
return;
}
// Record that this element was clicked, in case we need it for correct
// form submission during the "submit" handler above
$lastVClicked = $( target );
// Try to find a target element to which the active class will be applied
if ( $.data( target, "mobile-button" ) ) {
// If the form will not be submitted via AJAX, do not add active class
if ( !getAjaxFormData( $( target ).closest( "form" ), true ) ) {
return;
}
// We will apply the active state to this button widget - the parent
// of the input that was clicked will have the associated data
if ( target.parentNode ) {
target = target.parentNode;
}
} else {
target = findClosestLink( target );
if ( !( target && path.parseUrl( target.getAttribute( "href" ) || "#" ).hash !== "#" ) ) {
return;
}
// TODO teach $.mobile.hijackable to operate on raw dom elements so the
// link wrapping can be avoided
if ( !$( target ).jqmHijackable().length ) {
return;
}
}
// Avoid calling .closest by using the data set during .buttonMarkup()
// List items have the button data in the parent of the element clicked
if ( !!~target.className.indexOf( "ui-link-inherit" ) ) {
if ( target.parentNode ) {
btnEls = $.data( target.parentNode, "buttonElements" );
}
// Otherwise, look for the data on the target itself
} else {
btnEls = $.data( target, "buttonElements" );
}
// If found, grab the button's outer element
if ( btnEls ) {
target = btnEls.outer;
} else {
needClosest = true;
}
$btn = $( target );
// If the outer element wasn't found by the our heuristics, use .closest()
if ( needClosest ) {
$btn = $btn.closest( ".ui-btn" );
}
if ( $btn.length > 0 && !$btn.hasClass( "ui-disabled" ) ) {
removeActiveLinkClass( true );
$activeClickedLink = $btn;
$activeClickedLink.addClass( $.mobile.activeBtnClass );
}
});
// click routing - direct to HTTP or Ajax, accordingly
$.mobile.document.bind( "click", function( event ) {
if ( !$.mobile.linkBindingEnabled || event.isDefaultPrevented() ) {
return;
}
var link = findClosestLink( event.target ), $link = $( link ), httpCleanup;
// If there is no link associated with the click or its not a left
// click we want to ignore the click
// TODO teach $.mobile.hijackable to operate on raw dom elements so the link wrapping
// can be avoided
if ( !link || event.which > 1 || !$link.jqmHijackable().length ) {
return;
}
//remove active link class if external (then it won't be there if you come back)
httpCleanup = function() {
window.setTimeout(function() { removeActiveLinkClass( true ); }, 200 );
};
//if there's a data-rel=back attr, go back in history
if ( $link.is( ":jqmData(rel='back')" ) ) {
$.mobile.back();
return false;
}
var baseUrl = getClosestBaseUrl( $link ),
//get href, if defined, otherwise default to empty hash
href = path.makeUrlAbsolute( $link.attr( "href" ) || "#", baseUrl );
//if ajax is disabled, exit early
if ( !$.mobile.ajaxEnabled && !path.isEmbeddedPage( href ) ) {
httpCleanup();
//use default click handling
return;
}
// XXX_jblas: Ideally links to application pages should be specified as
// an url to the application document with a hash that is either
// the site relative path or id to the page. But some of the
// internal code that dynamically generates sub-pages for nested
// lists and select dialogs, just write a hash in the link they
// create. This means the actual URL path is based on whatever
// the current value of the base tag is at the time this code
// is called. For now we are just assuming that any url with a
// hash in it is an application page reference.
if ( href.search( "#" ) !== -1 ) {
href = href.replace( /[^#]*#/, "" );
if ( !href ) {
//link was an empty hash meant purely
//for interaction, so we ignore it.
event.preventDefault();
return;
} else if ( path.isPath( href ) ) {
//we have apath so make it the href we want to load.
href = path.makeUrlAbsolute( href, baseUrl );
} else {
//we have a simple id so use the documentUrl as its base.
href = path.makeUrlAbsolute( "#" + href, documentUrl.hrefNoHash );
}
}
// Should we handle this link, or let the browser deal with it?
var useDefaultUrlHandling = $link.is( "[rel='external']" ) || $link.is( ":jqmData(ajax='false')" ) || $link.is( "[target]" ),
// Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR
// requests if the document doing the request was loaded via the file:// protocol.
// This is usually to allow the application to "phone home" and fetch app specific
// data. We normally let the browser handle external/cross-domain urls, but if the
// allowCrossDomainPages option is true, we will allow cross-domain http/https
// requests to go through our page loading logic.
//check for protocol or rel and its not an embedded page
//TODO overlap in logic from isExternal, rel=external check should be
// moved into more comprehensive isExternalLink
isExternal = useDefaultUrlHandling || ( path.isExternal( href ) && !path.isPermittedCrossDomainRequest( documentUrl, href ) );
if ( isExternal ) {
httpCleanup();
//use default click handling
return;
}
//use ajax
var transition = $link.jqmData( "transition" ),
reverse = $link.jqmData( "direction" ) === "reverse" ||
// deprecated - remove by 1.0
$link.jqmData( "back" ),
//this may need to be more specific as we use data-rel more
role = $link.attr( "data-" + $.mobile.ns + "rel" ) || undefined;
$.mobile.changePage( href, { transition: transition, reverse: reverse, role: role, link: $link } );
event.preventDefault();
});
//prefetch pages when anchors with data-prefetch are encountered
$.mobile.document.delegate( ".ui-page", "pageshow.prefetch", function() {
var urls = [];
$( this ).find( "a:jqmData(prefetch)" ).each(function() {
var $link = $( this ),
url = $link.attr( "href" );
if ( url && $.inArray( url, urls ) === -1 ) {
urls.push( url );
$.mobile.loadPage( url, { role: $link.attr( "data-" + $.mobile.ns + "rel" ),prefetch: true } );
}
});
});
$.mobile._handleHashChange = function( url, data ) {
//find first page via hash
var to = path.stripHash(url),
//transition is false if it's the first page, undefined otherwise (and may be overridden by default)
transition = $.mobile.urlHistory.stack.length === 0 ? "none" : undefined,
// default options for the changPage calls made after examining the current state
// of the page and the hash, NOTE that the transition is derived from the previous
// history entry
changePageOptions = {
changeHash: false,
fromHashChange: true,
reverse: data.direction === "back"
};
$.extend( changePageOptions, data, {
transition: (urlHistory.getLast() || {}).transition || transition
});
// special case for dialogs
if ( urlHistory.activeIndex > 0 && to.indexOf( dialogHashKey ) > -1 && urlHistory.initialDst !== to ) {
// If current active page is not a dialog skip the dialog and continue
// in the same direction
if ( $.mobile.activePage && !$.mobile.activePage.is( ".ui-dialog" ) ) {
//determine if we're heading forward or backward and continue accordingly past
//the current dialog
if( data.direction === "back" ) {
$.mobile.back();
} else {
window.history.forward();
}
// prevent changePage call
return;
} else {
// if the current active page is a dialog and we're navigating
// to a dialog use the dialog objected saved in the stack
to = data.pageUrl;
var active = $.mobile.urlHistory.getActive();
// make sure to set the role, transition and reversal
// as most of this is lost by the domCache cleaning
$.extend( changePageOptions, {
role: active.role,
transition: active.transition,
reverse: data.direction === "back"
});
}
}
//if to is defined, load it
if ( to ) {
// At this point, 'to' can be one of 3 things, a cached page element from
// a history stack entry, an id, or site-relative/absolute URL. If 'to' is
// an id, we need to resolve it against the documentBase, not the location.href,
// since the hashchange could've been the result of a forward/backward navigation
// that crosses from an external page/dialog to an internal page/dialog.
to = !path.isPath( to ) ? ( path.makeUrlAbsolute( '#' + to, documentBase ) ) : to;
// If we're about to go to an initial URL that contains a reference to a non-existent
// internal page, go to the first page instead. We know that the initial hash refers to a
// non-existent page, because the initial hash did not end up in the initial urlHistory entry
if ( to === path.makeUrlAbsolute( '#' + urlHistory.initialDst, documentBase ) &&
urlHistory.stack.length && urlHistory.stack[0].url !== urlHistory.initialDst.replace( dialogHashKey, "" ) ) {
to = $.mobile.firstPage;
}
$.mobile.changePage( to, changePageOptions );
} else {
//there's no hash, go to the first page in the dom
$.mobile.changePage( $.mobile.firstPage, changePageOptions );
}
};
// TODO roll the logic here into the handleHashChange method
$window.bind( "navigate", function( e, data ) {
var url;
if ( e.originalEvent && e.originalEvent.isDefaultPrevented() ) {
return;
}
url = $.event.special.navigate.originalEventName.indexOf( "hashchange" ) > -1 ? data.state.hash : data.state.url;
if( !url ) {
url = $.mobile.path.parseLocation().hash;
}
if( !url || url === "#" || url.indexOf( "#" + $.mobile.path.uiStateKey ) === 0 ){
url = location.href;
}
$.mobile._handleHashChange( url, data.state );
});
//set page min-heights to be device specific
$.mobile.document.bind( "pageshow", $.mobile.resetActivePageHeight );
$.mobile.window.bind( "throttledresize", $.mobile.resetActivePageHeight );
};//navreadyDeferred done callback
$( function() { domreadyDeferred.resolve(); } );
$.when( domreadyDeferred, $.mobile.navreadyDeferred ).done( function() { $.mobile._registerInternalEvents(); } );
})( jQuery );
/*
* fallback transition for flip in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.flip = "fade";
})( jQuery, this );
/*
* fallback transition for flow in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.flow = "fade";
})( jQuery, this );
/*
* fallback transition for pop in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.pop = "fade";
})( jQuery, this );
/*
* fallback transition for slide in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
// Use the simultaneous transitions handler for slide transitions
$.mobile.transitionHandlers.slide = $.mobile.transitionHandlers.simultaneous;
// Set the slide transitions's fallback to "fade"
$.mobile.transitionFallbacks.slide = "fade";
})( jQuery, this );
/*
* fallback transition for slidedown in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.slidedown = "fade";
})( jQuery, this );
/*
* fallback transition for slidefade in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
// Set the slide transitions's fallback to "fade"
$.mobile.transitionFallbacks.slidefade = "fade";
})( jQuery, this );
/*
* fallback transition for slideup in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.slideup = "fade";
})( jQuery, this );
/*
* fallback transition for turn in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.turn = "fade";
})( jQuery, this );
(function( $, undefined ) {
$.mobile.page.prototype.options.degradeInputs = {
color: false,
date: false,
datetime: false,
"datetime-local": false,
email: false,
month: false,
number: false,
range: "number",
search: "text",
tel: false,
time: false,
url: false,
week: false
};
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
var page = $.mobile.closestPageData( $( e.target ) ), options;
if ( !page ) {
return;
}
options = page.options;
// degrade inputs to avoid poorly implemented native functionality
$( e.target ).find( "input" ).not( page.keepNativeSelector() ).each(function() {
var $this = $( this ),
type = this.getAttribute( "type" ),
optType = options.degradeInputs[ type ] || "text";
if ( options.degradeInputs[ type ] ) {
var html = $( "<div>" ).html( $this.clone() ).html(),
// In IE browsers, the type sometimes doesn't exist in the cloned markup, so we replace the closing tag instead
hasType = html.indexOf( " type=" ) > -1,
findstr = hasType ? /\s+type=["']?\w+['"]?/ : /\/?>/,
repstr = " type=\"" + optType + "\" data-" + $.mobile.ns + "type=\"" + type + "\"" + ( hasType ? "" : ">" );
$this.replaceWith( html.replace( findstr, repstr ) );
}
});
});
})( jQuery );
(function( $, window, undefined ) {
$.widget( "mobile.dialog", $.mobile.widget, {
options: {
closeBtn: "left",
closeBtnText: "Close",
overlayTheme: "a",
corners: true,
initSelector: ":jqmData(role='dialog')"
},
// Override the theme set by the page plugin on pageshow
_handlePageBeforeShow: function() {
this._isCloseable = true;
if ( this.options.overlayTheme ) {
this.element
.page( "removeContainerBackground" )
.page( "setContainerBackground", this.options.overlayTheme );
}
},
_handlePageBeforeHide: function() {
this._isCloseable = false;
},
_create: function() {
var self = this,
$el = this.element,
cornerClass = !!this.options.corners ? " ui-corner-all" : "",
dialogWrap = $( "<div/>", {
"role" : "dialog",
"class" : "ui-dialog-contain ui-overlay-shadow" + cornerClass
});
$el.addClass( "ui-dialog ui-overlay-" + this.options.overlayTheme );
// Class the markup for dialog styling
// Set aria role
$el.wrapInner( dialogWrap );
/* bind events
- clicks and submits should use the closing transition that the dialog opened with
unless a data-transition is specified on the link/form
- if the click was on the close button, or the link has a data-rel="back" it'll go back in history naturally
*/
$el.bind( "vclick submit", function( event ) {
var $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ),
active;
if ( $target.length && !$target.jqmData( "transition" ) ) {
active = $.mobile.urlHistory.getActive() || {};
$target.attr( "data-" + $.mobile.ns + "transition", ( active.transition || $.mobile.defaultDialogTransition ) )
.attr( "data-" + $.mobile.ns + "direction", "reverse" );
}
});
this._on( $el, {
pagebeforeshow: "_handlePageBeforeShow",
pagebeforehide: "_handlePageBeforeHide"
});
$.extend( this, {
_createComplete: false
});
this._setCloseBtn( this.options.closeBtn );
},
_setCloseBtn: function( value ) {
var self = this, btn, location;
if ( this._headerCloseButton ) {
this._headerCloseButton.remove();
this._headerCloseButton = null;
}
if ( value !== "none" ) {
// Sanitize value
location = ( value === "left" ? "left" : "right" );
btn = $( "<a href='#' class='ui-btn-" + location + "' data-" + $.mobile.ns + "icon='delete' data-" + $.mobile.ns + "iconpos='notext'>"+ this.options.closeBtnText + "</a>" );
this.element.children().find( ":jqmData(role='header')" ).first().prepend( btn );
if ( this._createComplete && $.fn.buttonMarkup ) {
btn.buttonMarkup();
}
this._createComplete = true;
// this must be an anonymous function so that select menu dialogs can replace
// the close method. This is a change from previously just defining data-rel=back
// on the button and letting nav handle it
//
// Use click rather than vclick in order to prevent the possibility of unintentionally
// reopening the dialog if the dialog opening item was directly under the close button.
btn.bind( "click", function() {
self.close();
});
this._headerCloseButton = btn;
}
},
_setOption: function( key, value ) {
if ( key === "closeBtn" ) {
this._setCloseBtn( value );
}
this._super( key, value );
},
// Close method goes back in history
close: function() {
var idx, dst, hist = $.mobile.navigate.history;
if ( this._isCloseable ) {
this._isCloseable = false;
// If the hash listening is enabled and there is at least one preceding history
// entry it's ok to go back. Initial pages with the dialog hash state are an example
// where the stack check is necessary
if ( $.mobile.hashListeningEnabled && hist.activeIndex > 0 ) {
$.mobile.back();
} else {
idx = Math.max( 0, hist.activeIndex - 1 );
dst = hist.stack[ idx ].pageUrl || hist.stack[ idx ].url;
hist.previousIndex = hist.activeIndex;
hist.activeIndex = idx;
if ( !$.mobile.path.isPath( dst ) ) {
dst = $.mobile.path.makeUrlAbsolute( "#" + dst );
}
$.mobile.changePage( dst, { direction: "back", changeHash: false, fromHashChange: true } );
}
}
}
});
//auto self-init widgets
$.mobile.document.delegate( $.mobile.dialog.prototype.options.initSelector, "pagecreate", function() {
$.mobile.dialog.prototype.enhance( this );
});
})( jQuery, this );
(function( $, undefined ) {
$.mobile.page.prototype.options.backBtnText = "Back";
$.mobile.page.prototype.options.addBackBtn = false;
$.mobile.page.prototype.options.backBtnTheme = null;
$.mobile.page.prototype.options.headerTheme = "a";
$.mobile.page.prototype.options.footerTheme = "a";
$.mobile.page.prototype.options.contentTheme = null;
// NOTE bind used to force this binding to run before the buttonMarkup binding
// which expects .ui-footer top be applied in its gigantic selector
// TODO remove the buttonMarkup giant selector and move it to the various modules
// on which it depends
$.mobile.document.bind( "pagecreate", function( e ) {
var $page = $( e.target ),
o = $page.data( "mobile-page" ).options,
pageRole = $page.jqmData( "role" ),
pageTheme = o.theme;
$( ":jqmData(role='header'), :jqmData(role='footer'), :jqmData(role='content')", $page )
.jqmEnhanceable()
.each(function() {
var $this = $( this ),
role = $this.jqmData( "role" ),
theme = $this.jqmData( "theme" ),
contentTheme = theme || o.contentTheme || ( pageRole === "dialog" && pageTheme ),
$headeranchors,
leftbtn,
rightbtn,
backBtn;
$this.addClass( "ui-" + role );
//apply theming and markup modifications to page,header,content,footer
if ( role === "header" || role === "footer" ) {
var thisTheme = theme || ( role === "header" ? o.headerTheme : o.footerTheme ) || pageTheme;
$this
//add theme class
.addClass( "ui-bar-" + thisTheme )
// Add ARIA role
.attr( "role", role === "header" ? "banner" : "contentinfo" );
if ( role === "header") {
// Right,left buttons
$headeranchors = $this.children( "a, button" );
leftbtn = $headeranchors.hasClass( "ui-btn-left" );
rightbtn = $headeranchors.hasClass( "ui-btn-right" );
leftbtn = leftbtn || $headeranchors.eq( 0 ).not( ".ui-btn-right" ).addClass( "ui-btn-left" ).length;
rightbtn = rightbtn || $headeranchors.eq( 1 ).addClass( "ui-btn-right" ).length;
}
// Auto-add back btn on pages beyond first view
if ( o.addBackBtn &&
role === "header" &&
$( ".ui-page" ).length > 1 &&
$page.jqmData( "url" ) !== $.mobile.path.stripHash( location.hash ) &&
!leftbtn ) {
backBtn = $( "<a href='javascript:void(0);' class='ui-btn-left' data-"+ $.mobile.ns +"rel='back' data-"+ $.mobile.ns +"icon='arrow-l'>"+ o.backBtnText +"</a>" )
// If theme is provided, override default inheritance
.attr( "data-"+ $.mobile.ns +"theme", o.backBtnTheme || thisTheme )
.prependTo( $this );
}
// Page title
$this.children( "h1, h2, h3, h4, h5, h6" )
.addClass( "ui-title" )
// Regardless of h element number in src, it becomes h1 for the enhanced page
.attr({
"role": "heading",
"aria-level": "1"
});
} else if ( role === "content" ) {
if ( contentTheme ) {
$this.addClass( "ui-body-" + ( contentTheme ) );
}
// Add ARIA role
$this.attr( "role", "main" );
}
});
});
})( jQuery );
(function( $, undefined ) {
// This function calls getAttribute, which should be safe for data-* attributes
var getAttrFixed = function( e, key ) {
var value = e.getAttribute( key );
return value === "true" ? true :
value === "false" ? false :
value === null ? undefined : value;
};
$.fn.buttonMarkup = function( options ) {
var $workingSet = this,
nsKey = "data-" + $.mobile.ns,
key;
// Enforce options to be of type string
options = ( options && ( $.type( options ) === "object" ) )? options : {};
for ( var i = 0; i < $workingSet.length; i++ ) {
var el = $workingSet.eq( i ),
e = el[ 0 ],
o = $.extend( {}, $.fn.buttonMarkup.defaults, {
icon: options.icon !== undefined ? options.icon : getAttrFixed( e, nsKey + "icon" ),
iconpos: options.iconpos !== undefined ? options.iconpos : getAttrFixed( e, nsKey + "iconpos" ),
theme: options.theme !== undefined ? options.theme : getAttrFixed( e, nsKey + "theme" ) || $.mobile.getInheritedTheme( el, "c" ),
inline: options.inline !== undefined ? options.inline : getAttrFixed( e, nsKey + "inline" ),
shadow: options.shadow !== undefined ? options.shadow : getAttrFixed( e, nsKey + "shadow" ),
corners: options.corners !== undefined ? options.corners : getAttrFixed( e, nsKey + "corners" ),
iconshadow: options.iconshadow !== undefined ? options.iconshadow : getAttrFixed( e, nsKey + "iconshadow" ),
mini: options.mini !== undefined ? options.mini : getAttrFixed( e, nsKey + "mini" )
}, options ),
// Classes Defined
innerClass = "ui-btn-inner",
textClass = "ui-btn-text",
buttonClass, iconClass,
hover = false,
state = "up",
// Button inner markup
buttonInner,
buttonText,
buttonIcon,
buttonElements;
for ( key in o ) {
if ( o[ key ] === undefined || o[ key ] === null ) {
el.removeAttr( nsKey + key );
} else {
e.setAttribute( nsKey + key, o[ key ] );
}
}
// Check if this element is already enhanced
buttonElements = $.data( ( ( e.tagName === "INPUT" || e.tagName === "BUTTON" ) ? e.parentNode : e ), "buttonElements" );
if ( buttonElements ) {
e = buttonElements.outer;
el = $( e );
buttonInner = buttonElements.inner;
buttonText = buttonElements.text;
// We will recreate this icon below
$( buttonElements.icon ).remove();
buttonElements.icon = null;
hover = buttonElements.hover;
state = buttonElements.state;
}
else {
buttonInner = document.createElement( o.wrapperEls );
buttonText = document.createElement( o.wrapperEls );
}
buttonIcon = o.icon ? document.createElement( "span" ) : null;
if ( attachEvents && !buttonElements ) {
attachEvents();
}
// if not, try to find closest theme container
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( el, "c" );
}
buttonClass = "ui-btn ";
buttonClass += ( hover ? "ui-btn-hover-" + o.theme : "" );
buttonClass += ( state ? " ui-btn-" + state + "-" + o.theme : "" );
buttonClass += o.shadow ? " ui-shadow" : "";
buttonClass += o.corners ? " ui-btn-corner-all" : "";
if ( o.mini !== undefined ) {
// Used to control styling in headers/footers, where buttons default to `mini` style.
buttonClass += o.mini === true ? " ui-mini" : " ui-fullsize";
}
if ( o.inline !== undefined ) {
// Used to control styling in headers/footers, where buttons default to `inline` style.
buttonClass += o.inline === true ? " ui-btn-inline" : " ui-btn-block";
}
if ( o.icon ) {
o.icon = "ui-icon-" + o.icon;
o.iconpos = o.iconpos || "left";
iconClass = "ui-icon " + o.icon;
if ( o.iconshadow ) {
iconClass += " ui-icon-shadow";
}
}
if ( o.iconpos ) {
buttonClass += " ui-btn-icon-" + o.iconpos;
if ( o.iconpos === "notext" && !el.attr( "title" ) ) {
el.attr( "title", el.getEncodedText() );
}
}
if ( buttonElements ) {
el.removeClass( buttonElements.bcls || "" );
}
el.removeClass( "ui-link" ).addClass( buttonClass );
buttonInner.className = innerClass;
buttonText.className = textClass;
if ( !buttonElements ) {
buttonInner.appendChild( buttonText );
}
if ( buttonIcon ) {
buttonIcon.className = iconClass;
if ( !( buttonElements && buttonElements.icon ) ) {
buttonIcon.innerHTML = " ";
buttonInner.appendChild( buttonIcon );
}
}
while ( e.firstChild && !buttonElements ) {
buttonText.appendChild( e.firstChild );
}
if ( !buttonElements ) {
e.appendChild( buttonInner );
}
// Assign a structure containing the elements of this button to the elements of this button. This
// will allow us to recognize this as an already-enhanced button in future calls to buttonMarkup().
buttonElements = {
hover : hover,
state : state,
bcls : buttonClass,
outer : e,
inner : buttonInner,
text : buttonText,
icon : buttonIcon
};
$.data( e, 'buttonElements', buttonElements );
$.data( buttonInner, 'buttonElements', buttonElements );
$.data( buttonText, 'buttonElements', buttonElements );
if ( buttonIcon ) {
$.data( buttonIcon, 'buttonElements', buttonElements );
}
}
return this;
};
$.fn.buttonMarkup.defaults = {
corners: true,
shadow: true,
iconshadow: true,
wrapperEls: "span"
};
function closestEnabledButton( element ) {
var cname;
while ( element ) {
// Note that we check for typeof className below because the element we
// handed could be in an SVG DOM where className on SVG elements is defined to
// be of a different type (SVGAnimatedString). We only operate on HTML DOM
// elements, so we look for plain "string".
cname = ( typeof element.className === 'string' ) && ( element.className + ' ' );
if ( cname && cname.indexOf( "ui-btn " ) > -1 && cname.indexOf( "ui-disabled " ) < 0 ) {
break;
}
element = element.parentNode;
}
return element;
}
function updateButtonClass( $btn, classToRemove, classToAdd, hover, state ) {
var buttonElements = $.data( $btn[ 0 ], "buttonElements" );
$btn.removeClass( classToRemove ).addClass( classToAdd );
if ( buttonElements ) {
buttonElements.bcls = $( document.createElement( "div" ) )
.addClass( buttonElements.bcls + " " + classToAdd )
.removeClass( classToRemove )
.attr( "class" );
if ( hover !== undefined ) {
buttonElements.hover = hover;
}
buttonElements.state = state;
}
}
var attachEvents = function() {
var hoverDelay = $.mobile.buttonMarkup.hoverDelay, hov, foc;
$.mobile.document.bind( {
"vmousedown vmousecancel vmouseup vmouseover vmouseout focus blur scrollstart": function( event ) {
var theme,
$btn = $( closestEnabledButton( event.target ) ),
isTouchEvent = event.originalEvent && /^touch/.test( event.originalEvent.type ),
evt = event.type;
if ( $btn.length ) {
theme = $btn.attr( "data-" + $.mobile.ns + "theme" );
if ( evt === "vmousedown" ) {
if ( isTouchEvent ) {
// Use a short delay to determine if the user is scrolling before highlighting
hov = setTimeout( function() {
updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-down-" + theme, undefined, "down" );
}, hoverDelay );
} else {
updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-down-" + theme, undefined, "down" );
}
} else if ( evt === "vmousecancel" || evt === "vmouseup" ) {
updateButtonClass( $btn, "ui-btn-down-" + theme, "ui-btn-up-" + theme, undefined, "up" );
} else if ( evt === "vmouseover" || evt === "focus" ) {
if ( isTouchEvent ) {
// Use a short delay to determine if the user is scrolling before highlighting
foc = setTimeout( function() {
updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-hover-" + theme, true, "" );
}, hoverDelay );
} else {
updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-hover-" + theme, true, "" );
}
} else if ( evt === "vmouseout" || evt === "blur" || evt === "scrollstart" ) {
updateButtonClass( $btn, "ui-btn-hover-" + theme + " ui-btn-down-" + theme, "ui-btn-up-" + theme, false, "up" );
if ( hov ) {
clearTimeout( hov );
}
if ( foc ) {
clearTimeout( foc );
}
}
}
},
"focusin focus": function( event ) {
$( closestEnabledButton( event.target ) ).addClass( $.mobile.focusClass );
},
"focusout blur": function( event ) {
$( closestEnabledButton( event.target ) ).removeClass( $.mobile.focusClass );
}
});
attachEvents = null;
};
//links in bars, or those with data-role become buttons
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$( ":jqmData(role='button'), .ui-bar > a, .ui-header > a, .ui-footer > a, .ui-bar > :jqmData(role='controlgroup') > a", e.target )
.jqmEnhanceable()
.not( "button, input, .ui-btn, :jqmData(role='none'), :jqmData(role='nojs')" )
.buttonMarkup();
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.collapsible", $.mobile.widget, {
options: {
expandCueText: " click to expand contents",
collapseCueText: " click to collapse contents",
collapsed: true,
heading: "h1,h2,h3,h4,h5,h6,legend",
collapsedIcon: "plus",
expandedIcon: "minus",
iconpos: "left",
theme: null,
contentTheme: null,
inset: true,
corners: true,
mini: false,
initSelector: ":jqmData(role='collapsible')"
},
_create: function() {
var $el = this.element,
o = this.options,
collapsible = $el.addClass( "ui-collapsible" ),
collapsibleHeading = $el.children( o.heading ).first(),
collapsibleContent = collapsible.wrapInner( "<div class='ui-collapsible-content'></div>" ).children( ".ui-collapsible-content" ),
collapsibleSet = $el.closest( ":jqmData(role='collapsible-set')" ).addClass( "ui-collapsible-set" ),
collapsibleClasses = "";
// Replace collapsibleHeading if it's a legend
if ( collapsibleHeading.is( "legend" ) ) {
collapsibleHeading = $( "<div role='heading'>"+ collapsibleHeading.html() +"</div>" ).insertBefore( collapsibleHeading );
collapsibleHeading.next().remove();
}
// If we are in a collapsible set
if ( collapsibleSet.length ) {
// Inherit the theme from collapsible-set
if ( !o.theme ) {
o.theme = collapsibleSet.jqmData( "theme" ) || $.mobile.getInheritedTheme( collapsibleSet, "c" );
}
// Inherit the content-theme from collapsible-set
if ( !o.contentTheme ) {
o.contentTheme = collapsibleSet.jqmData( "content-theme" );
}
// Get the preference for collapsed icon in the set, but override with data- attribute on the individual collapsible
o.collapsedIcon = $el.jqmData( "collapsed-icon" ) || collapsibleSet.jqmData( "collapsed-icon" ) || o.collapsedIcon;
// Get the preference for expanded icon in the set, but override with data- attribute on the individual collapsible
o.expandedIcon = $el.jqmData( "expanded-icon" ) || collapsibleSet.jqmData( "expanded-icon" ) || o.expandedIcon;
// Gets the preference icon position in the set, but override with data- attribute on the individual collapsible
o.iconpos = $el.jqmData( "iconpos" ) || collapsibleSet.jqmData( "iconpos" ) || o.iconpos;
// Inherit the preference for inset from collapsible-set or set the default value to ensure equalty within a set
if ( collapsibleSet.jqmData( "inset" ) !== undefined ) {
o.inset = collapsibleSet.jqmData( "inset" );
} else {
o.inset = true;
}
// Set corners for individual collapsibles to false when in a collapsible-set
o.corners = false;
// Gets the preference for mini in the set
if ( !o.mini ) {
o.mini = collapsibleSet.jqmData( "mini" );
}
} else {
// get inherited theme if not a set and no theme has been set
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( $el, "c" );
}
}
if ( !!o.inset ) {
collapsibleClasses += " ui-collapsible-inset";
if ( !!o.corners ) {
collapsibleClasses += " ui-corner-all" ;
}
}
if ( o.contentTheme ) {
collapsibleClasses += " ui-collapsible-themed-content";
collapsibleContent.addClass( "ui-body-" + o.contentTheme );
}
if ( collapsibleClasses !== "" ) {
collapsible.addClass( collapsibleClasses );
}
collapsibleHeading
//drop heading in before content
.insertBefore( collapsibleContent )
//modify markup & attributes
.addClass( "ui-collapsible-heading" )
.append( "<span class='ui-collapsible-heading-status'></span>" )
.wrapInner( "<a href='#' class='ui-collapsible-heading-toggle'></a>" )
.find( "a" )
.first()
.buttonMarkup({
shadow: false,
corners: false,
iconpos: o.iconpos,
icon: o.collapsedIcon,
mini: o.mini,
theme: o.theme
});
//events
collapsible
.bind( "expand collapse", function( event ) {
if ( !event.isDefaultPrevented() ) {
var $this = $( this ),
isCollapse = ( event.type === "collapse" );
event.preventDefault();
collapsibleHeading
.toggleClass( "ui-collapsible-heading-collapsed", isCollapse )
.find( ".ui-collapsible-heading-status" )
.text( isCollapse ? o.expandCueText : o.collapseCueText )
.end()
.find( ".ui-icon" )
.toggleClass( "ui-icon-" + o.expandedIcon, !isCollapse )
// logic or cause same icon for expanded/collapsed state would remove the ui-icon-class
.toggleClass( "ui-icon-" + o.collapsedIcon, ( isCollapse || o.expandedIcon === o.collapsedIcon ) )
.end()
.find( "a" ).first().removeClass( $.mobile.activeBtnClass );
$this.toggleClass( "ui-collapsible-collapsed", isCollapse );
collapsibleContent.toggleClass( "ui-collapsible-content-collapsed", isCollapse ).attr( "aria-hidden", isCollapse );
collapsibleContent.trigger( "updatelayout" );
}
})
.trigger( o.collapsed ? "collapse" : "expand" );
collapsibleHeading
.bind( "tap", function( event ) {
collapsibleHeading.find( "a" ).first().addClass( $.mobile.activeBtnClass );
})
.bind( "click", function( event ) {
var type = collapsibleHeading.is( ".ui-collapsible-heading-collapsed" ) ? "expand" : "collapse";
collapsible.trigger( type );
event.preventDefault();
event.stopPropagation();
});
}
});
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.collapsible.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
$.mobile.behaviors.addFirstLastClasses = {
_getVisibles: function( $els, create ) {
var visibles;
if ( create ) {
visibles = $els.not( ".ui-screen-hidden" );
} else {
visibles = $els.filter( ":visible" );
if ( visibles.length === 0 ) {
visibles = $els.not( ".ui-screen-hidden" );
}
}
return visibles;
},
_addFirstLastClasses: function( $els, $visibles, create ) {
$els.removeClass( "ui-first-child ui-last-child" );
$visibles.eq( 0 ).addClass( "ui-first-child" ).end().last().addClass( "ui-last-child" );
if ( !create ) {
this.element.trigger( "updatelayout" );
}
}
};
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.collapsibleset", $.mobile.widget, $.extend( {
options: {
initSelector: ":jqmData(role='collapsible-set')"
},
_create: function() {
var $el = this.element.addClass( "ui-collapsible-set" ),
o = this.options;
// Inherit the theme from collapsible-set
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( $el, "c" );
}
// Inherit the content-theme from collapsible-set
if ( !o.contentTheme ) {
o.contentTheme = $el.jqmData( "content-theme" );
}
// Inherit the corner styling from collapsible-set
if ( !o.corners ) {
o.corners = $el.jqmData( "corners" );
}
if ( $el.jqmData( "inset" ) !== undefined ) {
o.inset = $el.jqmData( "inset" );
}
o.inset = o.inset !== undefined ? o.inset : true;
o.corners = o.corners !== undefined ? o.corners : true;
if ( !!o.corners && !!o.inset ) {
$el.addClass( "ui-corner-all" );
}
// Initialize the collapsible set if it's not already initialized
if ( !$el.jqmData( "collapsiblebound" ) ) {
$el
.jqmData( "collapsiblebound", true )
.bind( "expand", function( event ) {
var closestCollapsible = $( event.target )
.closest( ".ui-collapsible" );
if ( closestCollapsible.parent().is( ":jqmData(role='collapsible-set')" ) ) {
closestCollapsible
.siblings( ".ui-collapsible" )
.trigger( "collapse" );
}
});
}
},
_init: function() {
var $el = this.element,
collapsiblesInSet = $el.children( ":jqmData(role='collapsible')" ),
expanded = collapsiblesInSet.filter( ":jqmData(collapsed='false')" );
this._refresh( "true" );
// Because the corners are handled by the collapsible itself and the default state is collapsed
// That was causing https://github.com/jquery/jquery-mobile/issues/4116
expanded.trigger( "expand" );
},
_refresh: function( create ) {
var collapsiblesInSet = this.element.children( ":jqmData(role='collapsible')" );
$.mobile.collapsible.prototype.enhance( collapsiblesInSet.not( ".ui-collapsible" ) );
this._addFirstLastClasses( collapsiblesInSet, this._getVisibles( collapsiblesInSet, create ), create );
},
refresh: function() {
this._refresh( false );
}
}, $.mobile.behaviors.addFirstLastClasses ) );
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.collapsibleset.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
// filter function removes whitespace between label and form element so we can use inline-block (nodeType 3 = text)
$.fn.fieldcontain = function( options ) {
return this
.addClass( "ui-field-contain ui-body ui-br" )
.contents().filter( function() {
return ( this.nodeType === 3 && !/\S/.test( this.nodeValue ) );
}).remove();
};
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ) {
$( ":jqmData(role='fieldcontain')", e.target ).jqmEnhanceable().fieldcontain();
});
})( jQuery );
(function( $, undefined ) {
$.fn.grid = function( options ) {
return this.each(function() {
var $this = $( this ),
o = $.extend({
grid: null
}, options ),
$kids = $this.children(),
gridCols = { solo:1, a:2, b:3, c:4, d:5 },
grid = o.grid,
iterator;
if ( !grid ) {
if ( $kids.length <= 5 ) {
for ( var letter in gridCols ) {
if ( gridCols[ letter ] === $kids.length ) {
grid = letter;
}
}
} else {
grid = "a";
$this.addClass( "ui-grid-duo" );
}
}
iterator = gridCols[grid];
$this.addClass( "ui-grid-" + grid );
$kids.filter( ":nth-child(" + iterator + "n+1)" ).addClass( "ui-block-a" );
if ( iterator > 1 ) {
$kids.filter( ":nth-child(" + iterator + "n+2)" ).addClass( "ui-block-b" );
}
if ( iterator > 2 ) {
$kids.filter( ":nth-child(" + iterator + "n+3)" ).addClass( "ui-block-c" );
}
if ( iterator > 3 ) {
$kids.filter( ":nth-child(" + iterator + "n+4)" ).addClass( "ui-block-d" );
}
if ( iterator > 4 ) {
$kids.filter( ":nth-child(" + iterator + "n+5)" ).addClass( "ui-block-e" );
}
});
};
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.navbar", $.mobile.widget, {
options: {
iconpos: "top",
grid: null,
initSelector: ":jqmData(role='navbar')"
},
_create: function() {
var $navbar = this.element,
$navbtns = $navbar.find( "a" ),
iconpos = $navbtns.filter( ":jqmData(icon)" ).length ?
this.options.iconpos : undefined;
$navbar.addClass( "ui-navbar ui-mini" )
.attr( "role", "navigation" )
.find( "ul" )
.jqmEnhanceable()
.grid({ grid: this.options.grid });
$navbtns.buttonMarkup({
corners: false,
shadow: false,
inline: true,
iconpos: iconpos
});
$navbar.delegate( "a", "vclick", function( event ) {
// ui-btn-inner is returned as target
var target = $( event.target ).is( "a" ) ? $( this ) : $( this ).parent( "a" );
if ( !target.is( ".ui-disabled, .ui-btn-active" ) ) {
$navbtns.removeClass( $.mobile.activeBtnClass );
$( this ).addClass( $.mobile.activeBtnClass );
// The code below is a workaround to fix #1181
var activeBtn = $( this );
$( document ).one( "pagehide", function() {
activeBtn.removeClass( $.mobile.activeBtnClass );
});
}
});
// Buttons in the navbar with ui-state-persist class should regain their active state before page show
$navbar.closest( ".ui-page" ).bind( "pagebeforeshow", function() {
$navbtns.filter( ".ui-state-persist" ).addClass( $.mobile.activeBtnClass );
});
}
});
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.navbar.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
//Keeps track of the number of lists per page UID
//This allows support for multiple nested list in the same page
//https://github.com/jquery/jquery-mobile/issues/1617
var listCountPerPage = {};
$.widget( "mobile.listview", $.mobile.widget, $.extend( {
options: {
theme: null,
countTheme: "c",
headerTheme: "b",
dividerTheme: "b",
icon: "arrow-r",
splitIcon: "arrow-r",
splitTheme: "b",
corners: true,
shadow: true,
inset: false,
initSelector: ":jqmData(role='listview')"
},
_create: function() {
var t = this,
listviewClasses = "";
listviewClasses += t.options.inset ? " ui-listview-inset" : "";
if ( !!t.options.inset ) {
listviewClasses += t.options.corners ? " ui-corner-all" : "";
listviewClasses += t.options.shadow ? " ui-shadow" : "";
}
// create listview markup
t.element.addClass(function( i, orig ) {
return orig + " ui-listview" + listviewClasses;
});
t.refresh( true );
},
// This is a generic utility method for finding the first
// node with a given nodeName. It uses basic DOM traversal
// to be fast and is meant to be a substitute for simple
// $.fn.closest() and $.fn.children() calls on a single
// element. Note that callers must pass both the lowerCase
// and upperCase version of the nodeName they are looking for.
// The main reason for this is that this function will be
// called many times and we want to avoid having to lowercase
// the nodeName from the element every time to ensure we have
// a match. Note that this function lives here for now, but may
// be moved into $.mobile if other components need a similar method.
_findFirstElementByTagName: function( ele, nextProp, lcName, ucName ) {
var dict = {};
dict[ lcName ] = dict[ ucName ] = true;
while ( ele ) {
if ( dict[ ele.nodeName ] ) {
return ele;
}
ele = ele[ nextProp ];
}
return null;
},
_getChildrenByTagName: function( ele, lcName, ucName ) {
var results = [],
dict = {};
dict[ lcName ] = dict[ ucName ] = true;
ele = ele.firstChild;
while ( ele ) {
if ( dict[ ele.nodeName ] ) {
results.push( ele );
}
ele = ele.nextSibling;
}
return $( results );
},
_addThumbClasses: function( containers ) {
var i, img, len = containers.length;
for ( i = 0; i < len; i++ ) {
img = $( this._findFirstElementByTagName( containers[ i ].firstChild, "nextSibling", "img", "IMG" ) );
if ( img.length ) {
img.addClass( "ui-li-thumb" );
$( this._findFirstElementByTagName( img[ 0 ].parentNode, "parentNode", "li", "LI" ) ).addClass( img.is( ".ui-li-icon" ) ? "ui-li-has-icon" : "ui-li-has-thumb" );
}
}
},
refresh: function( create ) {
this.parentPage = this.element.closest( ".ui-page" );
this._createSubPages();
var o = this.options,
$list = this.element,
self = this,
dividertheme = $list.jqmData( "dividertheme" ) || o.dividerTheme,
listsplittheme = $list.jqmData( "splittheme" ),
listspliticon = $list.jqmData( "spliticon" ),
listicon = $list.jqmData( "icon" ),
li = this._getChildrenByTagName( $list[ 0 ], "li", "LI" ),
ol = !!$.nodeName( $list[ 0 ], "ol" ),
jsCount = !$.support.cssPseudoElement,
start = $list.attr( "start" ),
itemClassDict = {},
item, itemClass, itemTheme,
a, last, splittheme, counter, startCount, newStartCount, countParent, icon, imgParents, img, linkIcon;
if ( ol && jsCount ) {
$list.find( ".ui-li-dec" ).remove();
}
if ( ol ) {
// Check if a start attribute has been set while taking a value of 0 into account
if ( start || start === 0 ) {
if ( !jsCount ) {
startCount = parseInt( start , 10 ) - 1;
$list.css( "counter-reset", "listnumbering " + startCount );
} else {
counter = parseInt( start , 10 );
}
} else if ( jsCount ) {
counter = 1;
}
}
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( this.element, "c" );
}
for ( var pos = 0, numli = li.length; pos < numli; pos++ ) {
item = li.eq( pos );
itemClass = "ui-li";
// If we're creating the element, we update it regardless
if ( create || !item.hasClass( "ui-li" ) ) {
itemTheme = item.jqmData( "theme" ) || o.theme;
a = this._getChildrenByTagName( item[ 0 ], "a", "A" );
var isDivider = ( item.jqmData( "role" ) === "list-divider" );
if ( a.length && !isDivider ) {
icon = item.jqmData( "icon" );
item.buttonMarkup({
wrapperEls: "div",
shadow: false,
corners: false,
iconpos: "right",
icon: a.length > 1 || icon === false ? false : icon || listicon || o.icon,
theme: itemTheme
});
if ( ( icon !== false ) && ( a.length === 1 ) ) {
item.addClass( "ui-li-has-arrow" );
}
a.first().removeClass( "ui-link" ).addClass( "ui-link-inherit" );
if ( a.length > 1 ) {
itemClass += " ui-li-has-alt";
last = a.last();
splittheme = listsplittheme || last.jqmData( "theme" ) || o.splitTheme;
linkIcon = last.jqmData( "icon" );
last.appendTo( item )
.attr( "title", $.trim(last.getEncodedText()) )
.addClass( "ui-li-link-alt" )
.empty()
.buttonMarkup({
shadow: false,
corners: false,
theme: itemTheme,
icon: false,
iconpos: "notext"
})
.find( ".ui-btn-inner" )
.append(
$( document.createElement( "span" ) ).buttonMarkup({
shadow: true,
corners: true,
theme: splittheme,
iconpos: "notext",
// link icon overrides list item icon overrides ul element overrides options
icon: linkIcon || icon || listspliticon || o.splitIcon
})
);
}
} else if ( isDivider ) {
itemClass += " ui-li-divider ui-bar-" + ( item.jqmData( "theme" ) || dividertheme );
item.attr( "role", "heading" );
if ( ol ) {
//reset counter when a divider heading is encountered
if ( start || start === 0 ) {
if ( !jsCount ) {
newStartCount = parseInt( start , 10 ) - 1;
item.css( "counter-reset", "listnumbering " + newStartCount );
} else {
counter = parseInt( start , 10 );
}
} else if ( jsCount ) {
counter = 1;
}
}
} else {
itemClass += " ui-li-static ui-btn-up-" + itemTheme;
}
}
if ( ol && jsCount && itemClass.indexOf( "ui-li-divider" ) < 0 ) {
countParent = itemClass.indexOf( "ui-li-static" ) > 0 ? item : item.find( ".ui-link-inherit" );
countParent.addClass( "ui-li-jsnumbering" )
.prepend( "<span class='ui-li-dec'>" + ( counter++ ) + ". </span>" );
}
// Instead of setting item class directly on the list item and its
// btn-inner at this point in time, push the item into a dictionary
// that tells us what class to set on it so we can do this after this
// processing loop is finished.
if ( !itemClassDict[ itemClass ] ) {
itemClassDict[ itemClass ] = [];
}
itemClassDict[ itemClass ].push( item[ 0 ] );
}
// Set the appropriate listview item classes on each list item
// and their btn-inner elements. The main reason we didn't do this
// in the for-loop above is because we can eliminate per-item function overhead
// by calling addClass() and children() once or twice afterwards. This
// can give us a significant boost on platforms like WP7.5.
for ( itemClass in itemClassDict ) {
$( itemClassDict[ itemClass ] ).addClass( itemClass ).children( ".ui-btn-inner" ).addClass( itemClass );
}
$list.find( "h1, h2, h3, h4, h5, h6" ).addClass( "ui-li-heading" )
.end()
.find( "p, dl" ).addClass( "ui-li-desc" )
.end()
.find( ".ui-li-aside" ).each(function() {
var $this = $( this );
$this.prependTo( $this.parent() ); //shift aside to front for css float
})
.end()
.find( ".ui-li-count" ).each(function() {
$( this ).closest( "li" ).addClass( "ui-li-has-count" );
}).addClass( "ui-btn-up-" + ( $list.jqmData( "counttheme" ) || this.options.countTheme) + " ui-btn-corner-all" );
// The idea here is to look at the first image in the list item
// itself, and any .ui-link-inherit element it may contain, so we
// can place the appropriate classes on the image and list item.
// Note that we used to use something like:
//
// li.find(">img:eq(0), .ui-link-inherit>img:eq(0)").each( ... );
//
// But executing a find() like that on Windows Phone 7.5 took a
// really long time. Walking things manually with the code below
// allows the 400 listview item page to load in about 3 seconds as
// opposed to 30 seconds.
this._addThumbClasses( li );
this._addThumbClasses( $list.find( ".ui-link-inherit" ) );
this._addFirstLastClasses( li, this._getVisibles( li, create ), create );
// autodividers binds to this to redraw dividers after the listview refresh
this._trigger( "afterrefresh" );
},
//create a string for ID/subpage url creation
_idStringEscape: function( str ) {
return str.replace(/[^a-zA-Z0-9]/g, '-');
},
_createSubPages: function() {
var parentList = this.element,
parentPage = parentList.closest( ".ui-page" ),
parentUrl = parentPage.jqmData( "url" ),
parentId = parentUrl || parentPage[ 0 ][ $.expando ],
parentListId = parentList.attr( "id" ),
o = this.options,
dns = "data-" + $.mobile.ns,
self = this,
persistentFooterID = parentPage.find( ":jqmData(role='footer')" ).jqmData( "id" ),
hasSubPages;
if ( typeof listCountPerPage[ parentId ] === "undefined" ) {
listCountPerPage[ parentId ] = -1;
}
parentListId = parentListId || ++listCountPerPage[ parentId ];
$( parentList.find( "li>ul, li>ol" ).toArray().reverse() ).each(function( i ) {
var self = this,
list = $( this ),
listId = list.attr( "id" ) || parentListId + "-" + i,
parent = list.parent(),
nodeElsFull = $( list.prevAll().toArray().reverse() ),
nodeEls = nodeElsFull.length ? nodeElsFull : $( "<span>" + $.trim(parent.contents()[ 0 ].nodeValue) + "</span>" ),
title = nodeEls.first().getEncodedText(),//url limits to first 30 chars of text
id = ( parentUrl || "" ) + "&" + $.mobile.subPageUrlKey + "=" + listId,
theme = list.jqmData( "theme" ) || o.theme,
countTheme = list.jqmData( "counttheme" ) || parentList.jqmData( "counttheme" ) || o.countTheme,
newPage, anchor;
//define hasSubPages for use in later removal
hasSubPages = true;
newPage = list.detach()
.wrap( "<div " + dns + "role='page' " + dns + "url='" + id + "' " + dns + "theme='" + theme + "' " + dns + "count-theme='" + countTheme + "'><div " + dns + "role='content'></div></div>" )
.parent()
.before( "<div " + dns + "role='header' " + dns + "theme='" + o.headerTheme + "'><div class='ui-title'>" + title + "</div></div>" )
.after( persistentFooterID ? $( "<div " + dns + "role='footer' " + dns + "id='"+ persistentFooterID +"'>" ) : "" )
.parent()
.appendTo( $.mobile.pageContainer );
newPage.page();
anchor = parent.find( 'a:first' );
if ( !anchor.length ) {
anchor = $( "<a/>" ).html( nodeEls || title ).prependTo( parent.empty() );
}
anchor.attr( "href", "#" + id );
}).listview();
// on pagehide, remove any nested pages along with the parent page, as long as they aren't active
// and aren't embedded
if ( hasSubPages &&
parentPage.is( ":jqmData(external-page='true')" ) &&
parentPage.data( "mobile-page" ).options.domCache === false ) {
var newRemove = function( e, ui ) {
var nextPage = ui.nextPage, npURL,
prEvent = new $.Event( "pageremove" );
if ( ui.nextPage ) {
npURL = nextPage.jqmData( "url" );
if ( npURL.indexOf( parentUrl + "&" + $.mobile.subPageUrlKey ) !== 0 ) {
self.childPages().remove();
parentPage.trigger( prEvent );
if ( !prEvent.isDefaultPrevented() ) {
parentPage.removeWithDependents();
}
}
}
};
// unbind the original page remove and replace with our specialized version
parentPage
.unbind( "pagehide.remove" )
.bind( "pagehide.remove", newRemove);
}
},
// TODO sort out a better way to track sub pages of the listview this is brittle
childPages: function() {
var parentUrl = this.parentPage.jqmData( "url" );
return $( ":jqmData(url^='"+ parentUrl + "&" + $.mobile.subPageUrlKey + "')" );
}
}, $.mobile.behaviors.addFirstLastClasses ) );
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.listview.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $ ) {
var meta = $( "meta[name=viewport]" ),
initialContent = meta.attr( "content" ),
disabledZoom = initialContent + ",maximum-scale=1, user-scalable=no",
enabledZoom = initialContent + ",maximum-scale=10, user-scalable=yes",
disabledInitially = /(user-scalable[\s]*=[\s]*no)|(maximum-scale[\s]*=[\s]*1)[$,\s]/.test( initialContent );
$.mobile.zoom = $.extend( {}, {
enabled: !disabledInitially,
locked: false,
disable: function( lock ) {
if ( !disabledInitially && !$.mobile.zoom.locked ) {
meta.attr( "content", disabledZoom );
$.mobile.zoom.enabled = false;
$.mobile.zoom.locked = lock || false;
}
},
enable: function( unlock ) {
if ( !disabledInitially && ( !$.mobile.zoom.locked || unlock === true ) ) {
meta.attr( "content", enabledZoom );
$.mobile.zoom.enabled = true;
$.mobile.zoom.locked = false;
}
},
restore: function() {
if ( !disabledInitially ) {
meta.attr( "content", initialContent );
$.mobile.zoom.enabled = true;
}
}
});
}( jQuery ));
(function( $, undefined ) {
$.widget( "mobile.textinput", $.mobile.widget, {
options: {
theme: null,
mini: false,
// This option defaults to true on iOS devices.
preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1,
initSelector: "input[type='text'], input[type='search'], :jqmData(type='search'), input[type='number'], :jqmData(type='number'), input[type='password'], input[type='email'], input[type='url'], input[type='tel'], textarea, input[type='time'], input[type='date'], input[type='month'], input[type='week'], input[type='datetime'], input[type='datetime-local'], input[type='color'], input:not([type]), input[type='file']",
clearBtn: false,
clearSearchButtonText: null, //deprecating for 1.3...
clearBtnText: "clear text",
disabled: false
},
_create: function() {
var self = this,
input = this.element,
o = this.options,
theme = o.theme || $.mobile.getInheritedTheme( this.element, "c" ),
themeclass = " ui-body-" + theme,
miniclass = o.mini ? " ui-mini" : "",
isSearch = input.is( "[type='search'], :jqmData(type='search')" ),
focusedEl,
clearbtn,
clearBtnText = o.clearSearchButtonText || o.clearBtnText,
clearBtnBlacklist = input.is( "textarea, :jqmData(type='range')" ),
inputNeedsClearBtn = !!o.clearBtn && !clearBtnBlacklist,
inputNeedsWrap = input.is( "input" ) && !input.is( ":jqmData(type='range')" );
function toggleClear() {
setTimeout( function() {
clearbtn.toggleClass( "ui-input-clear-hidden", !input.val() );
}, 0 );
}
$( "label[for='" + input.attr( "id" ) + "']" ).addClass( "ui-input-text" );
focusedEl = input.addClass( "ui-input-text ui-body-"+ theme );
// XXX: Temporary workaround for issue 785 (Apple bug 8910589).
// Turn off autocorrect and autocomplete on non-iOS 5 devices
// since the popup they use can't be dismissed by the user. Note
// that we test for the presence of the feature by looking for
// the autocorrect property on the input element. We currently
// have no test for iOS 5 or newer so we're temporarily using
// the touchOverflow support flag for jQM 1.0. Yes, I feel dirty. - jblas
if ( typeof input[0].autocorrect !== "undefined" && !$.support.touchOverflow ) {
// Set the attribute instead of the property just in case there
// is code that attempts to make modifications via HTML.
input[0].setAttribute( "autocorrect", "off" );
input[0].setAttribute( "autocomplete", "off" );
}
//"search" and "text" input widgets
if ( isSearch ) {
focusedEl = input.wrap( "<div class='ui-input-search ui-shadow-inset ui-btn-corner-all ui-btn-shadow ui-icon-searchfield" + themeclass + miniclass + "'></div>" ).parent();
} else if ( inputNeedsWrap ) {
focusedEl = input.wrap( "<div class='ui-input-text ui-shadow-inset ui-corner-all ui-btn-shadow" + themeclass + miniclass + "'></div>" ).parent();
}
if( inputNeedsClearBtn || isSearch ) {
clearbtn = $( "<a href='#' class='ui-input-clear' title='" + clearBtnText + "'>" + clearBtnText + "</a>" )
.bind( "click", function( event ) {
input
.val( "" )
.focus()
.trigger( "change" );
clearbtn.addClass( "ui-input-clear-hidden" );
event.preventDefault();
})
.appendTo( focusedEl )
.buttonMarkup({
icon: "delete",
iconpos: "notext",
corners: true,
shadow: true,
mini: o.mini
});
if ( !isSearch ) {
focusedEl.addClass( "ui-input-has-clear" );
}
toggleClear();
input.bind( "paste cut keyup input focus change blur", toggleClear );
}
else if ( !inputNeedsWrap && !isSearch ) {
input.addClass( "ui-corner-all ui-shadow-inset" + themeclass + miniclass );
}
input.focus(function() {
// In many situations, iOS will zoom into the input upon tap, this prevents that from happening
if ( o.preventFocusZoom ) {
$.mobile.zoom.disable( true );
}
focusedEl.addClass( $.mobile.focusClass );
})
.blur(function() {
focusedEl.removeClass( $.mobile.focusClass );
if ( o.preventFocusZoom ) {
$.mobile.zoom.enable( true );
}
});
// Autogrow
if ( input.is( "textarea" ) ) {
var extraLineHeight = 15,
keyupTimeoutBuffer = 100,
keyupTimeout;
this._keyup = function() {
var scrollHeight = input[ 0 ].scrollHeight,
clientHeight = input[ 0 ].clientHeight;
if ( clientHeight < scrollHeight ) {
var paddingTop = parseFloat( input.css( "padding-top" ) ),
paddingBottom = parseFloat( input.css( "padding-bottom" ) ),
paddingHeight = paddingTop + paddingBottom;
input.height( scrollHeight - paddingHeight + extraLineHeight );
}
};
input.on( "keyup change input paste", function() {
clearTimeout( keyupTimeout );
keyupTimeout = setTimeout( self._keyup, keyupTimeoutBuffer );
});
// binding to pagechange here ensures that for pages loaded via
// ajax the height is recalculated without user input
this._on( true, $.mobile.document, { "pagechange": "_keyup" });
// Issue 509: the browser is not providing scrollHeight properly until the styles load
if ( $.trim( input.val() ) ) {
// bind to the window load to make sure the height is calculated based on BOTH
// the DOM and CSS
this._on( true, $.mobile.window, {"load": "_keyup"});
}
}
if ( input.attr( "disabled" ) ) {
this.disable();
}
},
disable: function() {
var $el,
isSearch = this.element.is( "[type='search'], :jqmData(type='search')" ),
inputNeedsWrap = this.element.is( "input" ) && !this.element.is( ":jqmData(type='range')" ),
parentNeedsDisabled = this.element.attr( "disabled", true ) && ( inputNeedsWrap || isSearch );
if ( parentNeedsDisabled ) {
$el = this.element.parent();
} else {
$el = this.element;
}
$el.addClass( "ui-disabled" );
return this._setOption( "disabled", true );
},
enable: function() {
var $el,
isSearch = this.element.is( "[type='search'], :jqmData(type='search')" ),
inputNeedsWrap = this.element.is( "input" ) && !this.element.is( ":jqmData(type='range')" ),
parentNeedsEnabled = this.element.attr( "disabled", false ) && ( inputNeedsWrap || isSearch );
if ( parentNeedsEnabled ) {
$el = this.element.parent();
} else {
$el = this.element;
}
$el.removeClass( "ui-disabled" );
return this._setOption( "disabled", false );
}
});
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.textinput.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.mobile.listview.prototype.options.filter = false;
$.mobile.listview.prototype.options.filterPlaceholder = "Filter items...";
$.mobile.listview.prototype.options.filterTheme = "c";
$.mobile.listview.prototype.options.filterReveal = false;
// TODO rename callback/deprecate and default to the item itself as the first argument
var defaultFilterCallback = function( text, searchValue, item ) {
return text.toString().toLowerCase().indexOf( searchValue ) === -1;
};
$.mobile.listview.prototype.options.filterCallback = defaultFilterCallback;
$.mobile.document.delegate( "ul, ol", "listviewcreate", function() {
var list = $( this ),
listview = list.data( "mobile-listview" );
if ( !listview || !listview.options.filter ) {
return;
}
if ( listview.options.filterReveal ) {
list.children().addClass( "ui-screen-hidden" );
}
var wrapper = $( "<form>", {
"class": "ui-listview-filter ui-bar-" + listview.options.filterTheme,
"role": "search"
}).submit( function( e ) {
e.preventDefault();
search.blur();
}),
onKeyUp = function( e ) {
var $this = $( this ),
val = this.value.toLowerCase(),
listItems = null,
li = list.children(),
lastval = $this.jqmData( "lastval" ) + "",
childItems = false,
itemtext = "",
item,
// Check if a custom filter callback applies
isCustomFilterCallback = listview.options.filterCallback !== defaultFilterCallback;
if ( lastval && lastval === val ) {
// Execute the handler only once per value change
return;
}
listview._trigger( "beforefilter", "beforefilter", { input: this } );
// Change val as lastval for next execution
$this.jqmData( "lastval" , val );
if ( isCustomFilterCallback || val.length < lastval.length || val.indexOf( lastval ) !== 0 ) {
// Custom filter callback applies or removed chars or pasted something totally different, check all items
listItems = list.children();
} else {
// Only chars added, not removed, only use visible subset
listItems = list.children( ":not(.ui-screen-hidden)" );
if ( !listItems.length && listview.options.filterReveal ) {
listItems = list.children( ".ui-screen-hidden" );
}
}
if ( val ) {
// This handles hiding regular rows without the text we search for
// and any list dividers without regular rows shown under it
for ( var i = listItems.length - 1; i >= 0; i-- ) {
item = $( listItems[ i ] );
itemtext = item.jqmData( "filtertext" ) || item.text();
if ( item.is( "li:jqmData(role=list-divider)" ) ) {
item.toggleClass( "ui-filter-hidequeue" , !childItems );
// New bucket!
childItems = false;
} else if ( listview.options.filterCallback( itemtext, val, item ) ) {
//mark to be hidden
item.toggleClass( "ui-filter-hidequeue" , true );
} else {
// There's a shown item in the bucket
childItems = true;
}
}
// Show items, not marked to be hidden
listItems
.filter( ":not(.ui-filter-hidequeue)" )
.toggleClass( "ui-screen-hidden", false );
// Hide items, marked to be hidden
listItems
.filter( ".ui-filter-hidequeue" )
.toggleClass( "ui-screen-hidden", true )
.toggleClass( "ui-filter-hidequeue", false );
} else {
//filtervalue is empty => show all
listItems.toggleClass( "ui-screen-hidden", !!listview.options.filterReveal );
}
listview._addFirstLastClasses( li, listview._getVisibles( li, false ), false );
},
search = $( "<input>", {
placeholder: listview.options.filterPlaceholder
})
.attr( "data-" + $.mobile.ns + "type", "search" )
.jqmData( "lastval", "" )
.bind( "keyup change input", onKeyUp )
.appendTo( wrapper )
.textinput();
if ( listview.options.inset ) {
wrapper.addClass( "ui-listview-filter-inset" );
}
wrapper.bind( "submit", function() {
return false;
})
.insertBefore( list );
});
})( jQuery );
(function( $, undefined ) {
$.mobile.listview.prototype.options.autodividers = false;
$.mobile.listview.prototype.options.autodividersSelector = function( elt ) {
// look for the text in the given element
var text = $.trim( elt.text() ) || null;
if ( !text ) {
return null;
}
// create the text for the divider (first uppercased letter)
text = text.slice( 0, 1 ).toUpperCase();
return text;
};
$.mobile.document.delegate( "ul,ol", "listviewcreate", function() {
var list = $( this ),
listview = list.data( "mobile-listview" );
if ( !listview || !listview.options.autodividers ) {
return;
}
var replaceDividers = function () {
list.find( "li:jqmData(role='list-divider')" ).remove();
var lis = list.find( 'li' ),
lastDividerText = null, li, dividerText;
for ( var i = 0; i < lis.length ; i++ ) {
li = lis[i];
dividerText = listview.options.autodividersSelector( $( li ) );
if ( dividerText && lastDividerText !== dividerText ) {
var divider = document.createElement( 'li' );
divider.appendChild( document.createTextNode( dividerText ) );
divider.setAttribute( 'data-' + $.mobile.ns + 'role', 'list-divider' );
li.parentNode.insertBefore( divider, li );
}
lastDividerText = dividerText;
}
};
var afterListviewRefresh = function () {
list.unbind( 'listviewafterrefresh', afterListviewRefresh );
replaceDividers();
listview.refresh();
list.bind( 'listviewafterrefresh', afterListviewRefresh );
};
afterListviewRefresh();
});
})( jQuery );
(function( $, undefined ) {
$( document ).bind( "pagecreate create", function( e ) {
$( ":jqmData(role='nojs')", e.target ).addClass( "ui-nojs" );
});
})( jQuery );
(function( $, undefined ) {
$.mobile.behaviors.formReset = {
_handleFormReset: function() {
this._on( this.element.closest( "form" ), {
reset: function() {
this._delay( "_reset" );
}
});
}
};
})( jQuery );
/*
* "checkboxradio" plugin
*/
(function( $, undefined ) {
$.widget( "mobile.checkboxradio", $.mobile.widget, $.extend( {
options: {
theme: null,
mini: false,
initSelector: "input[type='checkbox'],input[type='radio']"
},
_create: function() {
var self = this,
input = this.element,
o = this.options,
inheritAttr = function( input, dataAttr ) {
return input.jqmData( dataAttr ) || input.closest( "form, fieldset" ).jqmData( dataAttr );
},
// NOTE: Windows Phone could not find the label through a selector
// filter works though.
parentLabel = $( input ).closest( "label" ),
label = parentLabel.length ? parentLabel : $( input ).closest( "form, fieldset, :jqmData(role='page'), :jqmData(role='dialog')" ).find( "label" ).filter( "[for='" + input[0].id + "']" ).first(),
inputtype = input[0].type,
mini = inheritAttr( input, "mini" ) || o.mini,
checkedState = inputtype + "-on",
uncheckedState = inputtype + "-off",
iconpos = inheritAttr( input, "iconpos" ),
checkedClass = "ui-" + checkedState,
uncheckedClass = "ui-" + uncheckedState;
if ( inputtype !== "checkbox" && inputtype !== "radio" ) {
return;
}
// Expose for other methods
$.extend( this, {
label: label,
inputtype: inputtype,
checkedClass: checkedClass,
uncheckedClass: uncheckedClass,
checkedicon: checkedState,
uncheckedicon: uncheckedState
});
// If there's no selected theme check the data attr
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( this.element, "c" );
}
label.buttonMarkup({
theme: o.theme,
icon: uncheckedState,
shadow: false,
mini: mini,
iconpos: iconpos
});
// Wrap the input + label in a div
var wrapper = document.createElement('div');
wrapper.className = 'ui-' + inputtype;
input.add( label ).wrapAll( wrapper );
label.bind({
vmouseover: function( event ) {
if ( $( this ).parent().is( ".ui-disabled" ) ) {
event.stopPropagation();
}
},
vclick: function( event ) {
if ( input.is( ":disabled" ) ) {
event.preventDefault();
return;
}
self._cacheVals();
input.prop( "checked", inputtype === "radio" && true || !input.prop( "checked" ) );
// trigger click handler's bound directly to the input as a substitute for
// how label clicks behave normally in the browsers
// TODO: it would be nice to let the browser's handle the clicks and pass them
// through to the associate input. we can swallow that click at the parent
// wrapper element level
input.triggerHandler( 'click' );
// Input set for common radio buttons will contain all the radio
// buttons, but will not for checkboxes. clearing the checked status
// of other radios ensures the active button state is applied properly
self._getInputSet().not( input ).prop( "checked", false );
self._updateAll();
return false;
}
});
input
.bind({
vmousedown: function() {
self._cacheVals();
},
vclick: function() {
var $this = $( this );
// Adds checked attribute to checked input when keyboard is used
if ( $this.is( ":checked" ) ) {
$this.prop( "checked", true);
self._getInputSet().not( $this ).prop( "checked", false );
} else {
$this.prop( "checked", false );
}
self._updateAll();
},
focus: function() {
label.addClass( $.mobile.focusClass );
},
blur: function() {
label.removeClass( $.mobile.focusClass );
}
});
this._handleFormReset();
this.refresh();
},
_cacheVals: function() {
this._getInputSet().each(function() {
$( this ).jqmData( "cacheVal", this.checked );
});
},
//returns either a set of radios with the same name attribute, or a single checkbox
_getInputSet: function() {
if ( this.inputtype === "checkbox" ) {
return this.element;
}
return this.element.closest( "form, :jqmData(role='page'), :jqmData(role='dialog')" )
.find( "input[name='" + this.element[0].name + "'][type='" + this.inputtype + "']" );
},
_updateAll: function() {
var self = this;
this._getInputSet().each(function() {
var $this = $( this );
if ( this.checked || self.inputtype === "checkbox" ) {
$this.trigger( "change" );
}
})
.checkboxradio( "refresh" );
},
_reset: function() {
this.refresh();
},
refresh: function() {
var input = this.element[ 0 ],
active = " " + $.mobile.activeBtnClass,
checkedClass = this.checkedClass + ( this.element.parents( ".ui-controlgroup-horizontal" ).length ? active : "" ),
label = this.label;
if ( input.checked ) {
label.removeClass( this.uncheckedClass + active ).addClass( checkedClass ).buttonMarkup( { icon: this.checkedicon } );
} else {
label.removeClass( checkedClass ).addClass( this.uncheckedClass ).buttonMarkup( { icon: this.uncheckedicon } );
}
if ( input.disabled ) {
this.disable();
} else {
this.enable();
}
},
disable: function() {
this.element.prop( "disabled", true ).parent().addClass( "ui-disabled" );
},
enable: function() {
this.element.prop( "disabled", false ).parent().removeClass( "ui-disabled" );
}
}, $.mobile.behaviors.formReset ) );
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.checkboxradio.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.button", $.mobile.widget, {
options: {
theme: null,
icon: null,
iconpos: null,
corners: true,
shadow: true,
iconshadow: true,
inline: null,
mini: null,
initSelector: "button, [type='button'], [type='submit'], [type='reset']"
},
_create: function() {
var $el = this.element,
$button,
// create a copy of this.options we can pass to buttonMarkup
o = ( function( tdo ) {
var key, ret = {};
for ( key in tdo ) {
if ( tdo[ key ] !== null && key !== "initSelector" ) {
ret[ key ] = tdo[ key ];
}
}
return ret;
} )( this.options ),
classes = "",
$buttonPlaceholder;
// if this is a link, check if it's been enhanced and, if not, use the right function
if ( $el[ 0 ].tagName === "A" ) {
if ( !$el.hasClass( "ui-btn" ) ) {
$el.buttonMarkup();
}
return;
}
// get the inherited theme
// TODO centralize for all widgets
if ( !this.options.theme ) {
this.options.theme = $.mobile.getInheritedTheme( this.element, "c" );
}
// TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577
/* if ( $el[0].className.length ) {
classes = $el[0].className;
} */
if ( !!~$el[0].className.indexOf( "ui-btn-left" ) ) {
classes = "ui-btn-left";
}
if ( !!~$el[0].className.indexOf( "ui-btn-right" ) ) {
classes = "ui-btn-right";
}
if ( $el.attr( "type" ) === "submit" || $el.attr( "type" ) === "reset" ) {
if ( classes ) {
classes += " ui-submit";
} else {
classes = "ui-submit";
}
}
$( "label[for='" + $el.attr( "id" ) + "']" ).addClass( "ui-submit" );
// Add ARIA role
this.button = $( "<div></div>" )
[ $el.html() ? "html" : "text" ]( $el.html() || $el.val() )
.insertBefore( $el )
.buttonMarkup( o )
.addClass( classes )
.append( $el.addClass( "ui-btn-hidden" ) );
$button = this.button;
$el.bind({
focus: function() {
$button.addClass( $.mobile.focusClass );
},
blur: function() {
$button.removeClass( $.mobile.focusClass );
}
});
this.refresh();
},
_setOption: function( key, value ) {
var op = {};
op[ key ] = value;
if ( key !== "initSelector" ) {
this.button.buttonMarkup( op );
// Record the option change in the options and in the DOM data-* attributes
this.element.attr( "data-" + ( $.mobile.ns || "" ) + ( key.replace( /([A-Z])/, "-$1" ).toLowerCase() ), value );
}
this._super( "_setOption", key, value );
},
enable: function() {
this.element.attr( "disabled", false );
this.button.removeClass( "ui-disabled" ).attr( "aria-disabled", false );
return this._setOption( "disabled", false );
},
disable: function() {
this.element.attr( "disabled", true );
this.button.addClass( "ui-disabled" ).attr( "aria-disabled", true );
return this._setOption( "disabled", true );
},
refresh: function() {
var $el = this.element;
if ( $el.prop("disabled") ) {
this.disable();
} else {
this.enable();
}
// Grab the button's text element from its implementation-independent data item
$( this.button.data( 'buttonElements' ).text )[ $el.html() ? "html" : "text" ]( $el.html() || $el.val() );
}
});
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.button.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.slider", $.mobile.widget, $.extend( {
widgetEventPrefix: "slide",
options: {
theme: null,
trackTheme: null,
disabled: false,
initSelector: "input[type='range'], :jqmData(type='range'), :jqmData(role='slider')",
mini: false,
highlight: false
},
_create: function() {
// TODO: Each of these should have comments explain what they're for
var self = this,
control = this.element,
parentTheme = $.mobile.getInheritedTheme( control, "c" ),
theme = this.options.theme || parentTheme,
trackTheme = this.options.trackTheme || parentTheme,
cType = control[ 0 ].nodeName.toLowerCase(),
isSelect = this.isToggleSwitch = cType === "select",
isRangeslider = control.parent().is( ":jqmData(role='rangeslider')" ),
selectClass = ( this.isToggleSwitch ) ? "ui-slider-switch" : "",
controlID = control.attr( "id" ),
$label = $( "[for='" + controlID + "']" ),
labelID = $label.attr( "id" ) || controlID + "-label",
label = $label.attr( "id", labelID ),
min = !this.isToggleSwitch ? parseFloat( control.attr( "min" ) ) : 0,
max = !this.isToggleSwitch ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length-1,
step = window.parseFloat( control.attr( "step" ) || 1 ),
miniClass = ( this.options.mini || control.jqmData( "mini" ) ) ? " ui-mini" : "",
domHandle = document.createElement( "a" ),
handle = $( domHandle ),
domSlider = document.createElement( "div" ),
slider = $( domSlider ),
valuebg = this.options.highlight && !this.isToggleSwitch ? (function() {
var bg = document.createElement( "div" );
bg.className = "ui-slider-bg " + $.mobile.activeBtnClass + " ui-btn-corner-all";
return $( bg ).prependTo( slider );
})() : false,
options,
wrapper;
domHandle.setAttribute( "href", "#" );
domSlider.setAttribute( "role", "application" );
domSlider.className = [this.isToggleSwitch ? "ui-slider " : "ui-slider-track ",selectClass," ui-btn-down-",trackTheme," ui-btn-corner-all", miniClass].join( "" );
domHandle.className = "ui-slider-handle";
domSlider.appendChild( domHandle );
handle.buttonMarkup({ corners: true, theme: theme, shadow: true })
.attr({
"role": "slider",
"aria-valuemin": min,
"aria-valuemax": max,
"aria-valuenow": this._value(),
"aria-valuetext": this._value(),
"title": this._value(),
"aria-labelledby": labelID
});
$.extend( this, {
slider: slider,
handle: handle,
type: cType,
step: step,
max: max,
min: min,
valuebg: valuebg,
isRangeslider: isRangeslider,
dragging: false,
beforeStart: null,
userModified: false,
mouseMoved: false
});
if ( this.isToggleSwitch ) {
wrapper = document.createElement( "div" );
wrapper.className = "ui-slider-inneroffset";
for ( var j = 0, length = domSlider.childNodes.length; j < length; j++ ) {
wrapper.appendChild( domSlider.childNodes[j] );
}
domSlider.appendChild( wrapper );
// slider.wrapInner( "<div class='ui-slider-inneroffset'></div>" );
// make the handle move with a smooth transition
handle.addClass( "ui-slider-handle-snapping" );
options = control.find( "option" );
for ( var i = 0, optionsCount = options.length; i < optionsCount; i++ ) {
var side = !i ? "b" : "a",
sliderTheme = !i ? " ui-btn-down-" + trackTheme : ( " " + $.mobile.activeBtnClass ),
sliderLabel = document.createElement( "div" ),
sliderImg = document.createElement( "span" );
sliderImg.className = ["ui-slider-label ui-slider-label-", side, sliderTheme, " ui-btn-corner-all"].join( "" );
sliderImg.setAttribute( "role", "img" );
sliderImg.appendChild( document.createTextNode( options[i].innerHTML ) );
$( sliderImg ).prependTo( slider );
}
self._labels = $( ".ui-slider-label", slider );
}
label.addClass( "ui-slider" );
// monitor the input for updated values
control.addClass( this.isToggleSwitch ? "ui-slider-switch" : "ui-slider-input" );
this._on( control, {
"change": "_controlChange",
"keyup": "_controlKeyup",
"blur": "_controlBlur",
"vmouseup": "_controlVMouseUp"
});
slider.bind( "vmousedown", $.proxy( this._sliderVMouseDown, this ) )
.bind( "vclick", false );
// We have to instantiate a new function object for the unbind to work properly
// since the method itself is defined in the prototype (causing it to unbind everything)
this._on( document, { "vmousemove": "_preventDocumentDrag" });
this._on( slider.add( document ), { "vmouseup": "_sliderVMouseUp" });
slider.insertAfter( control );
// wrap in a div for styling purposes
if ( !this.isToggleSwitch && !isRangeslider ) {
wrapper = this.options.mini ? "<div class='ui-slider ui-mini'>" : "<div class='ui-slider'>";
control.add( slider ).wrapAll( wrapper );
}
// Only add focus class to toggle switch, sliders get it automatically from ui-btn
if ( this.isToggleSwitch ) {
this.handle.bind({
focus: function() {
slider.addClass( $.mobile.focusClass );
},
blur: function() {
slider.removeClass( $.mobile.focusClass );
}
});
}
// bind the handle event callbacks and set the context to the widget instance
this._on( this.handle, {
"vmousedown": "_handleVMouseDown",
"keydown": "_handleKeydown",
"keyup": "_handleKeyup"
});
this.handle.bind( "vclick", false );
this._handleFormReset();
this.refresh( undefined, undefined, true );
},
_controlChange: function( event ) {
// if the user dragged the handle, the "change" event was triggered from inside refresh(); don't call refresh() again
if ( this._trigger( "controlchange", event ) === false ) {
return false;
}
if ( !this.mouseMoved ) {
this.refresh( this._value(), true );
}
},
_controlKeyup: function( event ) { // necessary?
this.refresh( this._value(), true, true );
},
_controlBlur: function( event ) {
this.refresh( this._value(), true );
},
// it appears the clicking the up and down buttons in chrome on
// range/number inputs doesn't trigger a change until the field is
// blurred. Here we check thif the value has changed and refresh
_controlVMouseUp: function( event ) {
this._checkedRefresh();
},
// NOTE force focus on handle
_handleVMouseDown: function( event ) {
this.handle.focus();
},
_handleKeydown: function( event ) {
var index = this._value();
if ( this.options.disabled ) {
return;
}
// In all cases prevent the default and mark the handle as active
switch ( event.keyCode ) {
case $.mobile.keyCode.HOME:
case $.mobile.keyCode.END:
case $.mobile.keyCode.PAGE_UP:
case $.mobile.keyCode.PAGE_DOWN:
case $.mobile.keyCode.UP:
case $.mobile.keyCode.RIGHT:
case $.mobile.keyCode.DOWN:
case $.mobile.keyCode.LEFT:
event.preventDefault();
if ( !this._keySliding ) {
this._keySliding = true;
this.handle.addClass( "ui-state-active" );
}
break;
}
// move the slider according to the keypress
switch ( event.keyCode ) {
case $.mobile.keyCode.HOME:
this.refresh( this.min );
break;
case $.mobile.keyCode.END:
this.refresh( this.max );
break;
case $.mobile.keyCode.PAGE_UP:
case $.mobile.keyCode.UP:
case $.mobile.keyCode.RIGHT:
this.refresh( index + this.step );
break;
case $.mobile.keyCode.PAGE_DOWN:
case $.mobile.keyCode.DOWN:
case $.mobile.keyCode.LEFT:
this.refresh( index - this.step );
break;
}
}, // remove active mark
_handleKeyup: function( event ) {
if ( this._keySliding ) {
this._keySliding = false;
this.handle.removeClass( "ui-state-active" );
}
},
_sliderVMouseDown: function( event ) {
// NOTE: we don't do this in refresh because we still want to
// support programmatic alteration of disabled inputs
if ( this.options.disabled || !( event.which === 1 || event.which === 0 || event.which === undefined ) ) {
return false;
}
if ( this._trigger( "beforestart", event ) === false ) {
return false;
}
this.dragging = true;
this.userModified = false;
this.mouseMoved = false;
if ( this.isToggleSwitch ) {
this.beforeStart = this.element[0].selectedIndex;
}
this.refresh( event );
this._trigger( "start" );
return false;
},
_sliderVMouseUp: function() {
if ( this.dragging ) {
this.dragging = false;
if ( this.isToggleSwitch ) {
// make the handle move with a smooth transition
this.handle.addClass( "ui-slider-handle-snapping" );
if ( this.mouseMoved ) {
// this is a drag, change the value only if user dragged enough
if ( this.userModified ) {
this.refresh( this.beforeStart === 0 ? 1 : 0 );
} else {
this.refresh( this.beforeStart );
}
} else {
// this is just a click, change the value
this.refresh( this.beforeStart === 0 ? 1 : 0 );
}
}
this.mouseMoved = false;
this._trigger( "stop" );
return false;
}
},
_preventDocumentDrag: function( event ) {
// NOTE: we don't do this in refresh because we still want to
// support programmatic alteration of disabled inputs
if ( this._trigger( "drag", event ) === false) {
return false;
}
if ( this.dragging && !this.options.disabled ) {
// this.mouseMoved must be updated before refresh() because it will be used in the control "change" event
this.mouseMoved = true;
if ( this.isToggleSwitch ) {
// make the handle move in sync with the mouse
this.handle.removeClass( "ui-slider-handle-snapping" );
}
this.refresh( event );
// only after refresh() you can calculate this.userModified
this.userModified = this.beforeStart !== this.element[0].selectedIndex;
return false;
}
},
_checkedRefresh: function() {
if ( this.value !== this._value() ) {
this.refresh( this._value() );
}
},
_value: function() {
return this.isToggleSwitch ? this.element[0].selectedIndex : parseFloat( this.element.val() ) ;
},
_reset: function() {
this.refresh( undefined, false, true );
},
refresh: function( val, isfromControl, preventInputUpdate ) {
// NOTE: we don't return here because we want to support programmatic
// alteration of the input value, which should still update the slider
var self = this,
parentTheme = $.mobile.getInheritedTheme( this.element, "c" ),
theme = this.options.theme || parentTheme,
trackTheme = this.options.trackTheme || parentTheme,
left, width, data, tol;
self.slider[0].className = [ this.isToggleSwitch ? "ui-slider ui-slider-switch" : "ui-slider-track"," ui-btn-down-" + trackTheme,' ui-btn-corner-all', ( this.options.mini ) ? " ui-mini":""].join( "" );
if ( this.options.disabled || this.element.attr( "disabled" ) ) {
this.disable();
}
// set the stored value for comparison later
this.value = this._value();
if ( this.options.highlight && !this.isToggleSwitch && this.slider.find( ".ui-slider-bg" ).length === 0 ) {
this.valuebg = (function() {
var bg = document.createElement( "div" );
bg.className = "ui-slider-bg " + $.mobile.activeBtnClass + " ui-btn-corner-all";
return $( bg ).prependTo( self.slider );
})();
}
this.handle.buttonMarkup({ corners: true, theme: theme, shadow: true });
var pxStep, percent,
control = this.element,
isInput = !this.isToggleSwitch,
optionElements = isInput ? [] : control.find( "option" ),
min = isInput ? parseFloat( control.attr( "min" ) ) : 0,
max = isInput ? parseFloat( control.attr( "max" ) ) : optionElements.length - 1,
step = ( isInput && parseFloat( control.attr( "step" ) ) > 0 ) ? parseFloat( control.attr( "step" ) ) : 1;
if ( typeof val === "object" ) {
data = val;
// a slight tolerance helped get to the ends of the slider
tol = 8;
left = this.slider.offset().left;
width = this.slider.width();
pxStep = width/((max-min)/step);
if ( !this.dragging ||
data.pageX < left - tol ||
data.pageX > left + width + tol ) {
return;
}
if ( pxStep > 1 ) {
percent = ( ( data.pageX - left ) / width ) * 100;
} else {
percent = Math.round( ( ( data.pageX - left ) / width ) * 100 );
}
} else {
if ( val == null ) {
val = isInput ? parseFloat( control.val() || 0 ) : control[0].selectedIndex;
}
percent = ( parseFloat( val ) - min ) / ( max - min ) * 100;
}
if ( isNaN( percent ) ) {
return;
}
var newval = ( percent / 100 ) * ( max - min ) + min;
//from jQuery UI slider, the following source will round to the nearest step
var valModStep = ( newval - min ) % step;
var alignValue = newval - valModStep;
if ( Math.abs( valModStep ) * 2 >= step ) {
alignValue += ( valModStep > 0 ) ? step : ( -step );
}
var percentPerStep = 100/((max-min)/step);
// Since JavaScript has problems with large floats, round
// the final value to 5 digits after the decimal point (see jQueryUI: #4124)
newval = parseFloat( alignValue.toFixed(5) );
if ( typeof pxStep === "undefined" ) {
pxStep = width / ( (max-min) / step );
}
if ( pxStep > 1 && isInput ) {
percent = ( newval - min ) * percentPerStep * ( 1 / step );
}
if ( percent < 0 ) {
percent = 0;
}
if ( percent > 100 ) {
percent = 100;
}
if ( newval < min ) {
newval = min;
}
if ( newval > max ) {
newval = max;
}
this.handle.css( "left", percent + "%" );
this.handle[0].setAttribute( "aria-valuenow", isInput ? newval : optionElements.eq( newval ).attr( "value" ) );
this.handle[0].setAttribute( "aria-valuetext", isInput ? newval : optionElements.eq( newval ).getEncodedText() );
this.handle[0].setAttribute( "title", isInput ? newval : optionElements.eq( newval ).getEncodedText() );
if ( this.valuebg ) {
this.valuebg.css( "width", percent + "%" );
}
// drag the label widths
if ( this._labels ) {
var handlePercent = this.handle.width() / this.slider.width() * 100,
aPercent = percent && handlePercent + ( 100 - handlePercent ) * percent / 100,
bPercent = percent === 100 ? 0 : Math.min( handlePercent + 100 - aPercent, 100 );
this._labels.each(function() {
var ab = $( this ).is( ".ui-slider-label-a" );
$( this ).width( ( ab ? aPercent : bPercent ) + "%" );
});
}
if ( !preventInputUpdate ) {
var valueChanged = false;
// update control"s value
if ( isInput ) {
valueChanged = control.val() !== newval;
control.val( newval );
} else {
valueChanged = control[ 0 ].selectedIndex !== newval;
control[ 0 ].selectedIndex = newval;
}
if ( this._trigger( "beforechange", val ) === false) {
return false;
}
if ( !isfromControl && valueChanged ) {
control.trigger( "change" );
}
}
},
enable: function() {
this.element.attr( "disabled", false );
this.slider.removeClass( "ui-disabled" ).attr( "aria-disabled", false );
return this._setOption( "disabled", false );
},
disable: function() {
this.element.attr( "disabled", true );
this.slider.addClass( "ui-disabled" ).attr( "aria-disabled", true );
return this._setOption( "disabled", true );
}
}, $.mobile.behaviors.formReset ) );
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.slider.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.rangeslider", $.mobile.widget, {
options: {
theme: null,
trackTheme: null,
disabled: false,
initSelector: ":jqmData(role='rangeslider')",
mini: false,
highlight: true
},
_create: function() {
var secondLabel,
$el = this.element,
elClass = this.options.mini ? "ui-rangeslider ui-mini" : "ui-rangeslider",
_inputFirst = $el.find( "input" ).first(),
_inputLast = $el.find( "input" ).last(),
label = $el.find( "label" ).first(),
_sliderFirst = $.data( _inputFirst.get(0), "mobileSlider" ).slider,
_sliderLast = $.data( _inputLast.get(0), "mobileSlider" ).slider,
firstHandle = $.data( _inputFirst.get(0), "mobileSlider" ).handle,
_sliders = $( "<div class=\"ui-rangeslider-sliders\" />" ).appendTo( $el );
if ( $el.find( "label" ).length > 1 ) {
secondLabel = $el.find( "label" ).last().hide();
}
_inputFirst.addClass( "ui-rangeslider-first" );
_inputLast.addClass( "ui-rangeslider-last" );
$el.addClass( elClass );
_sliderFirst.appendTo( _sliders );
_sliderLast.appendTo( _sliders );
label.prependTo( $el );
firstHandle.prependTo( _sliderLast );
$.extend( this, {
_inputFirst: _inputFirst,
_inputLast: _inputLast,
_sliderFirst: _sliderFirst,
_sliderLast: _sliderLast,
_targetVal: null,
_sliderTarget: false,
_sliders: _sliders,
_proxy: false
});
this.refresh();
this._on( this.element.find( "input.ui-slider-input" ), {
"slidebeforestart": "_slidebeforestart",
"slidestop": "_slidestop",
"slidedrag": "_slidedrag",
"slidebeforechange": "_change",
"blur": "_change",
"keyup": "_change"
});
this._on({
"mousedown":"_change"
});
this._on( this.element.closest( "form" ), {
"reset":"_handleReset"
});
this._on( firstHandle, {
"vmousedown": "_dragFirstHandle"
});
},
_handleReset: function(){
var self = this;
//we must wait for the stack to unwind before updateing other wise sliders will not have updated yet
setTimeout( function(){
self._updateHighlight();
},0);
},
_dragFirstHandle: function( event ) {
//if the first handle is dragged send the event to the first slider
$.data( this._inputFirst.get(0), "mobileSlider" ).dragging = true;
$.data( this._inputFirst.get(0), "mobileSlider" ).refresh( event );
return false;
},
_slidedrag: function( event ) {
var first = $( event.target ).is( this._inputFirst ),
otherSlider = ( first ) ? this._inputLast : this._inputFirst;
this._sliderTarget = false;
//if the drag was initiated on an extreme and the other handle is focused send the events to
//the closest handle
if ( ( this._proxy === "first" && first ) || ( this._proxy === "last" && !first ) ) {
$.data( otherSlider.get(0), "mobileSlider" ).dragging = true;
$.data( otherSlider.get(0), "mobileSlider" ).refresh( event );
return false;
}
},
_slidestop: function( event ) {
var first = $( event.target ).is( this._inputFirst );
this._proxy = false;
//this stops dragging of the handle and brings the active track to the front
//this makes clicks on the track go the the last handle used
this.element.find( "input" ).trigger( "vmouseup" );
this._sliderFirst.css( "z-index", first ? 1 : "" );
},
_slidebeforestart: function( event ) {
this._sliderTarget = false;
//if the track is the target remember this and the original value
if ( $( event.originalEvent.target ).hasClass( "ui-slider-track" ) ) {
this._sliderTarget = true;
this._targetVal = $( event.target ).val();
}
},
_setOption: function( options ) {
this._superApply( options );
this.refresh();
},
refresh: function() {
var $el = this.element,
o = this.options;
$el.find( "input" ).slider({
theme: o.theme,
trackTheme: o.trackTheme,
disabled: o.disabled,
mini: o.mini,
highlight: o.highlight
}).slider( "refresh" );
this._updateHighlight();
},
_change: function( event ) {
if ( event.type === "keyup" ) {
this._updateHighlight();
return false;
}
var self = this,
min = parseFloat( this._inputFirst.val(), 10 ),
max = parseFloat( this._inputLast.val(), 10 ),
first = $( event.target ).hasClass( "ui-rangeslider-first" ),
thisSlider = first ? this._inputFirst : this._inputLast,
otherSlider = first ? this._inputLast : this._inputFirst;
if( ( this._inputFirst.val() > this._inputLast.val() && event.type === "mousedown" && !$(event.target).hasClass("ui-slider-handle")) ){
thisSlider.blur();
} else if( event.type === "mousedown" ){
return;
}
if ( min > max && !this._sliderTarget ) {
//this prevents min from being greater then max
thisSlider.val( first ? max: min ).slider( "refresh" );
this._trigger( "normalize" );
} else if ( min > max ) {
//this makes it so clicks on the target on either extreme go to the closest handle
thisSlider.val( this._targetVal ).slider( "refresh" );
//You must wait for the stack to unwind so first slider is updated before updating second
setTimeout( function() {
otherSlider.val( first ? min: max ).slider( "refresh" );
$.data( otherSlider.get(0), "mobileSlider" ).handle.focus();
self._sliderFirst.css( "z-index", first ? "" : 1 );
self._trigger( "normalize" );
}, 0 );
this._proxy = ( first ) ? "first" : "last";
}
//fixes issue where when both _sliders are at min they cannot be adjusted
if ( min === max ) {
$.data( thisSlider.get(0), "mobileSlider" ).handle.css( "z-index", 1 );
$.data( otherSlider.get(0), "mobileSlider" ).handle.css( "z-index", 0 );
} else {
$.data( otherSlider.get(0), "mobileSlider" ).handle.css( "z-index", "" );
$.data( thisSlider.get(0), "mobileSlider" ).handle.css( "z-index", "" );
}
this._updateHighlight();
if ( min >= max ) {
return false;
}
},
_updateHighlight: function() {
var min = parseInt( $.data( this._inputFirst.get(0), "mobileSlider" ).handle.get(0).style.left, 10 ),
max = parseInt( $.data( this._inputLast.get(0), "mobileSlider" ).handle.get(0).style.left, 10 ),
width = (max - min);
this.element.find( ".ui-slider-bg" ).css({
"margin-left": min + "%",
"width": width + "%"
});
},
_destroy: function() {
this.element.removeClass( "ui-rangeslider ui-mini" ).find( "label" ).show();
this._inputFirst.after( this._sliderFirst );
this._inputLast.after( this._sliderLast );
this._sliders.remove();
this.element.find( "input" ).removeClass( "ui-rangeslider-first ui-rangeslider-last" ).slider( "destroy" );
}
});
$.widget( "mobile.rangeslider", $.mobile.rangeslider, $.mobile.behaviors.formReset );
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ) {
$.mobile.rangeslider.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.selectmenu", $.mobile.widget, $.extend( {
options: {
theme: null,
disabled: false,
icon: "arrow-d",
iconpos: "right",
inline: false,
corners: true,
shadow: true,
iconshadow: true,
overlayTheme: "a",
dividerTheme: "b",
hidePlaceholderMenuItems: true,
closeText: "Close",
nativeMenu: true,
// This option defaults to true on iOS devices.
preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1,
initSelector: "select:not( :jqmData(role='slider') )",
mini: false
},
_button: function() {
return $( "<div/>" );
},
_setDisabled: function( value ) {
this.element.attr( "disabled", value );
this.button.attr( "aria-disabled", value );
return this._setOption( "disabled", value );
},
_focusButton : function() {
var self = this;
setTimeout( function() {
self.button.focus();
}, 40);
},
_selectOptions: function() {
return this.select.find( "option" );
},
// setup items that are generally necessary for select menu extension
_preExtension: function() {
var classes = "";
// TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577
/* if ( $el[0].className.length ) {
classes = $el[0].className;
} */
if ( !!~this.element[0].className.indexOf( "ui-btn-left" ) ) {
classes = " ui-btn-left";
}
if ( !!~this.element[0].className.indexOf( "ui-btn-right" ) ) {
classes = " ui-btn-right";
}
this.select = this.element.removeClass( "ui-btn-left ui-btn-right" ).wrap( "<div class='ui-select" + classes + "'>" );
this.selectID = this.select.attr( "id" );
this.label = $( "label[for='"+ this.selectID +"']" ).addClass( "ui-select" );
this.isMultiple = this.select[ 0 ].multiple;
if ( !this.options.theme ) {
this.options.theme = $.mobile.getInheritedTheme( this.select, "c" );
}
},
_destroy: function() {
var wrapper = this.element.parents( ".ui-select" );
if ( wrapper.length > 0 ) {
if ( wrapper.is( ".ui-btn-left, .ui-btn-right" ) ) {
this.element.addClass( wrapper.is( ".ui-btn-left" ) ? "ui-btn-left" : "ui-btn-right" );
}
this.element.insertAfter( wrapper );
wrapper.remove();
}
},
_create: function() {
this._preExtension();
// Allows for extension of the native select for custom selects and other plugins
// see select.custom for example extension
// TODO explore plugin registration
this._trigger( "beforeCreate" );
this.button = this._button();
var self = this,
options = this.options,
inline = options.inline || this.select.jqmData( "inline" ),
mini = options.mini || this.select.jqmData( "mini" ),
iconpos = options.icon ? ( options.iconpos || this.select.jqmData( "iconpos" ) ) : false,
// IE throws an exception at options.item() function when
// there is no selected item
// select first in this case
selectedIndex = this.select[ 0 ].selectedIndex === -1 ? 0 : this.select[ 0 ].selectedIndex,
// TODO values buttonId and menuId are undefined here
button = this.button
.insertBefore( this.select )
.buttonMarkup( {
theme: options.theme,
icon: options.icon,
iconpos: iconpos,
inline: inline,
corners: options.corners,
shadow: options.shadow,
iconshadow: options.iconshadow,
mini: mini
});
this.setButtonText();
// Opera does not properly support opacity on select elements
// In Mini, it hides the element, but not its text
// On the desktop,it seems to do the opposite
// for these reasons, using the nativeMenu option results in a full native select in Opera
if ( options.nativeMenu && window.opera && window.opera.version ) {
button.addClass( "ui-select-nativeonly" );
}
// Add counter for multi selects
if ( this.isMultiple ) {
this.buttonCount = $( "<span>" )
.addClass( "ui-li-count ui-btn-up-c ui-btn-corner-all" )
.hide()
.appendTo( button.addClass('ui-li-has-count') );
}
// Disable if specified
if ( options.disabled || this.element.attr('disabled')) {
this.disable();
}
// Events on native select
this.select.change(function() {
self.refresh();
if ( !!options.nativeMenu ) {
this.blur();
}
});
this._handleFormReset();
this.build();
},
build: function() {
var self = this;
this.select
.appendTo( self.button )
.bind( "vmousedown", function() {
// Add active class to button
self.button.addClass( $.mobile.activeBtnClass );
})
.bind( "focus", function() {
self.button.addClass( $.mobile.focusClass );
})
.bind( "blur", function() {
self.button.removeClass( $.mobile.focusClass );
})
.bind( "focus vmouseover", function() {
self.button.trigger( "vmouseover" );
})
.bind( "vmousemove", function() {
// Remove active class on scroll/touchmove
self.button.removeClass( $.mobile.activeBtnClass );
})
.bind( "change blur vmouseout", function() {
self.button.trigger( "vmouseout" )
.removeClass( $.mobile.activeBtnClass );
})
.bind( "change blur", function() {
self.button.removeClass( "ui-btn-down-" + self.options.theme );
});
// In many situations, iOS will zoom into the select upon tap, this prevents that from happening
self.button.bind( "vmousedown", function() {
if ( self.options.preventFocusZoom ) {
$.mobile.zoom.disable( true );
}
});
self.label.bind( "click focus", function() {
if ( self.options.preventFocusZoom ) {
$.mobile.zoom.disable( true );
}
});
self.select.bind( "focus", function() {
if ( self.options.preventFocusZoom ) {
$.mobile.zoom.disable( true );
}
});
self.button.bind( "mouseup", function() {
if ( self.options.preventFocusZoom ) {
setTimeout(function() {
$.mobile.zoom.enable( true );
}, 0 );
}
});
self.select.bind( "blur", function() {
if ( self.options.preventFocusZoom ) {
$.mobile.zoom.enable( true );
}
});
},
selected: function() {
return this._selectOptions().filter( ":selected" );
},
selectedIndices: function() {
var self = this;
return this.selected().map(function() {
return self._selectOptions().index( this );
}).get();
},
setButtonText: function() {
var self = this,
selected = this.selected(),
text = this.placeholder,
span = $( document.createElement( "span" ) );
this.button.find( ".ui-btn-text" ).html(function() {
if ( selected.length ) {
text = selected.map(function() {
return $( this ).text();
}).get().join( ", " );
} else {
text = self.placeholder;
}
// TODO possibly aggregate multiple select option classes
return span.text( text )
.addClass( self.select.attr( "class" ) )
.addClass( selected.attr( "class" ) );
});
},
setButtonCount: function() {
var selected = this.selected();
// multiple count inside button
if ( this.isMultiple ) {
this.buttonCount[ selected.length > 1 ? "show" : "hide" ]().text( selected.length );
}
},
_reset: function() {
this.refresh();
},
refresh: function() {
this.setButtonText();
this.setButtonCount();
},
// open and close preserved in native selects
// to simplify users code when looping over selects
open: $.noop,
close: $.noop,
disable: function() {
this._setDisabled( true );
this.button.addClass( "ui-disabled" );
},
enable: function() {
this._setDisabled( false );
this.button.removeClass( "ui-disabled" );
}
}, $.mobile.behaviors.formReset ) );
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.selectmenu.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
function fitSegmentInsideSegment( winSize, segSize, offset, desired ) {
var ret = desired;
if ( winSize < segSize ) {
// Center segment if it's bigger than the window
ret = offset + ( winSize - segSize ) / 2;
} else {
// Otherwise center it at the desired coordinate while keeping it completely inside the window
ret = Math.min( Math.max( offset, desired - segSize / 2 ), offset + winSize - segSize );
}
return ret;
}
function windowCoords() {
var $win = $.mobile.window;
return {
x: $win.scrollLeft(),
y: $win.scrollTop(),
cx: ( window.innerWidth || $win.width() ),
cy: ( window.innerHeight || $win.height() )
};
}
$.widget( "mobile.popup", $.mobile.widget, {
options: {
theme: null,
overlayTheme: null,
shadow: true,
corners: true,
transition: "none",
positionTo: "origin",
tolerance: null,
initSelector: ":jqmData(role='popup')",
closeLinkSelector: "a:jqmData(rel='back')",
closeLinkEvents: "click.popup",
navigateEvents: "navigate.popup",
closeEvents: "navigate.popup pagebeforechange.popup",
dismissible: true,
// NOTE Windows Phone 7 has a scroll position caching issue that
// requires us to disable popup history management by default
// https://github.com/jquery/jquery-mobile/issues/4784
//
// NOTE this option is modified in _create!
history: !$.mobile.browser.oldIE
},
_eatEventAndClose: function( e ) {
e.preventDefault();
e.stopImmediatePropagation();
if ( this.options.dismissible ) {
this.close();
}
return false;
},
// Make sure the screen size is increased beyond the page height if the popup's causes the document to increase in height
_resizeScreen: function() {
var popupHeight = this._ui.container.outerHeight( true );
this._ui.screen.removeAttr( "style" );
if ( popupHeight > this._ui.screen.height() ) {
this._ui.screen.height( popupHeight );
}
},
_handleWindowKeyUp: function( e ) {
if ( this._isOpen && e.keyCode === $.mobile.keyCode.ESCAPE ) {
return this._eatEventAndClose( e );
}
},
_expectResizeEvent: function() {
var winCoords = windowCoords();
if ( this._resizeData ) {
if ( winCoords.x === this._resizeData.winCoords.x &&
winCoords.y === this._resizeData.winCoords.y &&
winCoords.cx === this._resizeData.winCoords.cx &&
winCoords.cy === this._resizeData.winCoords.cy ) {
// timeout not refreshed
return false;
} else {
// clear existing timeout - it will be refreshed below
clearTimeout( this._resizeData.timeoutId );
}
}
this._resizeData = {
timeoutId: setTimeout( $.proxy( this, "_resizeTimeout" ), 200 ),
winCoords: winCoords
};
return true;
},
_resizeTimeout: function() {
if ( this._isOpen ) {
if ( !this._expectResizeEvent() ) {
if ( this._ui.container.hasClass( "ui-popup-hidden" ) ) {
// effectively rapid-open the popup while leaving the screen intact
this._ui.container.removeClass( "ui-popup-hidden" );
this.reposition( { positionTo: "window" } );
this._ignoreResizeEvents();
}
this._resizeScreen();
this._resizeData = null;
this._orientationchangeInProgress = false;
}
} else {
this._resizeData = null;
this._orientationchangeInProgress = false;
}
},
_ignoreResizeEvents: function() {
var self = this;
if ( this._ignoreResizeTo ) {
clearTimeout( this._ignoreResizeTo );
}
this._ignoreResizeTo = setTimeout( function() { self._ignoreResizeTo = 0; }, 1000 );
},
_handleWindowResize: function( e ) {
if ( this._isOpen && this._ignoreResizeTo === 0 ) {
if ( ( this._expectResizeEvent() || this._orientationchangeInProgress ) &&
!this._ui.container.hasClass( "ui-popup-hidden" ) ) {
// effectively rapid-close the popup while leaving the screen intact
this._ui.container
.addClass( "ui-popup-hidden" )
.removeAttr( "style" );
}
}
},
_handleWindowOrientationchange: function( e ) {
if ( !this._orientationchangeInProgress && this._isOpen && this._ignoreResizeTo === 0 ) {
this._expectResizeEvent();
this._orientationchangeInProgress = true;
}
},
// When the popup is open, attempting to focus on an element that is not a
// child of the popup will redirect focus to the popup
_handleDocumentFocusIn: function( e ) {
var tgt = e.target, $tgt, ui = this._ui;
if ( !this._isOpen ) {
return;
}
if ( tgt !== ui.container[ 0 ] ) {
$tgt = $( e.target );
if ( 0 === $tgt.parents().filter( ui.container[ 0 ] ).length ) {
$( document.activeElement ).one( "focus", function( e ) {
$tgt.blur();
});
ui.focusElement.focus();
e.preventDefault();
e.stopImmediatePropagation();
return false;
} else if ( ui.focusElement[ 0 ] === ui.container[ 0 ] ) {
ui.focusElement = $tgt;
}
}
this._ignoreResizeEvents();
},
_create: function() {
var ui = {
screen: $( "<div class='ui-screen-hidden ui-popup-screen'></div>" ),
placeholder: $( "<div style='display: none;'><!-- placeholder --></div>" ),
container: $( "<div class='ui-popup-container ui-popup-hidden'></div>" )
},
thisPage = this.element.closest( ".ui-page" ),
myId = this.element.attr( "id" ),
o = this.options,
key, value;
// We need to adjust the history option to be false if there's no AJAX nav.
// We can't do it in the option declarations because those are run before
// it is determined whether there shall be AJAX nav.
o.history = o.history && $.mobile.ajaxEnabled && $.mobile.hashListeningEnabled;
if ( thisPage.length === 0 ) {
thisPage = $( "body" );
}
// define the container for navigation event bindings
// TODO this would be nice at the the mobile widget level
o.container = o.container || $.mobile.pageContainer || thisPage;
// Apply the proto
thisPage.append( ui.screen );
ui.container.insertAfter( ui.screen );
// Leave a placeholder where the element used to be
ui.placeholder.insertAfter( this.element );
if ( myId ) {
ui.screen.attr( "id", myId + "-screen" );
ui.container.attr( "id", myId + "-popup" );
ui.placeholder.html( "<!-- placeholder for " + myId + " -->" );
}
ui.container.append( this.element );
ui.focusElement = ui.container;
// Add class to popup element
this.element.addClass( "ui-popup" );
// Define instance variables
$.extend( this, {
_scrollTop: 0,
_page: thisPage,
_ui: ui,
_fallbackTransition: "",
_currentTransition: false,
_prereqs: null,
_isOpen: false,
_tolerance: null,
_resizeData: null,
_ignoreResizeTo: 0,
_orientationchangeInProgress: false
});
// This duplicates the code from the various option setters below for
// better performance. It must be kept in sync with those setters.
this._applyTheme( this.element, o.theme, "body" );
this._applyTheme( this._ui.screen, o.overlayTheme, "overlay" );
this._applyTransition( o.transition );
this.element
.toggleClass( "ui-overlay-shadow", o.shadow )
.toggleClass( "ui-corner-all", o.corners );
this._setTolerance( o.tolerance );
ui.screen.bind( "vclick", $.proxy( this, "_eatEventAndClose" ) );
this._on( $.mobile.window, {
orientationchange: $.proxy( this, "_handleWindowOrientationchange" ),
resize: $.proxy( this, "_handleWindowResize" ),
keyup: $.proxy( this, "_handleWindowKeyUp" )
});
this._on( $.mobile.document, {
focusin: $.proxy( this, "_handleDocumentFocusIn" )
});
},
_applyTheme: function( dst, theme, prefix ) {
var classes = ( dst.attr( "class" ) || "").split( " " ),
alreadyAdded = true,
currentTheme = null,
matches,
themeStr = String( theme );
while ( classes.length > 0 ) {
currentTheme = classes.pop();
matches = ( new RegExp( "^ui-" + prefix + "-([a-z])$" ) ).exec( currentTheme );
if ( matches && matches.length > 1 ) {
currentTheme = matches[ 1 ];
break;
} else {
currentTheme = null;
}
}
if ( theme !== currentTheme ) {
dst.removeClass( "ui-" + prefix + "-" + currentTheme );
if ( ! ( theme === null || theme === "none" ) ) {
dst.addClass( "ui-" + prefix + "-" + themeStr );
}
}
},
_setTheme: function( value ) {
this._applyTheme( this.element, value, "body" );
},
_setOverlayTheme: function( value ) {
this._applyTheme( this._ui.screen, value, "overlay" );
if ( this._isOpen ) {
this._ui.screen.addClass( "in" );
}
},
_setShadow: function( value ) {
this.element.toggleClass( "ui-overlay-shadow", value );
},
_setCorners: function( value ) {
this.element.toggleClass( "ui-corner-all", value );
},
_applyTransition: function( value ) {
this._ui.container.removeClass( this._fallbackTransition );
if ( value && value !== "none" ) {
this._fallbackTransition = $.mobile._maybeDegradeTransition( value );
if ( this._fallbackTransition === "none" ) {
this._fallbackTransition = "";
}
this._ui.container.addClass( this._fallbackTransition );
}
},
_setTransition: function( value ) {
if ( !this._currentTransition ) {
this._applyTransition( value );
}
},
_setTolerance: function( value ) {
var tol = { t: 30, r: 15, b: 30, l: 15 };
if ( value !== undefined ) {
var ar = String( value ).split( "," );
$.each( ar, function( idx, val ) { ar[ idx ] = parseInt( val, 10 ); } );
switch( ar.length ) {
// All values are to be the same
case 1:
if ( !isNaN( ar[ 0 ] ) ) {
tol.t = tol.r = tol.b = tol.l = ar[ 0 ];
}
break;
// The first value denotes top/bottom tolerance, and the second value denotes left/right tolerance
case 2:
if ( !isNaN( ar[ 0 ] ) ) {
tol.t = tol.b = ar[ 0 ];
}
if ( !isNaN( ar[ 1 ] ) ) {
tol.l = tol.r = ar[ 1 ];
}
break;
// The array contains values in the order top, right, bottom, left
case 4:
if ( !isNaN( ar[ 0 ] ) ) {
tol.t = ar[ 0 ];
}
if ( !isNaN( ar[ 1 ] ) ) {
tol.r = ar[ 1 ];
}
if ( !isNaN( ar[ 2 ] ) ) {
tol.b = ar[ 2 ];
}
if ( !isNaN( ar[ 3 ] ) ) {
tol.l = ar[ 3 ];
}
break;
default:
break;
}
}
this._tolerance = tol;
},
_setOption: function( key, value ) {
var setter = "_set" + key.charAt( 0 ).toUpperCase() + key.slice( 1 );
if ( this[ setter ] !== undefined ) {
this[ setter ]( value );
}
this._super( key, value );
},
// Try and center the overlay over the given coordinates
_placementCoords: function( desired ) {
// rectangle within which the popup must fit
var
winCoords = windowCoords(),
rc = {
x: this._tolerance.l,
y: winCoords.y + this._tolerance.t,
cx: winCoords.cx - this._tolerance.l - this._tolerance.r,
cy: winCoords.cy - this._tolerance.t - this._tolerance.b
},
menuSize, ret;
// Clamp the width of the menu before grabbing its size
this._ui.container.css( "max-width", rc.cx );
menuSize = {
cx: this._ui.container.outerWidth( true ),
cy: this._ui.container.outerHeight( true )
};
// Center the menu over the desired coordinates, while not going outside
// the window tolerances. This will center wrt. the window if the popup is too large.
ret = {
x: fitSegmentInsideSegment( rc.cx, menuSize.cx, rc.x, desired.x ),
y: fitSegmentInsideSegment( rc.cy, menuSize.cy, rc.y, desired.y )
};
// Make sure the top of the menu is visible
ret.y = Math.max( 0, ret.y );
// If the height of the menu is smaller than the height of the document
// align the bottom with the bottom of the document
// fix for $.mobile.document.height() bug in core 1.7.2.
var docEl = document.documentElement, docBody = document.body,
docHeight = Math.max( docEl.clientHeight, docBody.scrollHeight, docBody.offsetHeight, docEl.scrollHeight, docEl.offsetHeight );
ret.y -= Math.min( ret.y, Math.max( 0, ret.y + menuSize.cy - docHeight ) );
return { left: ret.x, top: ret.y };
},
_createPrereqs: function( screenPrereq, containerPrereq, whenDone ) {
var self = this, prereqs;
// It is important to maintain both the local variable prereqs and self._prereqs. The local variable remains in
// the closure of the functions which call the callbacks passed in. The comparison between the local variable and
// self._prereqs is necessary, because once a function has been passed to .animationComplete() it will be called
// next time an animation completes, even if that's not the animation whose end the function was supposed to catch
// (for example, if an abort happens during the opening animation, the .animationComplete handler is not called for
// that animation anymore, but the handler remains attached, so it is called the next time the popup is opened
// - making it stale. Comparing the local variable prereqs to the widget-level variable self._prereqs ensures that
// callbacks triggered by a stale .animationComplete will be ignored.
prereqs = {
screen: $.Deferred(),
container: $.Deferred()
};
prereqs.screen.then( function() {
if ( prereqs === self._prereqs ) {
screenPrereq();
}
});
prereqs.container.then( function() {
if ( prereqs === self._prereqs ) {
containerPrereq();
}
});
$.when( prereqs.screen, prereqs.container ).done( function() {
if ( prereqs === self._prereqs ) {
self._prereqs = null;
whenDone();
}
});
self._prereqs = prereqs;
},
_animate: function( args ) {
// NOTE before removing the default animation of the screen
// this had an animate callback that would resolve the deferred
// now the deferred is resolved immediately
// TODO remove the dependency on the screen deferred
this._ui.screen
.removeClass( args.classToRemove )
.addClass( args.screenClassToAdd );
args.prereqs.screen.resolve();
if ( args.transition && args.transition !== "none" ) {
if ( args.applyTransition ) {
this._applyTransition( args.transition );
}
if ( this._fallbackTransition ) {
this._ui.container
.animationComplete( $.proxy( args.prereqs.container, "resolve" ) )
.addClass( args.containerClassToAdd )
.removeClass( args.classToRemove );
return;
}
}
this._ui.container.removeClass( args.classToRemove );
args.prereqs.container.resolve();
},
// The desired coordinates passed in will be returned untouched if no reference element can be identified via
// desiredPosition.positionTo. Nevertheless, this function ensures that its return value always contains valid
// x and y coordinates by specifying the center middle of the window if the coordinates are absent.
// options: { x: coordinate, y: coordinate, positionTo: string: "origin", "window", or jQuery selector
_desiredCoords: function( o ) {
var dst = null, offset, winCoords = windowCoords(), x = o.x, y = o.y, pTo = o.positionTo;
// Establish which element will serve as the reference
if ( pTo && pTo !== "origin" ) {
if ( pTo === "window" ) {
x = winCoords.cx / 2 + winCoords.x;
y = winCoords.cy / 2 + winCoords.y;
} else {
try {
dst = $( pTo );
} catch( e ) {
dst = null;
}
if ( dst ) {
dst.filter( ":visible" );
if ( dst.length === 0 ) {
dst = null;
}
}
}
}
// If an element was found, center over it
if ( dst ) {
offset = dst.offset();
x = offset.left + dst.outerWidth() / 2;
y = offset.top + dst.outerHeight() / 2;
}
// Make sure x and y are valid numbers - center over the window
if ( $.type( x ) !== "number" || isNaN( x ) ) {
x = winCoords.cx / 2 + winCoords.x;
}
if ( $.type( y ) !== "number" || isNaN( y ) ) {
y = winCoords.cy / 2 + winCoords.y;
}
return { x: x, y: y };
},
_reposition: function( o ) {
// We only care about position-related parameters for repositioning
o = { x: o.x, y: o.y, positionTo: o.positionTo };
this._trigger( "beforeposition", undefined, o );
this._ui.container.offset( this._placementCoords( this._desiredCoords( o ) ) );
},
reposition: function( o ) {
if ( this._isOpen ) {
this._reposition( o );
}
},
_openPrereqsComplete: function() {
this._ui.container.addClass( "ui-popup-active" );
this._isOpen = true;
this._resizeScreen();
this._ui.container.attr( "tabindex", "0" ).focus();
this._ignoreResizeEvents();
this._trigger( "afteropen" );
},
_open: function( options ) {
var o = $.extend( {}, this.options, options ),
// TODO move blacklist to private method
androidBlacklist = ( function() {
var w = window,
ua = navigator.userAgent,
// Rendering engine is Webkit, and capture major version
wkmatch = ua.match( /AppleWebKit\/([0-9\.]+)/ ),
wkversion = !!wkmatch && wkmatch[ 1 ],
androidmatch = ua.match( /Android (\d+(?:\.\d+))/ ),
andversion = !!androidmatch && androidmatch[ 1 ],
chromematch = ua.indexOf( "Chrome" ) > -1;
// Platform is Android, WebKit version is greater than 534.13 ( Android 3.2.1 ) and not Chrome.
if( androidmatch !== null && andversion === "4.0" && wkversion && wkversion > 534.13 && !chromematch ) {
return true;
}
return false;
}());
// Count down to triggering "popupafteropen" - we have two prerequisites:
// 1. The popup window animation completes (container())
// 2. The screen opacity animation completes (screen())
this._createPrereqs(
$.noop,
$.noop,
$.proxy( this, "_openPrereqsComplete" ) );
this._currentTransition = o.transition;
this._applyTransition( o.transition );
if ( !this.options.theme ) {
this._setTheme( this._page.jqmData( "theme" ) || $.mobile.getInheritedTheme( this._page, "c" ) );
}
this._ui.screen.removeClass( "ui-screen-hidden" );
this._ui.container.removeClass( "ui-popup-hidden" );
// Give applications a chance to modify the contents of the container before it appears
this._reposition( o );
if ( this.options.overlayTheme && androidBlacklist ) {
/* TODO:
The native browser on Android 4.0.X ("Ice Cream Sandwich") suffers from an issue where the popup overlay appears to be z-indexed
above the popup itself when certain other styles exist on the same page -- namely, any element set to `position: fixed` and certain
types of input. These issues are reminiscent of previously uncovered bugs in older versions of Android's native browser:
https://github.com/scottjehl/Device-Bugs/issues/3
This fix closes the following bugs ( I use "closes" with reluctance, and stress that this issue should be revisited as soon as possible ):
https://github.com/jquery/jquery-mobile/issues/4816
https://github.com/jquery/jquery-mobile/issues/4844
https://github.com/jquery/jquery-mobile/issues/4874
*/
// TODO sort out why this._page isn't working
this.element.closest( ".ui-page" ).addClass( "ui-popup-open" );
}
this._animate({
additionalCondition: true,
transition: o.transition,
classToRemove: "",
screenClassToAdd: "in",
containerClassToAdd: "in",
applyTransition: false,
prereqs: this._prereqs
});
},
_closePrereqScreen: function() {
this._ui.screen
.removeClass( "out" )
.addClass( "ui-screen-hidden" );
},
_closePrereqContainer: function() {
this._ui.container
.removeClass( "reverse out" )
.addClass( "ui-popup-hidden" )
.removeAttr( "style" );
},
_closePrereqsDone: function() {
var container = this._ui.container;
container.removeAttr( "tabindex" );
// remove the global mutex for popups
$.mobile.popup.active = undefined;
// Blur elements inside the container, including the container
$( ":focus", container[ 0 ] ).add( container[ 0 ] ).blur();
// alert users that the popup is closed
this._trigger( "afterclose" );
},
_close: function( immediate ) {
this._ui.container.removeClass( "ui-popup-active" );
this._page.removeClass( "ui-popup-open" );
this._isOpen = false;
// Count down to triggering "popupafterclose" - we have two prerequisites:
// 1. The popup window reverse animation completes (container())
// 2. The screen opacity animation completes (screen())
this._createPrereqs(
$.proxy( this, "_closePrereqScreen" ),
$.proxy( this, "_closePrereqContainer" ),
$.proxy( this, "_closePrereqsDone" ) );
this._animate( {
additionalCondition: this._ui.screen.hasClass( "in" ),
transition: ( immediate ? "none" : ( this._currentTransition ) ),
classToRemove: "in",
screenClassToAdd: "out",
containerClassToAdd: "reverse out",
applyTransition: true,
prereqs: this._prereqs
});
},
_unenhance: function() {
// Put the element back to where the placeholder was and remove the "ui-popup" class
this._setTheme( "none" );
this.element
// Cannot directly insertAfter() - we need to detach() first, because
// insertAfter() will do nothing if the payload div was not attached
// to the DOM at the time the widget was created, and so the payload
// will remain inside the container even after we call insertAfter().
// If that happens and we remove the container a few lines below, we
// will cause an infinite recursion - #5244
.detach()
.insertAfter( this._ui.placeholder )
.removeClass( "ui-popup ui-overlay-shadow ui-corner-all" );
this._ui.screen.remove();
this._ui.container.remove();
this._ui.placeholder.remove();
},
_destroy: function() {
if ( $.mobile.popup.active === this ) {
this.element.one( "popupafterclose", $.proxy( this, "_unenhance" ) );
this.close();
} else {
this._unenhance();
}
},
_closePopup: function( e, data ) {
var parsedDst, toUrl, o = this.options, immediate = false;
// restore location on screen
window.scrollTo( 0, this._scrollTop );
if ( e && e.type === "pagebeforechange" && data ) {
// Determine whether we need to rapid-close the popup, or whether we can
// take the time to run the closing transition
if ( typeof data.toPage === "string" ) {
parsedDst = data.toPage;
} else {
parsedDst = data.toPage.jqmData( "url" );
}
parsedDst = $.mobile.path.parseUrl( parsedDst );
toUrl = parsedDst.pathname + parsedDst.search + parsedDst.hash;
if ( this._myUrl !== $.mobile.path.makeUrlAbsolute( toUrl ) ) {
// Going to a different page - close immediately
immediate = true;
} else {
e.preventDefault();
}
}
// remove nav bindings
o.container.unbind( o.closeEvents );
// unbind click handlers added when history is disabled
this.element.undelegate( o.closeLinkSelector, o.closeLinkEvents );
this._close( immediate );
},
// any navigation event after a popup is opened should close the popup
// NOTE the pagebeforechange is bound to catch navigation events that don't
// alter the url (eg, dialogs from popups)
_bindContainerClose: function() {
this.options.container
.one( this.options.closeEvents, $.proxy( this, "_closePopup" ) );
},
// TODO no clear deliniation of what should be here and
// what should be in _open. Seems to be "visual" vs "history" for now
open: function( options ) {
var self = this, opts = this.options, url, hashkey, activePage, currentIsDialog, hasHash, urlHistory;
// make sure open is idempotent
if( $.mobile.popup.active ) {
return;
}
// set the global popup mutex
$.mobile.popup.active = this;
this._scrollTop = $.mobile.window.scrollTop();
// if history alteration is disabled close on navigate events
// and leave the url as is
if( !( opts.history ) ) {
self._open( options );
self._bindContainerClose();
// When histoy is disabled we have to grab the data-rel
// back link clicks so we can close the popup instead of
// relying on history to do it for us
self.element
.delegate( opts.closeLinkSelector, opts.closeLinkEvents, function( e ) {
self.close();
e.preventDefault();
});
return;
}
// cache some values for min/readability
urlHistory = $.mobile.urlHistory;
hashkey = $.mobile.dialogHashKey;
activePage = $.mobile.activePage;
currentIsDialog = activePage.is( ".ui-dialog" );
this._myUrl = url = urlHistory.getActive().url;
hasHash = ( url.indexOf( hashkey ) > -1 ) && !currentIsDialog && ( urlHistory.activeIndex > 0 );
if ( hasHash ) {
self._open( options );
self._bindContainerClose();
return;
}
// if the current url has no dialog hash key proceed as normal
// otherwise, if the page is a dialog simply tack on the hash key
if ( url.indexOf( hashkey ) === -1 && !currentIsDialog ){
url = url + (url.indexOf( "#" ) > -1 ? hashkey : "#" + hashkey);
} else {
url = $.mobile.path.parseLocation().hash + hashkey;
}
// Tack on an extra hashkey if this is the first page and we've just reconstructed the initial hash
if ( urlHistory.activeIndex === 0 && url === urlHistory.initialDst ) {
url += hashkey;
}
// swallow the the initial navigation event, and bind for the next
$(window).one( "beforenavigate", function( e ) {
e.preventDefault();
self._open( options );
self._bindContainerClose();
});
this.urlAltered = true;
$.mobile.navigate( url, {role: "dialog"} );
},
close: function() {
// make sure close is idempotent
if( $.mobile.popup.active !== this ) {
return;
}
this._scrollTop = $.mobile.window.scrollTop();
if( this.options.history && this.urlAltered ) {
$.mobile.back();
this.urlAltered = false;
} else {
// simulate the nav bindings having fired
this._closePopup();
}
}
});
// TODO this can be moved inside the widget
$.mobile.popup.handleLink = function( $link ) {
var closestPage = $link.closest( ":jqmData(role='page')" ),
scope = ( ( closestPage.length === 0 ) ? $( "body" ) : closestPage ),
// NOTE make sure to get only the hash, ie7 (wp7) return the absolute href
// in this case ruining the element selection
popup = $( $.mobile.path.parseUrl($link.attr( "href" )).hash, scope[0] ),
offset;
if ( popup.data( "mobile-popup" ) ) {
offset = $link.offset();
popup.popup( "open", {
x: offset.left + $link.outerWidth() / 2,
y: offset.top + $link.outerHeight() / 2,
transition: $link.jqmData( "transition" ),
positionTo: $link.jqmData( "position-to" )
});
}
//remove after delay
setTimeout( function() {
// Check if we are in a listview
var $parent = $link.parent().parent();
if ($parent.hasClass("ui-li")) {
$link = $parent.parent();
}
$link.removeClass( $.mobile.activeBtnClass );
}, 300 );
};
// TODO move inside _create
$.mobile.document.bind( "pagebeforechange", function( e, data ) {
if ( data.options.role === "popup" ) {
$.mobile.popup.handleLink( data.options.link );
e.preventDefault();
}
});
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.popup.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
/*
* custom "selectmenu" plugin
*/
(function( $, undefined ) {
var extendSelect = function( widget ) {
var select = widget.select,
origDestroy = widget._destroy,
selectID = widget.selectID,
prefix = ( selectID ? selectID : ( ( $.mobile.ns || "" ) + "uuid-" + widget.uuid ) ),
popupID = prefix + "-listbox",
dialogID = prefix + "-dialog",
label = widget.label,
thisPage = widget.select.closest( ".ui-page" ),
selectOptions = widget._selectOptions(),
isMultiple = widget.isMultiple = widget.select[ 0 ].multiple,
buttonId = selectID + "-button",
menuId = selectID + "-menu",
menuPage = $( "<div data-" + $.mobile.ns + "role='dialog' id='" + dialogID + "' data-" +$.mobile.ns + "theme='"+ widget.options.theme +"' data-" +$.mobile.ns + "overlay-theme='"+ widget.options.overlayTheme +"'>" +
"<div data-" + $.mobile.ns + "role='header'>" +
"<div class='ui-title'>" + label.getEncodedText() + "</div>"+
"</div>"+
"<div data-" + $.mobile.ns + "role='content'></div>"+
"</div>" ),
listbox = $( "<div id='" + popupID + "' class='ui-selectmenu'>" ).insertAfter( widget.select ).popup( { theme: widget.options.overlayTheme } ),
list = $( "<ul>", {
"class": "ui-selectmenu-list",
"id": menuId,
"role": "listbox",
"aria-labelledby": buttonId
}).attr( "data-" + $.mobile.ns + "theme", widget.options.theme )
.attr( "data-" + $.mobile.ns + "divider-theme", widget.options.dividerTheme )
.appendTo( listbox ),
header = $( "<div>", {
"class": "ui-header ui-bar-" + widget.options.theme
}).prependTo( listbox ),
headerTitle = $( "<h1>", {
"class": "ui-title"
}).appendTo( header ),
menuPageContent,
menuPageClose,
headerClose;
if ( widget.isMultiple ) {
headerClose = $( "<a>", {
"text": widget.options.closeText,
"href": "#",
"class": "ui-btn-left"
}).attr( "data-" + $.mobile.ns + "iconpos", "notext" ).attr( "data-" + $.mobile.ns + "icon", "delete" ).appendTo( header ).buttonMarkup();
}
$.extend( widget, {
select: widget.select,
selectID: selectID,
buttonId: buttonId,
menuId: menuId,
popupID: popupID,
dialogID: dialogID,
thisPage: thisPage,
menuPage: menuPage,
label: label,
selectOptions: selectOptions,
isMultiple: isMultiple,
theme: widget.options.theme,
listbox: listbox,
list: list,
header: header,
headerTitle: headerTitle,
headerClose: headerClose,
menuPageContent: menuPageContent,
menuPageClose: menuPageClose,
placeholder: "",
build: function() {
var self = this,
escapeId = function( id ) {
return id.replace( /([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g, "\\$1" );
};
// Create list from select, update state
self.refresh();
if ( self._origTabIndex === undefined ) {
// Map undefined to false, because self._origTabIndex === undefined
// indicates that we have not yet checked whether the select has
// originally had a tabindex attribute, whereas false indicates that
// we have checked the select for such an attribute, and have found
// none present.
self._origTabIndex = ( self.select[ 0 ].getAttribute( "tabindex" ) === null ) ? false : self.select.attr( "tabindex" );
}
self.select.attr( "tabindex", "-1" ).focus(function() {
$( this ).blur();
self.button.focus();
});
// Button events
self.button.bind( "vclick keydown" , function( event ) {
if ( self.options.disabled || self.isOpen ) {
return;
}
if (event.type === "vclick" ||
event.keyCode && (event.keyCode === $.mobile.keyCode.ENTER ||
event.keyCode === $.mobile.keyCode.SPACE)) {
self._decideFormat();
if ( self.menuType === "overlay" ) {
self.button.attr( "href", "#" + escapeId( self.popupID ) ).attr( "data-" + ( $.mobile.ns || "" ) + "rel", "popup" );
} else {
self.button.attr( "href", "#" + escapeId( self.dialogID ) ).attr( "data-" + ( $.mobile.ns || "" ) + "rel", "dialog" );
}
self.isOpen = true;
// Do not prevent default, so the navigation may have a chance to actually open the chosen format
}
});
// Events for list items
self.list.attr( "role", "listbox" )
.bind( "focusin", function( e ) {
$( e.target )
.attr( "tabindex", "0" )
.trigger( "vmouseover" );
})
.bind( "focusout", function( e ) {
$( e.target )
.attr( "tabindex", "-1" )
.trigger( "vmouseout" );
})
.delegate( "li:not(.ui-disabled, .ui-li-divider)", "click", function( event ) {
// index of option tag to be selected
var oldIndex = self.select[ 0 ].selectedIndex,
newIndex = self.list.find( "li:not(.ui-li-divider)" ).index( this ),
option = self._selectOptions().eq( newIndex )[ 0 ];
// toggle selected status on the tag for multi selects
option.selected = self.isMultiple ? !option.selected : true;
// toggle checkbox class for multiple selects
if ( self.isMultiple ) {
$( this ).find( ".ui-icon" )
.toggleClass( "ui-icon-checkbox-on", option.selected )
.toggleClass( "ui-icon-checkbox-off", !option.selected );
}
// trigger change if value changed
if ( self.isMultiple || oldIndex !== newIndex ) {
self.select.trigger( "change" );
}
// hide custom select for single selects only - otherwise focus clicked item
// We need to grab the clicked item the hard way, because the list may have been rebuilt
if ( self.isMultiple ) {
self.list.find( "li:not(.ui-li-divider)" ).eq( newIndex )
.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
}
else {
self.close();
}
event.preventDefault();
})
.keydown(function( event ) { //keyboard events for menu items
var target = $( event.target ),
li = target.closest( "li" ),
prev, next;
// switch logic based on which key was pressed
switch ( event.keyCode ) {
// up or left arrow keys
case 38:
prev = li.prev().not( ".ui-selectmenu-placeholder" );
if ( prev.is( ".ui-li-divider" ) ) {
prev = prev.prev();
}
// if there's a previous option, focus it
if ( prev.length ) {
target
.blur()
.attr( "tabindex", "-1" );
prev.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
}
return false;
// down or right arrow keys
case 40:
next = li.next();
if ( next.is( ".ui-li-divider" ) ) {
next = next.next();
}
// if there's a next option, focus it
if ( next.length ) {
target
.blur()
.attr( "tabindex", "-1" );
next.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
}
return false;
// If enter or space is pressed, trigger click
case 13:
case 32:
target.trigger( "click" );
return false;
}
});
// button refocus ensures proper height calculation
// by removing the inline style and ensuring page inclusion
self.menuPage.bind( "pagehide", function() {
// TODO centralize page removal binding / handling in the page plugin.
// Suggestion from @jblas to do refcounting
//
// TODO extremely confusing dependency on the open method where the pagehide.remove
// bindings are stripped to prevent the parent page from disappearing. The way
// we're keeping pages in the DOM right now sucks
//
// rebind the page remove that was unbound in the open function
// to allow for the parent page removal from actions other than the use
// of a dialog sized custom select
//
// doing this here provides for the back button on the custom select dialog
$.mobile._bindPageRemove.call( self.thisPage );
});
// Events on the popup
self.listbox.bind( "popupafterclose", function( event ) {
self.close();
});
// Close button on small overlays
if ( self.isMultiple ) {
self.headerClose.click(function() {
if ( self.menuType === "overlay" ) {
self.close();
return false;
}
});
}
// track this dependency so that when the parent page
// is removed on pagehide it will also remove the menupage
self.thisPage.addDependents( this.menuPage );
},
_isRebuildRequired: function() {
var list = this.list.find( "li" ),
options = this._selectOptions();
// TODO exceedingly naive method to determine difference
// ignores value changes etc in favor of a forcedRebuild
// from the user in the refresh method
return options.text() !== list.text();
},
selected: function() {
return this._selectOptions().filter( ":selected:not( :jqmData(placeholder='true') )" );
},
refresh: function( forceRebuild , foo ) {
var self = this,
select = this.element,
isMultiple = this.isMultiple,
indicies;
if ( forceRebuild || this._isRebuildRequired() ) {
self._buildList();
}
indicies = this.selectedIndices();
self.setButtonText();
self.setButtonCount();
self.list.find( "li:not(.ui-li-divider)" )
.removeClass( $.mobile.activeBtnClass )
.attr( "aria-selected", false )
.each(function( i ) {
if ( $.inArray( i, indicies ) > -1 ) {
var item = $( this );
// Aria selected attr
item.attr( "aria-selected", true );
// Multiple selects: add the "on" checkbox state to the icon
if ( self.isMultiple ) {
item.find( ".ui-icon" ).removeClass( "ui-icon-checkbox-off" ).addClass( "ui-icon-checkbox-on" );
} else {
if ( item.is( ".ui-selectmenu-placeholder" ) ) {
item.next().addClass( $.mobile.activeBtnClass );
} else {
item.addClass( $.mobile.activeBtnClass );
}
}
}
});
},
close: function() {
if ( this.options.disabled || !this.isOpen ) {
return;
}
var self = this;
if ( self.menuType === "page" ) {
self.menuPage.dialog( "close" );
self.list.appendTo( self.listbox );
} else {
self.listbox.popup( "close" );
}
self._focusButton();
// allow the dialog to be closed again
self.isOpen = false;
},
open: function() {
this.button.click();
},
_decideFormat: function() {
var self = this,
$window = $.mobile.window,
selfListParent = self.list.parent(),
menuHeight = selfListParent.outerHeight(),
menuWidth = selfListParent.outerWidth(),
activePage = $( "." + $.mobile.activePageClass ),
scrollTop = $window.scrollTop(),
btnOffset = self.button.offset().top,
screenHeight = $window.height(),
screenWidth = $window.width();
function focusMenuItem() {
var selector = self.list.find( "." + $.mobile.activeBtnClass + " a" );
if ( selector.length === 0 ) {
selector = self.list.find( "li.ui-btn:not( :jqmData(placeholder='true') ) a" );
}
selector.first().focus().closest( "li" ).addClass( "ui-btn-down-" + widget.options.theme );
}
if ( menuHeight > screenHeight - 80 || !$.support.scrollTop ) {
self.menuPage.appendTo( $.mobile.pageContainer ).page();
self.menuPageContent = menuPage.find( ".ui-content" );
self.menuPageClose = menuPage.find( ".ui-header a" );
// prevent the parent page from being removed from the DOM,
// otherwise the results of selecting a list item in the dialog
// fall into a black hole
self.thisPage.unbind( "pagehide.remove" );
//for WebOS/Opera Mini (set lastscroll using button offset)
if ( scrollTop === 0 && btnOffset > screenHeight ) {
self.thisPage.one( "pagehide", function() {
$( this ).jqmData( "lastScroll", btnOffset );
});
}
self.menuPage
.one( "pageshow", function() {
focusMenuItem();
})
.one( "pagehide", function() {
self.close();
});
self.menuType = "page";
self.menuPageContent.append( self.list );
self.menuPage.find("div .ui-title").text(self.label.text());
} else {
self.menuType = "overlay";
self.listbox.one( "popupafteropen", focusMenuItem );
}
},
_buildList: function() {
var self = this,
o = this.options,
placeholder = this.placeholder,
needPlaceholder = true,
optgroups = [],
lis = [],
dataIcon = self.isMultiple ? "checkbox-off" : "false";
self.list.empty().filter( ".ui-listview" ).listview( "destroy" );
var $options = self.select.find( "option" ),
numOptions = $options.length,
select = this.select[ 0 ],
dataPrefix = 'data-' + $.mobile.ns,
dataIndexAttr = dataPrefix + 'option-index',
dataIconAttr = dataPrefix + 'icon',
dataRoleAttr = dataPrefix + 'role',
dataPlaceholderAttr = dataPrefix + 'placeholder',
fragment = document.createDocumentFragment(),
isPlaceholderItem = false,
optGroup;
for (var i = 0; i < numOptions;i++, isPlaceholderItem = false) {
var option = $options[i],
$option = $( option ),
parent = option.parentNode,
text = $option.text(),
anchor = document.createElement( 'a' ),
classes = [];
anchor.setAttribute( 'href', '#' );
anchor.appendChild( document.createTextNode( text ) );
// Are we inside an optgroup?
if ( parent !== select && parent.nodeName.toLowerCase() === "optgroup" ) {
var optLabel = parent.getAttribute( 'label' );
if ( optLabel !== optGroup ) {
var divider = document.createElement( 'li' );
divider.setAttribute( dataRoleAttr, 'list-divider' );
divider.setAttribute( 'role', 'option' );
divider.setAttribute( 'tabindex', '-1' );
divider.appendChild( document.createTextNode( optLabel ) );
fragment.appendChild( divider );
optGroup = optLabel;
}
}
if ( needPlaceholder && ( !option.getAttribute( "value" ) || text.length === 0 || $option.jqmData( "placeholder" ) ) ) {
needPlaceholder = false;
isPlaceholderItem = true;
// If we have identified a placeholder, record the fact that it was
// us who have added the placeholder to the option and mark it
// retroactively in the select as well
if ( null === option.getAttribute( dataPlaceholderAttr ) ) {
this._removePlaceholderAttr = true;
}
option.setAttribute( dataPlaceholderAttr, true );
if ( o.hidePlaceholderMenuItems ) {
classes.push( "ui-selectmenu-placeholder" );
}
if ( placeholder !== text ) {
placeholder = self.placeholder = text;
}
}
var item = document.createElement('li');
if ( option.disabled ) {
classes.push( "ui-disabled" );
item.setAttribute('aria-disabled',true);
}
item.setAttribute( dataIndexAttr,i );
item.setAttribute( dataIconAttr, dataIcon );
if ( isPlaceholderItem ) {
item.setAttribute( dataPlaceholderAttr, true );
}
item.className = classes.join( " " );
item.setAttribute( 'role', 'option' );
anchor.setAttribute( 'tabindex', '-1' );
item.appendChild( anchor );
fragment.appendChild( item );
}
self.list[0].appendChild( fragment );
// Hide header if it's not a multiselect and there's no placeholder
if ( !this.isMultiple && !placeholder.length ) {
this.header.hide();
} else {
this.headerTitle.text( this.placeholder );
}
// Now populated, create listview
self.list.listview();
},
_button: function() {
return $( "<a>", {
"href": "#",
"role": "button",
// TODO value is undefined at creation
"id": this.buttonId,
"aria-haspopup": "true",
// TODO value is undefined at creation
"aria-owns": this.menuId
});
},
_destroy: function() {
this.close();
// Restore the tabindex attribute to its original value
if ( this._origTabIndex !== undefined ) {
if ( this._origTabIndex !== false ) {
this.select.attr( "tabindex", this._origTabIndex );
} else {
this.select.removeAttr( "tabindex" );
}
}
// Remove the placeholder attribute if we were the ones to add it
if ( this._removePlaceholderAttr ) {
this._selectOptions().removeAttr( "data-" + $.mobile.ns + "placeholder" );
}
// Remove the popup
this.listbox.remove();
// Remove the dialog
this.menuPage.remove();
// Chain up
origDestroy.apply( this, arguments );
}
});
};
// issue #3894 - core doesn't trigger events on disabled delegates
$.mobile.document.bind( "selectmenubeforecreate", function( event ) {
var selectmenuWidget = $( event.target ).data( "mobile-selectmenu" );
if ( !selectmenuWidget.options.nativeMenu &&
selectmenuWidget.element.parents( ":jqmData(role='popup')" ).length === 0 ) {
extendSelect( selectmenuWidget );
}
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.controlgroup", $.mobile.widget, $.extend( {
options: {
shadow: false,
corners: true,
excludeInvisible: true,
type: "vertical",
mini: false,
initSelector: ":jqmData(role='controlgroup')"
},
_create: function() {
var $el = this.element,
ui = {
inner: $( "<div class='ui-controlgroup-controls'></div>" ),
legend: $( "<div role='heading' class='ui-controlgroup-label'></div>" )
},
grouplegend = $el.children( "legend" ),
self = this;
// Apply the proto
$el.wrapInner( ui.inner );
if ( grouplegend.length ) {
ui.legend.append( grouplegend ).insertBefore( $el.children( 0 ) );
}
$el.addClass( "ui-corner-all ui-controlgroup" );
$.extend( this, {
_initialRefresh: true
});
$.each( this.options, function( key, value ) {
// Cause initial options to be applied by their handler by temporarily setting the option to undefined
// - the handler then sets it to the initial value
self.options[ key ] = undefined;
self._setOption( key, value, true );
});
},
_init: function() {
this.refresh();
},
_setOption: function( key, value ) {
var setter = "_set" + key.charAt( 0 ).toUpperCase() + key.slice( 1 );
if ( this[ setter ] !== undefined ) {
this[ setter ]( value );
}
this._super( key, value );
this.element.attr( "data-" + ( $.mobile.ns || "" ) + ( key.replace( /([A-Z])/, "-$1" ).toLowerCase() ), value );
},
_setType: function( value ) {
this.element
.removeClass( "ui-controlgroup-horizontal ui-controlgroup-vertical" )
.addClass( "ui-controlgroup-" + value );
this.refresh();
},
_setCorners: function( value ) {
this.element.toggleClass( "ui-corner-all", value );
},
_setShadow: function( value ) {
this.element.toggleClass( "ui-shadow", value );
},
_setMini: function( value ) {
this.element.toggleClass( "ui-mini", value );
},
container: function() {
return this.element.children( ".ui-controlgroup-controls" );
},
refresh: function() {
var els = this.element.find( ".ui-btn" ).not( ".ui-slider-handle" ),
create = this._initialRefresh;
if ( $.mobile.checkboxradio ) {
this.element.find( ":mobile-checkboxradio" ).checkboxradio( "refresh" );
}
this._addFirstLastClasses( els, this.options.excludeInvisible ? this._getVisibles( els, create ) : els, create );
this._initialRefresh = false;
}
}, $.mobile.behaviors.addFirstLastClasses ) );
// TODO: Implement a mechanism to allow widgets to become enhanced in the
// correct order when their correct enhancement depends on other widgets in
// the page being correctly enhanced already.
//
// For now, we wait until dom-ready to attach the controlgroup's enhancement
// hook, because by that time, all the other widgets' enhancement hooks should
// already be in place, ensuring that all widgets that need to be grouped will
// already have been enhanced by the time the controlgroup is created.
$( function() {
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.controlgroup.prototype.enhanceWithin( e.target, true );
});
});
})(jQuery);
(function( $, undefined ) {
$( document ).bind( "pagecreate create", function( e ) {
//links within content areas, tests included with page
$( e.target )
.find( "a" )
.jqmEnhanceable()
.filter( ":jqmData(rel='popup')[href][href!='']" )
.each( function() {
// Accessibility info for popups
var e = this,
href = $( this ).attr( "href" ),
idref = href.substring( 1 );
e.setAttribute( "aria-haspopup", true );
e.setAttribute( "aria-owns", idref );
e.setAttribute( "aria-expanded", false );
$( document )
.on( "popupafteropen", href, function() {
e.setAttribute( "aria-expanded", true );
})
.on( "popupafterclose", href, function() {
e.setAttribute( "aria-expanded", false );
});
})
.end()
.not( ".ui-btn, .ui-link-inherit, :jqmData(role='none'), :jqmData(role='nojs')" )
.addClass( "ui-link" );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.fixedtoolbar", $.mobile.widget, {
options: {
visibleOnPageShow: true,
disablePageZoom: true,
transition: "slide", //can be none, fade, slide (slide maps to slideup or slidedown)
fullscreen: false,
tapToggle: true,
tapToggleBlacklist: "a, button, input, select, textarea, .ui-header-fixed, .ui-footer-fixed, .ui-popup, .ui-panel, .ui-panel-dismiss-open",
hideDuringFocus: "input, textarea, select",
updatePagePadding: true,
trackPersistentToolbars: true,
// Browser detection! Weeee, here we go...
// Unfortunately, position:fixed is costly, not to mention probably impossible, to feature-detect accurately.
// Some tests exist, but they currently return false results in critical devices and browsers, which could lead to a broken experience.
// Testing fixed positioning is also pretty obtrusive to page load, requiring injected elements and scrolling the window
// The following function serves to rule out some popular browsers with known fixed-positioning issues
// This is a plugin option like any other, so feel free to improve or overwrite it
supportBlacklist: function() {
return !$.support.fixedPosition;
},
initSelector: ":jqmData(position='fixed')"
},
_create: function() {
var self = this,
o = self.options,
$el = self.element,
tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer",
$page = $el.closest( ".ui-page" );
// Feature detecting support for
if ( o.supportBlacklist() ) {
self.destroy();
return;
}
$el.addClass( "ui-"+ tbtype +"-fixed" );
// "fullscreen" overlay positioning
if ( o.fullscreen ) {
$el.addClass( "ui-"+ tbtype +"-fullscreen" );
$page.addClass( "ui-page-" + tbtype + "-fullscreen" );
}
// If not fullscreen, add class to page to set top or bottom padding
else{
$page.addClass( "ui-page-" + tbtype + "-fixed" );
}
$.extend( this, {
_thisPage: null
});
self._addTransitionClass();
self._bindPageEvents();
self._bindToggleHandlers();
},
_addTransitionClass: function() {
var tclass = this.options.transition;
if ( tclass && tclass !== "none" ) {
// use appropriate slide for header or footer
if ( tclass === "slide" ) {
tclass = this.element.is( ".ui-header" ) ? "slidedown" : "slideup";
}
this.element.addClass( tclass );
}
},
_bindPageEvents: function() {
this._thisPage = this.element.closest( ".ui-page" );
//page event bindings
// Fixed toolbars require page zoom to be disabled, otherwise usability issues crop up
// This method is meant to disable zoom while a fixed-positioned toolbar page is visible
this._on( this._thisPage, {
"pagebeforeshow": "_handlePageBeforeShow",
"webkitAnimationStart":"_handleAnimationStart",
"animationstart":"_handleAnimationStart",
"updatelayout": "_handleAnimationStart",
"pageshow": "_handlePageShow",
"pagebeforehide": "_handlePageBeforeHide"
});
},
_handlePageBeforeShow: function() {
var o = this.options;
if ( o.disablePageZoom ) {
$.mobile.zoom.disable( true );
}
if ( !o.visibleOnPageShow ) {
this.hide( true );
}
},
_handleAnimationStart: function() {
if ( this.options.updatePagePadding ) {
this.updatePagePadding( this._thisPage );
}
},
_handlePageShow: function() {
this.updatePagePadding( this._thisPage );
if ( this.options.updatePagePadding ) {
this._on( $.mobile.window, { "throttledresize": "updatePagePadding" } );
}
},
_handlePageBeforeHide: function( e, ui ) {
var o = this.options;
if ( o.disablePageZoom ) {
$.mobile.zoom.enable( true );
}
if ( o.updatePagePadding ) {
this._off( $.mobile.window, "throttledresize" );
}
if ( o.trackPersistentToolbars ) {
var thisFooter = $( ".ui-footer-fixed:jqmData(id)", this._thisPage ),
thisHeader = $( ".ui-header-fixed:jqmData(id)", this._thisPage ),
nextFooter = thisFooter.length && ui.nextPage && $( ".ui-footer-fixed:jqmData(id='" + thisFooter.jqmData( "id" ) + "')", ui.nextPage ) || $(),
nextHeader = thisHeader.length && ui.nextPage && $( ".ui-header-fixed:jqmData(id='" + thisHeader.jqmData( "id" ) + "')", ui.nextPage ) || $();
if ( nextFooter.length || nextHeader.length ) {
nextFooter.add( nextHeader ).appendTo( $.mobile.pageContainer );
ui.nextPage.one( "pageshow", function() {
nextHeader.prependTo( this );
nextFooter.appendTo( this );
});
}
}
},
_visible: true,
// This will set the content element's top or bottom padding equal to the toolbar's height
updatePagePadding: function( tbPage ) {
var $el = this.element,
header = $el.is( ".ui-header" ),
pos = parseFloat( $el.css( header ? "top" : "bottom" ) );
// This behavior only applies to "fixed", not "fullscreen"
if ( this.options.fullscreen ) { return; }
// tbPage argument can be a Page object or an event, if coming from throttled resize.
tbPage = ( tbPage && tbPage.type === undefined && tbPage ) || this._thisPage || $el.closest( ".ui-page" );
$( tbPage ).css( "padding-" + ( header ? "top" : "bottom" ), $el.outerHeight() + pos );
},
_useTransition: function( notransition ) {
var $win = $.mobile.window,
$el = this.element,
scroll = $win.scrollTop(),
elHeight = $el.height(),
pHeight = $el.closest( ".ui-page" ).height(),
viewportHeight = $.mobile.getScreenHeight(),
tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer";
return !notransition &&
( this.options.transition && this.options.transition !== "none" &&
(
( tbtype === "header" && !this.options.fullscreen && scroll > elHeight ) ||
( tbtype === "footer" && !this.options.fullscreen && scroll + viewportHeight < pHeight - elHeight )
) || this.options.fullscreen
);
},
show: function( notransition ) {
var hideClass = "ui-fixed-hidden",
$el = this.element;
if ( this._useTransition( notransition ) ) {
$el
.removeClass( "out " + hideClass )
.addClass( "in" )
.animationComplete(function () {
$el.removeClass('in');
});
}
else {
$el.removeClass( hideClass );
}
this._visible = true;
},
hide: function( notransition ) {
var hideClass = "ui-fixed-hidden",
$el = this.element,
// if it's a slide transition, our new transitions need the reverse class as well to slide outward
outclass = "out" + ( this.options.transition === "slide" ? " reverse" : "" );
if( this._useTransition( notransition ) ) {
$el
.addClass( outclass )
.removeClass( "in" )
.animationComplete(function() {
$el.addClass( hideClass ).removeClass( outclass );
});
}
else {
$el.addClass( hideClass ).removeClass( outclass );
}
this._visible = false;
},
toggle: function() {
this[ this._visible ? "hide" : "show" ]();
},
_bindToggleHandlers: function() {
var self = this,
o = self.options,
$el = self.element,
delayShow, delayHide,
isVisible = true;
// tap toggle
$el.closest( ".ui-page" )
.bind( "vclick", function( e ) {
if ( o.tapToggle && !$( e.target ).closest( o.tapToggleBlacklist ).length ) {
self.toggle();
}
})
.bind( "focusin focusout", function( e ) {
//this hides the toolbars on a keyboard pop to give more screen room and prevent ios bug which
//positions fixed toolbars in the middle of the screen on pop if the input is near the top or
//bottom of the screen addresses issues #4410 Footer navbar moves up when clicking on a textbox in an Android environment
//and issue #4113 Header and footer change their position after keyboard popup - iOS
//and issue #4410 Footer navbar moves up when clicking on a textbox in an Android environment
if ( screen.width < 1025 && $( e.target ).is( o.hideDuringFocus ) && !$( e.target ).closest( ".ui-header-fixed, .ui-footer-fixed" ).length ) {
//Fix for issue #4724 Moving through form in Mobile Safari with "Next" and "Previous" system
//controls causes fixed position, tap-toggle false Header to reveal itself
// isVisible instead of self._visible because the focusin and focusout events fire twice at the same time
// Also use a delay for hiding the toolbars because on Android native browser focusin is direclty followed
// by a focusout when a native selects opens and the other way around when it closes.
if ( e.type === "focusout" && !isVisible ) {
isVisible = true;
//wait for the stack to unwind and see if we have jumped to another input
clearTimeout( delayHide );
delayShow = setTimeout( function() {
self.show();
}, 0 );
} else if ( e.type === "focusin" && !!isVisible ) {
//if we have jumped to another input clear the time out to cancel the show.
clearTimeout( delayShow );
isVisible = false;
delayHide = setTimeout( function() {
self.hide();
}, 0 );
}
}
});
},
_destroy: function() {
var $el = this.element,
header = $el.is( ".ui-header" );
$el.closest( ".ui-page" ).css( "padding-" + ( header ? "top" : "bottom" ), "" );
$el.removeClass( "ui-header-fixed ui-footer-fixed ui-header-fullscreen ui-footer-fullscreen in out fade slidedown slideup ui-fixed-hidden" );
$el.closest( ".ui-page" ).removeClass( "ui-page-header-fixed ui-page-footer-fixed ui-page-header-fullscreen ui-page-footer-fullscreen" );
}
});
//auto self-init widgets
$.mobile.document
.bind( "pagecreate create", function( e ) {
// DEPRECATED in 1.1: support for data-fullscreen=true|false on the page element.
// This line ensures it still works, but we recommend moving the attribute to the toolbars themselves.
if ( $( e.target ).jqmData( "fullscreen" ) ) {
$( $.mobile.fixedtoolbar.prototype.options.initSelector, e.target ).not( ":jqmData(fullscreen)" ).jqmData( "fullscreen", true );
}
$.mobile.fixedtoolbar.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.fixedtoolbar", $.mobile.fixedtoolbar, {
_create: function() {
this._super();
this._workarounds();
},
//check the browser and version and run needed workarounds
_workarounds: function() {
var ua = navigator.userAgent,
platform = navigator.platform,
// Rendering engine is Webkit, and capture major version
wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ),
wkversion = !!wkmatch && wkmatch[ 1 ],
os = null,
self = this;
//set the os we are working in if it dosent match one with workarounds return
if( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ){
os = "ios";
} else if( ua.indexOf( "Android" ) > -1 ){
os = "android";
} else {
return;
}
//check os version if it dosent match one with workarounds return
if( os === "ios" ) {
//iOS workarounds
self._bindScrollWorkaround();
} else if( os === "android" && wkversion && wkversion < 534 ) {
//Android 2.3 run all Android 2.3 workaround
self._bindScrollWorkaround();
self._bindListThumbWorkaround();
} else {
return;
}
},
//Utility class for checking header and footer positions relative to viewport
_viewportOffset: function() {
var $el = this.element,
header = $el.is( ".ui-header" ),
offset = Math.abs($el.offset().top - $.mobile.window.scrollTop());
if( !header ) {
offset = Math.round(offset - $.mobile.window.height() + $el.outerHeight())-60;
}
return offset;
},
//bind events for _triggerRedraw() function
_bindScrollWorkaround: function() {
var self = this;
//bind to scrollstop and check if the toolbars are correctly positioned
this._on( $.mobile.window, { scrollstop: function() {
var viewportOffset = self._viewportOffset();
//check if the header is visible and if its in the right place
if( viewportOffset > 2 && self._visible) {
self._triggerRedraw();
}
}});
},
//this addresses issue #4250 Persistent footer instability in v1.1 with long select lists in Android 2.3.3
//and issue #3748 Android 2.x: Page transitions broken when fixed toolbars used
//the absolutely positioned thumbnail in a list view causes problems with fixed position buttons above in a nav bar
//setting the li's to -webkit-transform:translate3d(0,0,0); solves this problem to avoide potential issues in other
//platforms we scope this with the class ui-android-2x-fix
_bindListThumbWorkaround: function() {
this.element.closest(".ui-page").addClass( "ui-android-2x-fixed" );
},
//this addresses issues #4337 Fixed header problem after scrolling content on iOS and Android
//and device bugs project issue #1 Form elements can lose click hit area in position: fixed containers.
//this also addresses not on fixed toolbars page in docs
//adding 1px of padding to the bottom then removing it causes a "redraw"
//which positions the toolbars correctly (they will always be visually correct)
_triggerRedraw: function() {
var paddingBottom = parseFloat( $( ".ui-page-active" ).css( "padding-bottom" ) );
//trigger page redraw to fix incorrectly positioned fixed elements
$( ".ui-page-active" ).css( "padding-bottom", ( paddingBottom + 1 ) +"px" );
//if the padding is reset with out a timeout the reposition will not occure.
//this is independant of JQM the browser seems to need the time to react.
setTimeout( function() {
$( ".ui-page-active" ).css( "padding-bottom", paddingBottom + "px" );
}, 0 );
},
destroy: function() {
this._super();
//Remove the class we added to the page previously in android 2.x
this.element.closest(".ui-page-active").removeClass( "ui-android-2x-fix" );
}
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.panel", $.mobile.widget, {
options: {
classes: {
panel: "ui-panel",
panelOpen: "ui-panel-open",
panelClosed: "ui-panel-closed",
panelFixed: "ui-panel-fixed",
panelInner: "ui-panel-inner",
modal: "ui-panel-dismiss",
modalOpen: "ui-panel-dismiss-open",
pagePanel: "ui-page-panel",
pagePanelOpen: "ui-page-panel-open",
contentWrap: "ui-panel-content-wrap",
contentWrapOpen: "ui-panel-content-wrap-open",
contentWrapClosed: "ui-panel-content-wrap-closed",
contentFixedToolbar: "ui-panel-content-fixed-toolbar",
contentFixedToolbarOpen: "ui-panel-content-fixed-toolbar-open",
contentFixedToolbarClosed: "ui-panel-content-fixed-toolbar-closed",
animate: "ui-panel-animate"
},
animate: true,
theme: "c",
position: "left",
dismissible: true,
display: "reveal", //accepts reveal, push, overlay
initSelector: ":jqmData(role='panel')",
swipeClose: true,
positionFixed: false
},
_panelID: null,
_closeLink: null,
_page: null,
_modal: null,
_panelInner: null,
_wrapper: null,
_fixedToolbar: null,
_create: function() {
var self = this,
$el = self.element,
page = $el.closest( ":jqmData(role='page')" ),
_getPageTheme = function() {
var $theme = $.data( page[0], "mobilePage" ).options.theme,
$pageThemeClass = "ui-body-" + $theme;
return $pageThemeClass;
},
_getPanelInner = function() {
var $panelInner = $el.find( "." + self.options.classes.panelInner );
if ( $panelInner.length === 0 ) {
$panelInner = $el.children().wrapAll( '<div class="' + self.options.classes.panelInner + '" />' ).parent();
}
return $panelInner;
},
_getWrapper = function() {
var $wrapper = page.find( "." + self.options.classes.contentWrap );
if ( $wrapper.length === 0 ) {
$wrapper = page.children( ".ui-header:not(:jqmData(position='fixed')), .ui-content:not(:jqmData(role='popup')), .ui-footer:not(:jqmData(position='fixed'))" ).wrapAll( '<div class="' + self.options.classes.contentWrap + ' ' + _getPageTheme() + '" />' ).parent();
if ( $.support.cssTransform3d && !!self.options.animate ) {
$wrapper.addClass( self.options.classes.animate );
}
}
return $wrapper;
},
_getFixedToolbar = function() {
var $fixedToolbar = page.find( "." + self.options.classes.contentFixedToolbar );
if ( $fixedToolbar.length === 0 ) {
$fixedToolbar = page.find( ".ui-header:jqmData(position='fixed'), .ui-footer:jqmData(position='fixed')" ).addClass( self.options.classes.contentFixedToolbar );
if ( $.support.cssTransform3d && !!self.options.animate ) {
$fixedToolbar.addClass( self.options.classes.animate );
}
}
return $fixedToolbar;
};
// expose some private props to other methods
$.extend( this, {
_panelID: $el.attr( "id" ),
_closeLink: $el.find( ":jqmData(rel='close')" ),
_page: $el.closest( ":jqmData(role='page')" ),
_pageTheme: _getPageTheme(),
_panelInner: _getPanelInner(),
_wrapper: _getWrapper(),
_fixedToolbar: _getFixedToolbar()
});
self._addPanelClasses();
self._wrapper.addClass( this.options.classes.contentWrapClosed );
self._fixedToolbar.addClass( this.options.classes.contentFixedToolbarClosed );
// add class to page so we can set "overflow-x: hidden;" for it to fix Android zoom issue
self._page.addClass( self.options.classes.pagePanel );
// if animating, add the class to do so
if ( $.support.cssTransform3d && !!self.options.animate ) {
this.element.addClass( self.options.classes.animate );
}
self._bindUpdateLayout();
self._bindCloseEvents();
self._bindLinkListeners();
self._bindPageEvents();
if ( !!self.options.dismissible ) {
self._createModal();
}
self._bindSwipeEvents();
},
_createModal: function( options ) {
var self = this;
self._modal = $( "<div class='" + self.options.classes.modal + "' data-panelid='" + self._panelID + "'></div>" )
.on( "mousedown", function() {
self.close();
})
.appendTo( this._page );
},
_getPosDisplayClasses: function( prefix ) {
return prefix + "-position-" + this.options.position + " " + prefix + "-display-" + this.options.display;
},
_getPanelClasses: function() {
var panelClasses = this.options.classes.panel +
" " + this._getPosDisplayClasses( this.options.classes.panel ) +
" " + this.options.classes.panelClosed;
if ( this.options.theme ) {
panelClasses += " ui-body-" + this.options.theme;
}
if ( !!this.options.positionFixed ) {
panelClasses += " " + this.options.classes.panelFixed;
}
return panelClasses;
},
_addPanelClasses: function() {
this.element.addClass( this._getPanelClasses() );
},
_bindCloseEvents: function() {
var self = this;
self._closeLink.on( "click.panel" , function( e ) {
e.preventDefault();
self.close();
return false;
});
self.element.on( "click.panel" , "a:jqmData(ajax='false')", function( e ) {
self.close();
});
},
_positionPanel: function() {
var self = this,
panelInnerHeight = self._panelInner.outerHeight(),
expand = panelInnerHeight > $.mobile.getScreenHeight();
if ( expand || !self.options.positionFixed ) {
if ( expand ) {
self._unfixPanel();
$.mobile.resetActivePageHeight( panelInnerHeight );
}
self._scrollIntoView( panelInnerHeight );
} else {
self._fixPanel();
}
},
_scrollIntoView: function( panelInnerHeight ) {
if ( panelInnerHeight < $( window ).scrollTop() ) {
window.scrollTo( 0, 0 );
}
},
_bindFixListener: function() {
this._on( $( window ), { "throttledresize": "_positionPanel" });
},
_unbindFixListener: function() {
this._off( $( window ), "throttledresize" );
},
_unfixPanel: function() {
if ( !!this.options.positionFixed && $.support.fixedPosition ) {
this.element.removeClass( this.options.classes.panelFixed );
}
},
_fixPanel: function() {
if ( !!this.options.positionFixed && $.support.fixedPosition ) {
this.element.addClass( this.options.classes.panelFixed );
}
},
_bindUpdateLayout: function() {
var self = this;
self.element.on( "updatelayout", function( e ) {
if ( self._open ) {
self._positionPanel();
}
});
},
_bindLinkListeners: function() {
var self = this;
self._page.on( "click.panel" , "a", function( e ) {
if ( this.href.split( "#" )[ 1 ] === self._panelID && self._panelID !== undefined ) {
e.preventDefault();
var $link = $( this ),
$parent;
if ( ! $link.hasClass( "ui-link" ) ) {
// Check if we are in a listview
$parent = $link.parent().parent();
if ( $parent.hasClass( "ui-li" ) ) {
$link = $parent.parent();
}
$link.addClass( $.mobile.activeBtnClass );
self.element.one( "panelopen panelclose", function() {
$link.removeClass( $.mobile.activeBtnClass );
});
}
self.toggle();
return false;
}
});
},
_bindSwipeEvents: function() {
var self = this,
area = self._modal ? self.element.add( self._modal ) : self.element;
// on swipe, close the panel
if( !!self.options.swipeClose ) {
if ( self.options.position === "left" ) {
area.on( "swipeleft.panel", function( e ) {
self.close();
});
} else {
area.on( "swiperight.panel", function( e ) {
self.close();
});
}
}
},
_bindPageEvents: function() {
var self = this;
self._page
// Close the panel if another panel on the page opens
.on( "panelbeforeopen", function( e ) {
if ( self._open && e.target !== self.element[ 0 ] ) {
self.close();
}
})
// clean up open panels after page hide
.on( "pagehide", function( e ) {
if ( self._open ) {
self.close( true );
}
})
// on escape, close? might need to have a target check too...
.on( "keyup.panel", function( e ) {
if ( e.keyCode === 27 && self._open ) {
self.close();
}
});
},
// state storage of open or closed
_open: false,
_contentWrapOpenClasses: null,
_fixedToolbarOpenClasses: null,
_modalOpenClasses: null,
open: function( immediate ) {
if ( !this._open ) {
var self = this,
o = self.options,
_openPanel = function() {
self._page.off( "panelclose" );
self._page.jqmData( "panel", "open" );
if ( !immediate && $.support.cssTransform3d && !!o.animate ) {
self.element.add( self._wrapper ).on( self._transitionEndEvents, complete );
} else {
setTimeout( complete, 0 );
}
if ( self.options.theme && self.options.display !== "overlay" ) {
self._page
.removeClass( self._pageTheme )
.addClass( "ui-body-" + self.options.theme );
}
self.element.removeClass( o.classes.panelClosed ).addClass( o.classes.panelOpen );
self._positionPanel();
// Fix for IE7 min-height bug
if ( self.options.theme && self.options.display !== "overlay" ) {
self._wrapper.css( "min-height", self._page.css( "min-height" ) );
}
self._contentWrapOpenClasses = self._getPosDisplayClasses( o.classes.contentWrap );
self._wrapper
.removeClass( o.classes.contentWrapClosed )
.addClass( self._contentWrapOpenClasses + " " + o.classes.contentWrapOpen );
self._fixedToolbarOpenClasses = self._getPosDisplayClasses( o.classes.contentFixedToolbar );
self._fixedToolbar
.removeClass( o.classes.contentFixedToolbarClosed )
.addClass( self._fixedToolbarOpenClasses + " " + o.classes.contentFixedToolbarOpen );
self._modalOpenClasses = self._getPosDisplayClasses( o.classes.modal ) + " " + o.classes.modalOpen;
if ( self._modal ) {
self._modal.addClass( self._modalOpenClasses );
}
},
complete = function() {
self.element.add( self._wrapper ).off( self._transitionEndEvents, complete );
self._page.addClass( o.classes.pagePanelOpen );
self._bindFixListener();
self._trigger( "open" );
};
if ( this.element.closest( ".ui-page-active" ).length < 0 ) {
immediate = true;
}
self._trigger( "beforeopen" );
if ( self._page.jqmData('panel') === "open" ) {
self._page.on( "panelclose", function() {
_openPanel();
});
} else {
_openPanel();
}
self._open = true;
}
},
close: function( immediate ) {
if ( this._open ) {
var o = this.options,
self = this,
_closePanel = function() {
if ( !immediate && $.support.cssTransform3d && !!o.animate ) {
self.element.add( self._wrapper ).on( self._transitionEndEvents, complete );
} else {
setTimeout( complete, 0 );
}
self._page.removeClass( o.classes.pagePanelOpen );
self.element.removeClass( o.classes.panelOpen );
self._wrapper.removeClass( o.classes.contentWrapOpen );
self._fixedToolbar.removeClass( o.classes.contentFixedToolbarOpen );
if ( self._modal ) {
self._modal.removeClass( self._modalOpenClasses );
}
},
complete = function() {
if ( self.options.theme && self.options.display !== "overlay" ) {
self._page.removeClass( "ui-body-" + self.options.theme ).addClass( self._pageTheme );
// reset fix for IE7 min-height bug
self._wrapper.css( "min-height", "" );
}
self.element.add( self._wrapper ).off( self._transitionEndEvents, complete );
self.element.addClass( o.classes.panelClosed );
self._wrapper
.removeClass( self._contentWrapOpenClasses )
.addClass( o.classes.contentWrapClosed );
self._fixedToolbar
.removeClass( self._fixedToolbarOpenClasses )
.addClass( o.classes.contentFixedToolbarClosed );
self._fixPanel();
self._unbindFixListener();
$.mobile.resetActivePageHeight();
self._page.jqmRemoveData( "panel" );
self._trigger( "close" );
};
if ( this.element.closest( ".ui-page-active" ).length < 0 ) {
immediate = true;
}
self._trigger( "beforeclose" );
_closePanel();
self._open = false;
}
},
toggle: function( options ) {
this[ this._open ? "close" : "open" ]();
},
_transitionEndEvents: "webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd",
_destroy: function() {
var classes = this.options.classes,
theme = this.options.theme,
hasOtherSiblingPanels = this.element.siblings( "." + classes.panel ).length;
// create
if ( !hasOtherSiblingPanels ) {
this._wrapper.children().unwrap();
this._page.find( "a" ).unbind( "panelopen panelclose" );
this._page.removeClass( classes.pagePanel );
if ( this._open ) {
this._page.jqmRemoveData( "panel" );
this._page.removeClass( classes.pagePanelOpen );
if ( theme ) {
this._page.removeClass( "ui-body-" + theme ).addClass( this._pageTheme );
}
$.mobile.resetActivePageHeight();
}
} else if ( this._open ) {
this._wrapper.removeClass( classes.contentWrapOpen );
this._fixedToolbar.removeClass( classes.contentFixedToolbarOpen );
this._page.jqmRemoveData( "panel" );
this._page.removeClass( classes.pagePanelOpen );
if ( theme ) {
this._page.removeClass( "ui-body-" + theme ).addClass( this._pageTheme );
}
}
this._panelInner.children().unwrap();
this.element.removeClass( [ this._getPanelClasses(), classes.panelAnimate ].join( " " ) )
.off( "swipeleft.panel swiperight.panel" )
.off( "panelbeforeopen" )
.off( "panelhide" )
.off( "keyup.panel" )
.off( "updatelayout" );
this._closeLink.off( "click.panel" );
if ( this._modal ) {
this._modal.remove();
}
// open and close
this.element.off( this._transitionEndEvents )
.removeClass( [ classes.panelUnfixed, classes.panelClosed, classes.panelOpen ].join( " " ) );
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ) {
$.mobile.panel.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.table", $.mobile.widget, {
options: {
classes: {
table: "ui-table"
},
initSelector: ":jqmData(role='table')"
},
_create: function() {
var self = this;
self.refresh( true );
},
refresh: function (create) {
var self = this,
trs = this.element.find( "thead tr" );
if ( create ) {
this.element.addClass( this.options.classes.table );
}
// Expose headers and allHeaders properties on the widget
// headers references the THs within the first TR in the table
self.headers = this.element.find( "tr:eq(0)" ).children();
// allHeaders references headers, plus all THs in the thead, which may include several rows, or not
self.allHeaders = self.headers.add( trs.children() );
trs.each(function(){
var coltally = 0;
$( this ).children().each(function( i ){
var span = parseInt( $( this ).attr( "colspan" ), 10 ),
sel = ":nth-child(" + ( coltally + 1 ) + ")";
$( this )
.jqmData( "colstart", coltally + 1 );
if( span ){
for( var j = 0; j < span - 1; j++ ){
coltally++;
sel += ", :nth-child(" + ( coltally + 1 ) + ")";
}
}
if ( create === undefined ) {
$(this).jqmData("cells", "");
}
// Store "cells" data on header as a reference to all cells in the same column as this TH
$( this )
.jqmData( "cells", self.element.find( "tr" ).not( trs.eq(0) ).not( this ).children( sel ) );
coltally++;
});
});
// update table modes
if ( create === undefined ) {
this.element.trigger( 'refresh' );
}
}
});
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.table.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
$.mobile.table.prototype.options.mode = "columntoggle";
$.mobile.table.prototype.options.columnBtnTheme = null;
$.mobile.table.prototype.options.columnPopupTheme = null;
$.mobile.table.prototype.options.columnBtnText = "Columns...";
$.mobile.table.prototype.options.classes = $.extend(
$.mobile.table.prototype.options.classes,
{
popup: "ui-table-columntoggle-popup",
columnBtn: "ui-table-columntoggle-btn",
priorityPrefix: "ui-table-priority-",
columnToggleTable: "ui-table-columntoggle"
}
);
$.mobile.document.delegate( ":jqmData(role='table')", "tablecreate refresh", function( e ) {
var $table = $( this ),
self = $table.data( "mobile-table" ),
event = e.type,
o = self.options,
ns = $.mobile.ns,
id = ( $table.attr( "id" ) || o.classes.popup ) + "-popup", /* TODO BETTER FALLBACK ID HERE */
$menuButton,
$popup,
$menu,
$switchboard;
if ( o.mode !== "columntoggle" ) {
return;
}
if ( event !== "refresh" ) {
self.element.addClass( o.classes.columnToggleTable );
$menuButton = $( "<a href='#" + id + "' class='" + o.classes.columnBtn + "' data-" + ns + "rel='popup' data-" + ns + "mini='true'>" + o.columnBtnText + "</a>" ),
$popup = $( "<div data-" + ns + "role='popup' data-" + ns + "role='fieldcontain' class='" + o.classes.popup + "' id='" + id + "'></div>"),
$menu = $("<fieldset data-" + ns + "role='controlgroup'></fieldset>");
}
// create the hide/show toggles
self.headers.not( "td" ).each(function( i ) {
var priority = $( this ).jqmData( "priority" ),
$cells = $( this ).add( $( this ).jqmData( "cells" ) );
if ( priority ) {
$cells.addClass( o.classes.priorityPrefix + priority );
if ( event !== "refresh" ) {
$("<label><input type='checkbox' checked />" + $( this ).text() + "</label>" )
.appendTo( $menu )
.children( 0 )
.jqmData( "cells", $cells )
.checkboxradio({
theme: o.columnPopupTheme
});
} else {
$( '#' + id + ' fieldset div:eq(' + i +')').find('input').jqmData( 'cells', $cells );
}
}
});
if ( event !== "refresh" ) {
$menu.appendTo( $popup );
}
// bind change event listeners to inputs - TODO: move to a private method?
if ( $menu === undefined ) {
$switchboard = $('#' + id + ' fieldset');
} else {
$switchboard = $menu;
}
if ( event !== "refresh" ) {
$switchboard.on( "change", "input", function( e ){
if( this.checked ){
$( this ).jqmData( "cells" ).removeClass( "ui-table-cell-hidden" ).addClass( "ui-table-cell-visible" );
} else {
$( this ).jqmData( "cells" ).removeClass( "ui-table-cell-visible" ).addClass( "ui-table-cell-hidden" );
}
});
$menuButton
.insertBefore( $table )
.buttonMarkup({
theme: o.columnBtnTheme
});
$popup
.insertBefore( $table )
.popup();
}
// refresh method
self.update = function(){
$switchboard.find( "input" ).each( function(){
if (this.checked) {
this.checked = $( this ).jqmData( "cells" ).eq(0).css( "display" ) === "table-cell";
if (event === "refresh") {
$( this ).jqmData( "cells" ).addClass('ui-table-cell-visible');
}
} else {
$( this ).jqmData( "cells" ).addClass('ui-table-cell-hidden');
}
$( this ).checkboxradio( "refresh" );
});
};
$.mobile.window.on( "throttledresize", self.update );
self.update();
});
})( jQuery );
(function( $, undefined ) {
$.mobile.table.prototype.options.mode = "reflow";
$.mobile.table.prototype.options.classes = $.extend(
$.mobile.table.prototype.options.classes,
{
reflowTable: "ui-table-reflow",
cellLabels: "ui-table-cell-label"
}
);
$.mobile.document.delegate( ":jqmData(role='table')", "tablecreate refresh", function( e ) {
var $table = $( this ),
event = e.type,
self = $table.data( "mobile-table" ),
o = self.options;
// If it's not reflow mode, return here.
if( o.mode !== "reflow" ){
return;
}
if ( event !== "refresh" ) {
self.element.addClass( o.classes.reflowTable );
}
// get headers in reverse order so that top-level headers are appended last
var reverseHeaders = $( self.allHeaders.get().reverse() );
// create the hide/show toggles
reverseHeaders.each(function( i ){
var $cells = $( this ).jqmData( "cells" ),
colstart = $( this ).jqmData( "colstart" ),
hierarchyClass = $cells.not( this ).filter( "thead th" ).length && " ui-table-cell-label-top",
text = $(this).text();
if( text !== "" ){
if( hierarchyClass ){
var iteration = parseInt( $( this ).attr( "colspan" ), 10 ),
filter = "";
if( iteration ){
filter = "td:nth-child("+ iteration +"n + " + ( colstart ) +")";
}
$cells.filter( filter ).prepend( "<b class='" + o.classes.cellLabels + hierarchyClass + "'>" + text + "</b>" );
}
else {
$cells.prepend( "<b class='" + o.classes.cellLabels + "'>" + text + "</b>" );
}
}
});
});
})( jQuery );
(function( $, window ) {
$.mobile.iosorientationfixEnabled = true;
// This fix addresses an iOS bug, so return early if the UA claims it's something else.
var ua = navigator.userAgent;
if( !( /iPhone|iPad|iPod/.test( navigator.platform ) && /OS [1-5]_[0-9_]* like Mac OS X/i.test( ua ) && ua.indexOf( "AppleWebKit" ) > -1 ) ){
$.mobile.iosorientationfixEnabled = false;
return;
}
var zoom = $.mobile.zoom,
evt, x, y, z, aig;
function checkTilt( e ) {
evt = e.originalEvent;
aig = evt.accelerationIncludingGravity;
x = Math.abs( aig.x );
y = Math.abs( aig.y );
z = Math.abs( aig.z );
// If portrait orientation and in one of the danger zones
if ( !window.orientation && ( x > 7 || ( ( z > 6 && y < 8 || z < 8 && y > 6 ) && x > 5 ) ) ) {
if ( zoom.enabled ) {
zoom.disable();
}
} else if ( !zoom.enabled ) {
zoom.enable();
}
}
$.mobile.document.on( "mobileinit", function(){
if( $.mobile.iosorientationfixEnabled ){
$.mobile.window
.bind( "orientationchange.iosorientationfix", zoom.enable )
.bind( "devicemotion.iosorientationfix", checkTilt );
}
});
}( jQuery, this ));
(function( $, window, undefined ) {
var $html = $( "html" ),
$head = $( "head" ),
$window = $.mobile.window;
//remove initial build class (only present on first pageshow)
function hideRenderingClass() {
$html.removeClass( "ui-mobile-rendering" );
}
// trigger mobileinit event - useful hook for configuring $.mobile settings before they're used
$( window.document ).trigger( "mobileinit" );
// support conditions
// if device support condition(s) aren't met, leave things as they are -> a basic, usable experience,
// otherwise, proceed with the enhancements
if ( !$.mobile.gradeA() ) {
return;
}
// override ajaxEnabled on platforms that have known conflicts with hash history updates
// or generally work better browsing in regular http for full page refreshes (BB5, Opera Mini)
if ( $.mobile.ajaxBlacklist ) {
$.mobile.ajaxEnabled = false;
}
// Add mobile, initial load "rendering" classes to docEl
$html.addClass( "ui-mobile ui-mobile-rendering" );
// This is a fallback. If anything goes wrong (JS errors, etc), or events don't fire,
// this ensures the rendering class is removed after 5 seconds, so content is visible and accessible
setTimeout( hideRenderingClass, 5000 );
$.extend( $.mobile, {
// find and enhance the pages in the dom and transition to the first page.
initializePage: function() {
// find present pages
var path = $.mobile.path,
$pages = $( ":jqmData(role='page'), :jqmData(role='dialog')" ),
hash = path.stripHash( path.stripQueryParams(path.parseLocation().hash) ),
hashPage = document.getElementById( hash );
// if no pages are found, create one with body's inner html
if ( !$pages.length ) {
$pages = $( "body" ).wrapInner( "<div data-" + $.mobile.ns + "role='page'></div>" ).children( 0 );
}
// add dialogs, set data-url attrs
$pages.each(function() {
var $this = $( this );
// unless the data url is already set set it to the pathname
if ( !$this.jqmData( "url" ) ) {
$this.attr( "data-" + $.mobile.ns + "url", $this.attr( "id" ) || location.pathname + location.search );
}
});
// define first page in dom case one backs out to the directory root (not always the first page visited, but defined as fallback)
$.mobile.firstPage = $pages.first();
// define page container
$.mobile.pageContainer = $.mobile.firstPage.parent().addClass( "ui-mobile-viewport" );
// initialize navigation events now, after mobileinit has occurred and the page container
// has been created but before the rest of the library is alerted to that fact
$.mobile.navreadyDeferred.resolve();
// alert listeners that the pagecontainer has been determined for binding
// to events triggered on it
$window.trigger( "pagecontainercreate" );
// cue page loading message
$.mobile.showPageLoadingMsg();
//remove initial build class (only present on first pageshow)
hideRenderingClass();
// if hashchange listening is disabled, there's no hash deeplink,
// the hash is not valid (contains more than one # or does not start with #)
// or there is no page with that hash, change to the first page in the DOM
// Remember, however, that the hash can also be a path!
if ( ! ( $.mobile.hashListeningEnabled &&
$.mobile.path.isHashValid( location.hash ) &&
( $( hashPage ).is( ':jqmData(role="page")' ) ||
$.mobile.path.isPath( hash ) ||
hash === $.mobile.dialogHashKey ) ) ) {
// Store the initial destination
if ( $.mobile.path.isHashValid( location.hash ) ) {
$.mobile.urlHistory.initialDst = hash.replace( "#", "" );
}
// make sure to set initial popstate state if it exists
// so that navigation back to the initial page works properly
if( $.event.special.navigate.isPushStateEnabled() ) {
$.mobile.navigate.navigator.squash( path.parseLocation().href );
}
$.mobile.changePage( $.mobile.firstPage, {
transition: "none",
reverse: true,
changeHash: false,
fromHashChange: true
});
} else {
// trigger hashchange or navigate to squash and record the correct
// history entry for an initial hash path
if( !$.event.special.navigate.isPushStateEnabled() ) {
$window.trigger( "hashchange", [true] );
} else {
// TODO figure out how to simplify this interaction with the initial history entry
// at the bottom js/navigate/navigate.js
$.mobile.navigate.history.stack = [];
$.mobile.navigate( $.mobile.path.isPath( location.hash ) ? location.hash : location.href );
}
}
}
});
// check which scrollTop value should be used by scrolling to 1 immediately at domready
// then check what the scroll top is. Android will report 0... others 1
// note that this initial scroll won't hide the address bar. It's just for the check.
$(function() {
window.scrollTo( 0, 1 );
// if defaultHomeScroll hasn't been set yet, see if scrollTop is 1
// it should be 1 in most browsers, but android treats 1 as 0 (for hiding addr bar)
// so if it's 1, use 0 from now on
$.mobile.defaultHomeScroll = ( !$.support.scrollTop || $.mobile.window.scrollTop() === 1 ) ? 0 : 1;
//dom-ready inits
if ( $.mobile.autoInitializePage ) {
$.mobile.initializePage();
}
// window load event
// hide iOS browser chrome on load
$window.load( $.mobile.silentScroll );
if ( !$.support.cssPointerEvents ) {
// IE and Opera don't support CSS pointer-events: none that we use to disable link-based buttons
// by adding the 'ui-disabled' class to them. Using a JavaScript workaround for those browser.
// https://github.com/jquery/jquery-mobile/issues/3558
$.mobile.document.delegate( ".ui-disabled", "vclick",
function( e ) {
e.preventDefault();
e.stopImmediatePropagation();
}
);
}
});
}( jQuery, this ));
}));
|
app/javascript/flavours/glitch/features/ui/components/mute_modal.js | im-in-space/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import Toggle from 'react-toggle';
import Button from 'flavours/glitch/components/button';
import { closeModal } from 'flavours/glitch/actions/modal';
import { muteAccount } from 'flavours/glitch/actions/accounts';
import { toggleHideNotifications, changeMuteDuration } from 'flavours/glitch/actions/mutes';
const messages = defineMessages({
minutes: { id: 'intervals.full.minutes', defaultMessage: '{number, plural, one {# minute} other {# minutes}}' },
hours: { id: 'intervals.full.hours', defaultMessage: '{number, plural, one {# hour} other {# hours}}' },
days: { id: 'intervals.full.days', defaultMessage: '{number, plural, one {# day} other {# days}}' },
indefinite: { id: 'mute_modal.indefinite', defaultMessage: 'Indefinite' },
});
const mapStateToProps = state => {
return {
account: state.getIn(['mutes', 'new', 'account']),
notifications: state.getIn(['mutes', 'new', 'notifications']),
muteDuration: state.getIn(['mutes', 'new', 'duration']),
};
};
const mapDispatchToProps = dispatch => {
return {
onConfirm(account, notifications, muteDuration) {
dispatch(muteAccount(account.get('id'), notifications, muteDuration));
},
onClose() {
dispatch(closeModal());
},
onToggleNotifications() {
dispatch(toggleHideNotifications());
},
onChangeMuteDuration(e) {
dispatch(changeMuteDuration(e.target.value));
},
};
};
export default @connect(mapStateToProps, mapDispatchToProps)
@injectIntl
class MuteModal extends React.PureComponent {
static propTypes = {
account: PropTypes.object.isRequired,
notifications: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired,
onConfirm: PropTypes.func.isRequired,
onToggleNotifications: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
muteDuration: PropTypes.number.isRequired,
onChangeMuteDuration: PropTypes.func.isRequired,
};
componentDidMount() {
this.button.focus();
}
handleClick = () => {
this.props.onClose();
this.props.onConfirm(this.props.account, this.props.notifications, this.props.muteDuration);
}
handleCancel = () => {
this.props.onClose();
}
setRef = (c) => {
this.button = c;
}
toggleNotifications = () => {
this.props.onToggleNotifications();
}
changeMuteDuration = (e) => {
this.props.onChangeMuteDuration(e);
}
render () {
const { account, notifications, muteDuration, intl } = this.props;
return (
<div className='modal-root__modal mute-modal'>
<div className='mute-modal__container'>
<p>
<FormattedMessage
id='confirmations.mute.message'
defaultMessage='Are you sure you want to mute {name}?'
values={{ name: <strong>@{account.get('acct')}</strong> }}
/>
</p>
<p className='mute-modal__explanation'>
<FormattedMessage
id='confirmations.mute.explanation'
defaultMessage='This will hide posts from them and posts mentioning them, but it will still allow them to see your posts and follow you.'
/>
</p>
<div className='setting-toggle'>
<Toggle id='mute-modal__hide-notifications-checkbox' checked={notifications} onChange={this.toggleNotifications} />
<label className='setting-toggle__label' htmlFor='mute-modal__hide-notifications-checkbox'>
<FormattedMessage id='mute_modal.hide_notifications' defaultMessage='Hide notifications from this user?' />
</label>
</div>
<div>
<span><FormattedMessage id='mute_modal.duration' defaultMessage='Duration' />: </span>
{/* eslint-disable-next-line jsx-a11y/no-onchange */}
<select value={muteDuration} onChange={this.changeMuteDuration}>
<option value={0}>{intl.formatMessage(messages.indefinite)}</option>
<option value={300}>{intl.formatMessage(messages.minutes, { number: 5 })}</option>
<option value={1800}>{intl.formatMessage(messages.minutes, { number: 30 })}</option>
<option value={3600}>{intl.formatMessage(messages.hours, { number: 1 })}</option>
<option value={21600}>{intl.formatMessage(messages.hours, { number: 6 })}</option>
<option value={86400}>{intl.formatMessage(messages.days, { number: 1 })}</option>
<option value={259200}>{intl.formatMessage(messages.days, { number: 3 })}</option>
<option value={604800}>{intl.formatMessage(messages.days, { number: 7 })}</option>
</select>
</div>
</div>
<div className='mute-modal__action-bar'>
<Button onClick={this.handleCancel} className='mute-modal__cancel-button'>
<FormattedMessage id='confirmation_modal.cancel' defaultMessage='Cancel' />
</Button>
<Button onClick={this.handleClick} ref={this.setRef}>
<FormattedMessage id='confirmations.mute.confirm' defaultMessage='Mute' />
</Button>
</div>
</div>
);
}
}
|
apps/app/src/containers/User.js | argos-ci/argos | import React from 'react'
import gql from 'graphql-tag'
import { useAuthToken, useLogout } from './Auth'
import { useQuery } from './Apollo'
const UserContext = React.createContext()
const UserQuery = gql`
query User {
user {
id
email
name
login
privateSync
latestSynchronization {
id
jobStatus
}
installations {
id
latestSynchronization {
id
jobStatus
}
}
}
}
`
export function UserInitializer({ children }) {
const token = useAuthToken()
const logout = useLogout()
const { loading, data, refetch } = useQuery(UserQuery, { skip: !token })
// Remove token if outdated
React.useEffect(() => {
if (!loading && token && data.user === null) {
logout()
}
}, [loading, token, data, logout])
const user = token && !loading ? data.user : null
React.useEffect(() => {
if (user) {
window.gtag('set', { user_id: user.id })
} else {
window.gtag('set', { user_id: null })
}
}, [user])
const value = React.useMemo(() => ({ user, refetch }), [user, refetch])
if (loading && token) return null
return <UserContext.Provider value={value}>{children}</UserContext.Provider>
}
export function useUser() {
const { user } = React.useContext(UserContext)
return user
}
export function useRefetchUser() {
const { refetch } = React.useContext(UserContext)
return refetch
}
|
blueocean-material-icons/src/js/components/svg-icons/editor/border-outer.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const EditorBorderOuter = (props) => (
<SvgIcon {...props}>
<path d="M13 7h-2v2h2V7zm0 4h-2v2h2v-2zm4 0h-2v2h2v-2zM3 3v18h18V3H3zm16 16H5V5h14v14zm-6-4h-2v2h2v-2zm-4-4H7v2h2v-2z"/>
</SvgIcon>
);
EditorBorderOuter.displayName = 'EditorBorderOuter';
EditorBorderOuter.muiName = 'SvgIcon';
export default EditorBorderOuter;
|
app/components/shared/data.js | nypl-registry/browse | import React from 'react'
const Data = React.createClass({
componentDidMount () {
setInterval(function () { this.render() }.bind(this), 1000)
},
componentWillUpdate () {
return true
},
toggleApiList (event) {
this.refs.databox.style.height = '100px'
this.refs.databox.style.overflowY = 'scroll'
},
render () {
var hist = JSON.parse(JSON.stringify(window.apiHistory))
hist.reverse()
return (
<div className=''>
<div className='dataicon' alt='Click to show API DATA' onClick={this.toggleApiList}></div>
<div ref='databox' className='databox'>
API requests made:
<br/>
{hist.map((x, ind) => <code key={ind}><a href={x.url}>{x.desc}</a></code>)}
</div>
</div>
)
}
})
export default Data
|
ajax/libs/remoteStorage/0.13.0/remotestorage-nocache.js | honestree/cdnjs | /** remotestorage.js 0.13.0, http://remotestorage.io, MIT-licensed **/
/** FILE: lib/bluebird.js **/
/**
* bluebird build version 2.3.4
* Features enabled: core, nodeify
* Features disabled: race, call_get, generators, map, promisify, props, reduce, settle, some, progress, cancel, using, filter, any, each, timers
*/
/**
* @preserve Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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(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.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
var schedule = _dereq_("./schedule.js");
var Queue = _dereq_("./queue.js");
var errorObj = _dereq_("./util.js").errorObj;
var tryCatch1 = _dereq_("./util.js").tryCatch1;
var _process = typeof process !== "undefined" ? process : void 0;
function Async() {
this._isTickUsed = false;
this._schedule = schedule;
this._length = 0;
this._lateBuffer = new Queue(16);
this._functionBuffer = new Queue(65536);
var self = this;
this.consumeFunctionBuffer = function Async$consumeFunctionBuffer() {
self._consumeFunctionBuffer();
};
}
Async.prototype.haveItemsQueued = function Async$haveItemsQueued() {
return this._length > 0;
};
Async.prototype.invokeLater = function Async$invokeLater(fn, receiver, arg) {
if (_process !== void 0 &&
_process.domain != null &&
!fn.domain) {
fn = _process.domain.bind(fn);
}
this._lateBuffer.push(fn, receiver, arg);
this._queueTick();
};
Async.prototype.invoke = function Async$invoke(fn, receiver, arg) {
if (_process !== void 0 &&
_process.domain != null &&
!fn.domain) {
fn = _process.domain.bind(fn);
}
var functionBuffer = this._functionBuffer;
functionBuffer.push(fn, receiver, arg);
this._length = functionBuffer.length();
this._queueTick();
};
Async.prototype._consumeFunctionBuffer =
function Async$_consumeFunctionBuffer() {
var functionBuffer = this._functionBuffer;
while (functionBuffer.length() > 0) {
var fn = functionBuffer.shift();
var receiver = functionBuffer.shift();
var arg = functionBuffer.shift();
fn.call(receiver, arg);
}
this._reset();
this._consumeLateBuffer();
};
Async.prototype._consumeLateBuffer = function Async$_consumeLateBuffer() {
var buffer = this._lateBuffer;
while(buffer.length() > 0) {
var fn = buffer.shift();
var receiver = buffer.shift();
var arg = buffer.shift();
var res = tryCatch1(fn, receiver, arg);
if (res === errorObj) {
this._queueTick();
if (fn.domain != null) {
fn.domain.emit("error", res.e);
} else {
throw res.e;
}
}
}
};
Async.prototype._queueTick = function Async$_queue() {
if (!this._isTickUsed) {
this._schedule(this.consumeFunctionBuffer);
this._isTickUsed = true;
}
};
Async.prototype._reset = function Async$_reset() {
this._isTickUsed = false;
this._length = 0;
};
module.exports = new Async();
},{"./queue.js":15,"./schedule.js":16,"./util.js":19}],2:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
var Promise = _dereq_("./promise.js")();
module.exports = Promise;
},{"./promise.js":12}],3:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
module.exports = function() {
var inherits = _dereq_("./util.js").inherits;
var defineProperty = _dereq_("./es5.js").defineProperty;
var rignore = new RegExp(
"\\b(?:[a-zA-Z0-9.]+\\$_\\w+|" +
"tryCatch(?:1|2|3|4|Apply)|new \\w*PromiseArray|" +
"\\w*PromiseArray\\.\\w*PromiseArray|" +
"setTimeout|CatchFilter\\$_\\w+|makeNodePromisified|processImmediate|" +
"process._tickCallback|nextTick|Async\\$\\w+)\\b"
);
var rtraceline = null;
var formatStack = null;
function formatNonError(obj) {
var str;
if (typeof obj === "function") {
str = "[function " +
(obj.name || "anonymous") +
"]";
} else {
str = obj.toString();
var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
if (ruselessToString.test(str)) {
try {
var newStr = JSON.stringify(obj);
str = newStr;
}
catch(e) {
}
}
if (str.length === 0) {
str = "(empty array)";
}
}
return ("(<" + snip(str) + ">, no stack trace)");
}
function snip(str) {
var maxChars = 41;
if (str.length < maxChars) {
return str;
}
return str.substr(0, maxChars - 3) + "...";
}
function CapturedTrace(ignoreUntil, isTopLevel) {
this.captureStackTrace(CapturedTrace, isTopLevel);
}
inherits(CapturedTrace, Error);
CapturedTrace.prototype.captureStackTrace =
function CapturedTrace$captureStackTrace(ignoreUntil, isTopLevel) {
captureStackTrace(this, ignoreUntil, isTopLevel);
};
CapturedTrace.possiblyUnhandledRejection =
function CapturedTrace$PossiblyUnhandledRejection(reason) {
if (typeof console === "object") {
var message;
if (typeof reason === "object" || typeof reason === "function") {
var stack = reason.stack;
message = "Possibly unhandled " + formatStack(stack, reason);
} else {
message = "Possibly unhandled " + String(reason);
}
if (typeof console.error === "function" ||
typeof console.error === "object") {
console.error(message);
} else if (typeof console.log === "function" ||
typeof console.log === "object") {
console.log(message);
}
}
};
CapturedTrace.combine = function CapturedTrace$Combine(current, prev) {
var curLast = current.length - 1;
for (var i = prev.length - 1; i >= 0; --i) {
var line = prev[i];
if (current[curLast] === line) {
current.pop();
curLast--;
} else {
break;
}
}
current.push("From previous event:");
var lines = current.concat(prev);
var ret = [];
for (var i = 0, len = lines.length; i < len; ++i) {
if (((rignore.test(lines[i]) && rtraceline.test(lines[i])) ||
(i > 0 && !rtraceline.test(lines[i])) &&
lines[i] !== "From previous event:")
) {
continue;
}
ret.push(lines[i]);
}
return ret;
};
CapturedTrace.protectErrorMessageNewlines = function(stack) {
for (var i = 0; i < stack.length; ++i) {
if (rtraceline.test(stack[i])) {
break;
}
}
if (i <= 1) return;
var errorMessageLines = [];
for (var j = 0; j < i; ++j) {
errorMessageLines.push(stack.shift());
}
stack.unshift(errorMessageLines.join("\u0002\u0000\u0001"));
};
CapturedTrace.isSupported = function CapturedTrace$IsSupported() {
return typeof captureStackTrace === "function";
};
var captureStackTrace = (function stackDetection() {
if (typeof Error.stackTraceLimit === "number" &&
typeof Error.captureStackTrace === "function") {
rtraceline = /^\s*at\s*/;
formatStack = function(stack, error) {
if (typeof stack === "string") return stack;
if (error.name !== void 0 &&
error.message !== void 0) {
return error.name + ". " + error.message;
}
return formatNonError(error);
};
var captureStackTrace = Error.captureStackTrace;
return function CapturedTrace$_captureStackTrace(
receiver, ignoreUntil) {
captureStackTrace(receiver, ignoreUntil);
};
}
var err = new Error();
if (typeof err.stack === "string" &&
typeof "".startsWith === "function" &&
(err.stack.startsWith("stackDetection@")) &&
stackDetection.name === "stackDetection") {
defineProperty(Error, "stackTraceLimit", {
writable: true,
enumerable: false,
configurable: false,
value: 25
});
rtraceline = /@/;
var rline = /[@\n]/;
formatStack = function(stack, error) {
if (typeof stack === "string") {
return (error.name + ". " + error.message + "\n" + stack);
}
if (error.name !== void 0 &&
error.message !== void 0) {
return error.name + ". " + error.message;
}
return formatNonError(error);
};
return function captureStackTrace(o) {
var stack = new Error().stack;
var split = stack.split(rline);
var len = split.length;
var ret = "";
for (var i = 0; i < len; i += 2) {
ret += split[i];
ret += "@";
ret += split[i + 1];
ret += "\n";
}
o.stack = ret;
};
} else {
formatStack = function(stack, error) {
if (typeof stack === "string") return stack;
if ((typeof error === "object" ||
typeof error === "function") &&
error.name !== void 0 &&
error.message !== void 0) {
return error.name + ". " + error.message;
}
return formatNonError(error);
};
return null;
}
})();
return CapturedTrace;
};
},{"./es5.js":8,"./util.js":19}],4:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
module.exports = function(NEXT_FILTER) {
var util = _dereq_("./util.js");
var errors = _dereq_("./errors.js");
var tryCatch1 = util.tryCatch1;
var errorObj = util.errorObj;
var keys = _dereq_("./es5.js").keys;
var TypeError = errors.TypeError;
function CatchFilter(instances, callback, promise) {
this._instances = instances;
this._callback = callback;
this._promise = promise;
}
function CatchFilter$_safePredicate(predicate, e) {
var safeObject = {};
var retfilter = tryCatch1(predicate, safeObject, e);
if (retfilter === errorObj) return retfilter;
var safeKeys = keys(safeObject);
if (safeKeys.length) {
errorObj.e = new TypeError(
"Catch filter must inherit from Error "
+ "or be a simple predicate function");
return errorObj;
}
return retfilter;
}
CatchFilter.prototype.doFilter = function CatchFilter$_doFilter(e) {
var cb = this._callback;
var promise = this._promise;
var boundTo = promise._boundTo;
for (var i = 0, len = this._instances.length; i < len; ++i) {
var item = this._instances[i];
var itemIsErrorType = item === Error ||
(item != null && item.prototype instanceof Error);
if (itemIsErrorType && e instanceof item) {
var ret = tryCatch1(cb, boundTo, e);
if (ret === errorObj) {
NEXT_FILTER.e = ret.e;
return NEXT_FILTER;
}
return ret;
} else if (typeof item === "function" && !itemIsErrorType) {
var shouldHandle = CatchFilter$_safePredicate(item, e);
if (shouldHandle === errorObj) {
var trace = errors.canAttach(errorObj.e)
? errorObj.e
: new Error(errorObj.e + "");
this._promise._attachExtraTrace(trace);
e = errorObj.e;
break;
} else if (shouldHandle) {
var ret = tryCatch1(cb, boundTo, e);
if (ret === errorObj) {
NEXT_FILTER.e = ret.e;
return NEXT_FILTER;
}
return ret;
}
}
}
NEXT_FILTER.e = e;
return NEXT_FILTER;
};
return CatchFilter;
};
},{"./errors.js":6,"./es5.js":8,"./util.js":19}],5:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
var util = _dereq_("./util.js");
var isPrimitive = util.isPrimitive;
var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver;
module.exports = function(Promise) {
var returner = function Promise$_returner() {
return this;
};
var thrower = function Promise$_thrower() {
throw this;
};
var wrapper = function Promise$_wrapper(value, action) {
if (action === 1) {
return function Promise$_thrower() {
throw value;
};
} else if (action === 2) {
return function Promise$_returner() {
return value;
};
}
};
Promise.prototype["return"] =
Promise.prototype.thenReturn =
function Promise$thenReturn(value) {
if (wrapsPrimitiveReceiver && isPrimitive(value)) {
return this._then(
wrapper(value, 2),
void 0,
void 0,
void 0,
void 0
);
}
return this._then(returner, void 0, void 0, value, void 0);
};
Promise.prototype["throw"] =
Promise.prototype.thenThrow =
function Promise$thenThrow(reason) {
if (wrapsPrimitiveReceiver && isPrimitive(reason)) {
return this._then(
wrapper(reason, 1),
void 0,
void 0,
void 0,
void 0
);
}
return this._then(thrower, void 0, void 0, reason, void 0);
};
};
},{"./util.js":19}],6:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
var Objectfreeze = _dereq_("./es5.js").freeze;
var util = _dereq_("./util.js");
var inherits = util.inherits;
var notEnumerableProp = util.notEnumerableProp;
function markAsOriginatingFromRejection(e) {
try {
notEnumerableProp(e, "isOperational", true);
}
catch(ignore) {}
}
function originatesFromRejection(e) {
if (e == null) return false;
return ((e instanceof OperationalError) ||
e["isOperational"] === true);
}
function isError(obj) {
return obj instanceof Error;
}
function canAttach(obj) {
return isError(obj);
}
function subError(nameProperty, defaultMessage) {
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
this.message = typeof message === "string" ? message : defaultMessage;
this.name = nameProperty;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
inherits(SubError, Error);
return SubError;
}
var _TypeError, _RangeError;
var CancellationError = subError("CancellationError", "cancellation error");
var TimeoutError = subError("TimeoutError", "timeout error");
var AggregateError = subError("AggregateError", "aggregate error");
try {
_TypeError = TypeError;
_RangeError = RangeError;
} catch(e) {
_TypeError = subError("TypeError", "type error");
_RangeError = subError("RangeError", "range error");
}
var methods = ("join pop push shift unshift slice filter forEach some " +
"every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
for (var i = 0; i < methods.length; ++i) {
if (typeof Array.prototype[methods[i]] === "function") {
AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
}
}
AggregateError.prototype.length = 0;
AggregateError.prototype["isOperational"] = true;
var level = 0;
AggregateError.prototype.toString = function() {
var indent = Array(level * 4 + 1).join(" ");
var ret = "\n" + indent + "AggregateError of:" + "\n";
level++;
indent = Array(level * 4 + 1).join(" ");
for (var i = 0; i < this.length; ++i) {
var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
var lines = str.split("\n");
for (var j = 0; j < lines.length; ++j) {
lines[j] = indent + lines[j];
}
str = lines.join("\n");
ret += str + "\n";
}
level--;
return ret;
};
function OperationalError(message) {
this.name = "OperationalError";
this.message = message;
this.cause = message;
this["isOperational"] = true;
if (message instanceof Error) {
this.message = message.message;
this.stack = message.stack;
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
inherits(OperationalError, Error);
var key = "__BluebirdErrorTypes__";
var errorTypes = Error[key];
if (!errorTypes) {
errorTypes = Objectfreeze({
CancellationError: CancellationError,
TimeoutError: TimeoutError,
OperationalError: OperationalError,
RejectionError: OperationalError,
AggregateError: AggregateError
});
notEnumerableProp(Error, key, errorTypes);
}
module.exports = {
Error: Error,
TypeError: _TypeError,
RangeError: _RangeError,
CancellationError: errorTypes.CancellationError,
OperationalError: errorTypes.OperationalError,
TimeoutError: errorTypes.TimeoutError,
AggregateError: errorTypes.AggregateError,
originatesFromRejection: originatesFromRejection,
markAsOriginatingFromRejection: markAsOriginatingFromRejection,
canAttach: canAttach
};
},{"./es5.js":8,"./util.js":19}],7:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
module.exports = function(Promise) {
var TypeError = _dereq_('./errors.js').TypeError;
function apiRejection(msg) {
var error = new TypeError(msg);
var ret = Promise.rejected(error);
var parent = ret._peekContext();
if (parent != null) {
parent._attachExtraTrace(error);
}
return ret;
}
return apiRejection;
};
},{"./errors.js":6}],8:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
var isES5 = (function(){
"use strict";
return this === void 0;
})();
if (isES5) {
module.exports = {
freeze: Object.freeze,
defineProperty: Object.defineProperty,
keys: Object.keys,
getPrototypeOf: Object.getPrototypeOf,
isArray: Array.isArray,
isES5: isES5
};
} else {
var has = {}.hasOwnProperty;
var str = {}.toString;
var proto = {}.constructor.prototype;
var ObjectKeys = function ObjectKeys(o) {
var ret = [];
for (var key in o) {
if (has.call(o, key)) {
ret.push(key);
}
}
return ret;
}
var ObjectDefineProperty = function ObjectDefineProperty(o, key, desc) {
o[key] = desc.value;
return o;
}
var ObjectFreeze = function ObjectFreeze(obj) {
return obj;
}
var ObjectGetPrototypeOf = function ObjectGetPrototypeOf(obj) {
try {
return Object(obj).constructor.prototype;
}
catch (e) {
return proto;
}
}
var ArrayIsArray = function ArrayIsArray(obj) {
try {
return str.call(obj) === "[object Array]";
}
catch(e) {
return false;
}
}
module.exports = {
isArray: ArrayIsArray,
keys: ObjectKeys,
defineProperty: ObjectDefineProperty,
freeze: ObjectFreeze,
getPrototypeOf: ObjectGetPrototypeOf,
isES5: isES5
};
}
},{}],9:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
module.exports = function(Promise, NEXT_FILTER, cast) {
var util = _dereq_("./util.js");
var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver;
var isPrimitive = util.isPrimitive;
var thrower = util.thrower;
function returnThis() {
return this;
}
function throwThis() {
throw this;
}
function return$(r) {
return function Promise$_returner() {
return r;
};
}
function throw$(r) {
return function Promise$_thrower() {
throw r;
};
}
function promisedFinally(ret, reasonOrValue, isFulfilled) {
var then;
if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) {
then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue);
} else {
then = isFulfilled ? returnThis : throwThis;
}
return ret._then(then, thrower, void 0, reasonOrValue, void 0);
}
function finallyHandler(reasonOrValue) {
var promise = this.promise;
var handler = this.handler;
var ret = promise._isBound()
? handler.call(promise._boundTo)
: handler();
if (ret !== void 0) {
var maybePromise = cast(ret, void 0);
if (maybePromise instanceof Promise) {
return promisedFinally(maybePromise, reasonOrValue,
promise.isFulfilled());
}
}
if (promise.isRejected()) {
NEXT_FILTER.e = reasonOrValue;
return NEXT_FILTER;
} else {
return reasonOrValue;
}
}
function tapHandler(value) {
var promise = this.promise;
var handler = this.handler;
var ret = promise._isBound()
? handler.call(promise._boundTo, value)
: handler(value);
if (ret !== void 0) {
var maybePromise = cast(ret, void 0);
if (maybePromise instanceof Promise) {
return promisedFinally(maybePromise, value, true);
}
}
return value;
}
Promise.prototype._passThroughHandler =
function Promise$_passThroughHandler(handler, isFinally) {
if (typeof handler !== "function") return this.then();
var promiseAndHandler = {
promise: this,
handler: handler
};
return this._then(
isFinally ? finallyHandler : tapHandler,
isFinally ? finallyHandler : void 0, void 0,
promiseAndHandler, void 0);
};
Promise.prototype.lastly =
Promise.prototype["finally"] = function Promise$finally(handler) {
return this._passThroughHandler(handler, true);
};
Promise.prototype.tap = function Promise$tap(handler) {
return this._passThroughHandler(handler, false);
};
};
},{"./util.js":19}],10:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
module.exports =
function(Promise, PromiseArray, cast, INTERNAL) {
var util = _dereq_("./util.js");
var canEvaluate = util.canEvaluate;
var tryCatch1 = util.tryCatch1;
var errorObj = util.errorObj;
if (canEvaluate) {
var thenCallback = function(i) {
return new Function("value", "holder", " \n\
'use strict'; \n\
holder.pIndex = value; \n\
holder.checkFulfillment(this); \n\
".replace(/Index/g, i));
};
var caller = function(count) {
var values = [];
for (var i = 1; i <= count; ++i) values.push("holder.p" + i);
return new Function("holder", " \n\
'use strict'; \n\
var callback = holder.fn; \n\
return callback(values); \n\
".replace(/values/g, values.join(", ")));
};
var thenCallbacks = [];
var callers = [void 0];
for (var i = 1; i <= 5; ++i) {
thenCallbacks.push(thenCallback(i));
callers.push(caller(i));
}
var Holder = function(total, fn) {
this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null;
this.fn = fn;
this.total = total;
this.now = 0;
};
Holder.prototype.callers = callers;
Holder.prototype.checkFulfillment = function(promise) {
var now = this.now;
now++;
var total = this.total;
if (now >= total) {
var handler = this.callers[total];
var ret = tryCatch1(handler, void 0, this);
if (ret === errorObj) {
promise._rejectUnchecked(ret.e);
} else if (!promise._tryFollow(ret)) {
promise._fulfillUnchecked(ret);
}
} else {
this.now = now;
}
};
}
Promise.join = function Promise$Join() {
var last = arguments.length - 1;
var fn;
if (last > 0 && typeof arguments[last] === "function") {
fn = arguments[last];
if (last < 6 && canEvaluate) {
var ret = new Promise(INTERNAL);
ret._setTrace(void 0);
var holder = new Holder(last, fn);
var reject = ret._reject;
var callbacks = thenCallbacks;
for (var i = 0; i < last; ++i) {
var maybePromise = cast(arguments[i], void 0);
if (maybePromise instanceof Promise) {
if (maybePromise.isPending()) {
maybePromise._then(callbacks[i], reject,
void 0, ret, holder);
} else if (maybePromise.isFulfilled()) {
callbacks[i].call(ret,
maybePromise._settledValue, holder);
} else {
ret._reject(maybePromise._settledValue);
maybePromise._unsetRejectionIsUnhandled();
}
} else {
callbacks[i].call(ret, maybePromise, holder);
}
}
return ret;
}
}
var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}
var ret = new PromiseArray(args).promise();
return fn !== void 0 ? ret.spread(fn) : ret;
};
};
},{"./util.js":19}],11:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
module.exports = function(Promise) {
var util = _dereq_("./util.js");
var async = _dereq_("./async.js");
var tryCatch2 = util.tryCatch2;
var tryCatch1 = util.tryCatch1;
var errorObj = util.errorObj;
function thrower(r) {
throw r;
}
function Promise$_spreadAdapter(val, receiver) {
if (!util.isArray(val)) return Promise$_successAdapter(val, receiver);
var ret = util.tryCatchApply(this, [null].concat(val), receiver);
if (ret === errorObj) {
async.invokeLater(thrower, void 0, ret.e);
}
}
function Promise$_successAdapter(val, receiver) {
var nodeback = this;
var ret = val === void 0
? tryCatch1(nodeback, receiver, null)
: tryCatch2(nodeback, receiver, null, val);
if (ret === errorObj) {
async.invokeLater(thrower, void 0, ret.e);
}
}
function Promise$_errorAdapter(reason, receiver) {
var nodeback = this;
var ret = tryCatch1(nodeback, receiver, reason);
if (ret === errorObj) {
async.invokeLater(thrower, void 0, ret.e);
}
}
Promise.prototype.nodeify = function Promise$nodeify(nodeback, options) {
if (typeof nodeback == "function") {
var adapter = Promise$_successAdapter;
if (options !== void 0 && Object(options).spread) {
adapter = Promise$_spreadAdapter;
}
this._then(
adapter,
Promise$_errorAdapter,
void 0,
nodeback,
this._boundTo
);
}
return this;
};
};
},{"./async.js":1,"./util.js":19}],12:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
var old;
if (typeof Promise !== "undefined") old = Promise;
function noConflict(bluebird) {
try { if (Promise === bluebird) Promise = old; }
catch (e) {}
return bluebird;
}
module.exports = function() {
var util = _dereq_("./util.js");
var async = _dereq_("./async.js");
var errors = _dereq_("./errors.js");
var INTERNAL = function(){};
var APPLY = {};
var NEXT_FILTER = {e: null};
var cast = _dereq_("./thenables.js")(Promise, INTERNAL);
var PromiseArray = _dereq_("./promise_array.js")(Promise, INTERNAL, cast);
var CapturedTrace = _dereq_("./captured_trace.js")();
var CatchFilter = _dereq_("./catch_filter.js")(NEXT_FILTER);
var PromiseResolver = _dereq_("./promise_resolver.js");
var isArray = util.isArray;
var errorObj = util.errorObj;
var tryCatch1 = util.tryCatch1;
var tryCatch2 = util.tryCatch2;
var tryCatchApply = util.tryCatchApply;
var RangeError = errors.RangeError;
var TypeError = errors.TypeError;
var CancellationError = errors.CancellationError;
var TimeoutError = errors.TimeoutError;
var OperationalError = errors.OperationalError;
var originatesFromRejection = errors.originatesFromRejection;
var markAsOriginatingFromRejection = errors.markAsOriginatingFromRejection;
var canAttach = errors.canAttach;
var thrower = util.thrower;
var apiRejection = _dereq_("./errors_api_rejection")(Promise);
var makeSelfResolutionError = function Promise$_makeSelfResolutionError() {
return new TypeError("circular promise resolution chain");
};
function Promise(resolver) {
if (typeof resolver !== "function") {
throw new TypeError("the promise constructor requires a resolver function");
}
if (this.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly");
}
this._bitField = 0;
this._fulfillmentHandler0 = void 0;
this._rejectionHandler0 = void 0;
this._promise0 = void 0;
this._receiver0 = void 0;
this._settledValue = void 0;
this._boundTo = void 0;
if (resolver !== INTERNAL) this._resolveFromResolver(resolver);
}
function returnFirstElement(elements) {
return elements[0];
}
Promise.prototype.bind = function Promise$bind(thisArg) {
var maybePromise = cast(thisArg, void 0);
var ret = new Promise(INTERNAL);
if (maybePromise instanceof Promise) {
var binder = maybePromise.then(function(thisArg) {
ret._setBoundTo(thisArg);
});
var p = Promise.all([this, binder]).then(returnFirstElement);
ret._follow(p);
} else {
ret._follow(this);
ret._setBoundTo(thisArg);
}
ret._propagateFrom(this, 2 | 1);
return ret;
};
Promise.prototype.toString = function Promise$toString() {
return "[object Promise]";
};
Promise.prototype.caught = Promise.prototype["catch"] =
function Promise$catch(fn) {
var len = arguments.length;
if (len > 1) {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (typeof item === "function") {
catchInstances[j++] = item;
} else {
var catchFilterTypeError =
new TypeError(
"A catch filter must be an error constructor "
+ "or a filter function");
this._attachExtraTrace(catchFilterTypeError);
return Promise.reject(catchFilterTypeError);
}
}
catchInstances.length = j;
fn = arguments[i];
this._resetTrace();
var catchFilter = new CatchFilter(catchInstances, fn, this);
return this._then(void 0, catchFilter.doFilter, void 0,
catchFilter, void 0);
}
return this._then(void 0, fn, void 0, void 0, void 0);
};
Promise.prototype.then =
function Promise$then(didFulfill, didReject, didProgress) {
return this._then(didFulfill, didReject, didProgress,
void 0, void 0);
};
Promise.prototype.done =
function Promise$done(didFulfill, didReject, didProgress) {
var promise = this._then(didFulfill, didReject, didProgress,
void 0, void 0);
promise._setIsFinal();
};
Promise.prototype.spread = function Promise$spread(didFulfill, didReject) {
return this._then(didFulfill, didReject, void 0,
APPLY, void 0);
};
Promise.prototype.isCancellable = function Promise$isCancellable() {
return !this.isResolved() &&
this._cancellable();
};
Promise.prototype.toJSON = function Promise$toJSON() {
var ret = {
isFulfilled: false,
isRejected: false,
fulfillmentValue: void 0,
rejectionReason: void 0
};
if (this.isFulfilled()) {
ret.fulfillmentValue = this._settledValue;
ret.isFulfilled = true;
} else if (this.isRejected()) {
ret.rejectionReason = this._settledValue;
ret.isRejected = true;
}
return ret;
};
Promise.prototype.all = function Promise$all() {
return new PromiseArray(this).promise();
};
Promise.is = function Promise$Is(val) {
return val instanceof Promise;
};
Promise.all = function Promise$All(promises) {
return new PromiseArray(promises).promise();
};
Promise.prototype.error = function Promise$_error(fn) {
return this.caught(originatesFromRejection, fn);
};
Promise.prototype._resolveFromSyncValue =
function Promise$_resolveFromSyncValue(value) {
if (value === errorObj) {
this._cleanValues();
this._setRejected();
this._settledValue = value.e;
this._ensurePossibleRejectionHandled();
} else {
var maybePromise = cast(value, void 0);
if (maybePromise instanceof Promise) {
this._follow(maybePromise);
} else {
this._cleanValues();
this._setFulfilled();
this._settledValue = value;
}
}
};
Promise.method = function Promise$_Method(fn) {
if (typeof fn !== "function") {
throw new TypeError("fn must be a function");
}
return function Promise$_method() {
var value;
switch(arguments.length) {
case 0: value = tryCatch1(fn, this, void 0); break;
case 1: value = tryCatch1(fn, this, arguments[0]); break;
case 2: value = tryCatch2(fn, this, arguments[0], arguments[1]); break;
default:
var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}
value = tryCatchApply(fn, args, this); break;
}
var ret = new Promise(INTERNAL);
ret._setTrace(void 0);
ret._resolveFromSyncValue(value);
return ret;
};
};
Promise.attempt = Promise["try"] = function Promise$_Try(fn, args, ctx) {
if (typeof fn !== "function") {
return apiRejection("fn must be a function");
}
var value = isArray(args)
? tryCatchApply(fn, args, ctx)
: tryCatch1(fn, ctx, args);
var ret = new Promise(INTERNAL);
ret._setTrace(void 0);
ret._resolveFromSyncValue(value);
return ret;
};
Promise.defer = Promise.pending = function Promise$Defer() {
var promise = new Promise(INTERNAL);
promise._setTrace(void 0);
return new PromiseResolver(promise);
};
Promise.bind = function Promise$Bind(thisArg) {
var maybePromise = cast(thisArg, void 0);
var ret = new Promise(INTERNAL);
ret._setTrace(void 0);
if (maybePromise instanceof Promise) {
var p = maybePromise.then(function(thisArg) {
ret._setBoundTo(thisArg);
});
ret._follow(p);
} else {
ret._setBoundTo(thisArg);
ret._setFulfilled();
}
return ret;
};
Promise.cast = function Promise$_Cast(obj) {
var ret = cast(obj, void 0);
if (!(ret instanceof Promise)) {
var val = ret;
ret = new Promise(INTERNAL);
ret._setTrace(void 0);
ret._setFulfilled();
ret._cleanValues();
ret._settledValue = val;
}
return ret;
};
Promise.resolve = Promise.fulfilled = Promise.cast;
Promise.reject = Promise.rejected = function Promise$Reject(reason) {
var ret = new Promise(INTERNAL);
ret._setTrace(void 0);
markAsOriginatingFromRejection(reason);
ret._cleanValues();
ret._setRejected();
ret._settledValue = reason;
if (!canAttach(reason)) {
var trace = new Error(reason + "");
ret._setCarriedStackTrace(trace);
}
ret._ensurePossibleRejectionHandled();
return ret;
};
Promise.onPossiblyUnhandledRejection =
function Promise$OnPossiblyUnhandledRejection(fn) {
CapturedTrace.possiblyUnhandledRejection = typeof fn === "function"
? fn : void 0;
};
var unhandledRejectionHandled;
Promise.onUnhandledRejectionHandled =
function Promise$onUnhandledRejectionHandled(fn) {
unhandledRejectionHandled = typeof fn === "function" ? fn : void 0;
};
var debugging = false || !!(
typeof process !== "undefined" &&
typeof process.execPath === "string" &&
typeof process.env === "object" &&
(process.env["BLUEBIRD_DEBUG"] ||
process.env["NODE_ENV"] === "development")
);
Promise.longStackTraces = function Promise$LongStackTraces() {
if (async.haveItemsQueued() &&
debugging === false
) {
throw new Error("cannot enable long stack traces after promises have been created");
}
debugging = CapturedTrace.isSupported();
};
Promise.hasLongStackTraces = function Promise$HasLongStackTraces() {
return debugging && CapturedTrace.isSupported();
};
Promise.prototype._then =
function Promise$_then(
didFulfill,
didReject,
didProgress,
receiver,
internalData
) {
var haveInternalData = internalData !== void 0;
var ret = haveInternalData ? internalData : new Promise(INTERNAL);
if (!haveInternalData) {
if (debugging) {
var haveSameContext = this._peekContext() === this._traceParent;
ret._traceParent = haveSameContext ? this._traceParent : this;
}
ret._propagateFrom(this, 7);
}
var callbackIndex =
this._addCallbacks(didFulfill, didReject, didProgress, ret, receiver);
if (this.isResolved()) {
async.invoke(this._queueSettleAt, this, callbackIndex);
}
return ret;
};
Promise.prototype._length = function Promise$_length() {
return this._bitField & 262143;
};
Promise.prototype._isFollowingOrFulfilledOrRejected =
function Promise$_isFollowingOrFulfilledOrRejected() {
return (this._bitField & 939524096) > 0;
};
Promise.prototype._isFollowing = function Promise$_isFollowing() {
return (this._bitField & 536870912) === 536870912;
};
Promise.prototype._setLength = function Promise$_setLength(len) {
this._bitField = (this._bitField & -262144) |
(len & 262143);
};
Promise.prototype._setFulfilled = function Promise$_setFulfilled() {
this._bitField = this._bitField | 268435456;
};
Promise.prototype._setRejected = function Promise$_setRejected() {
this._bitField = this._bitField | 134217728;
};
Promise.prototype._setFollowing = function Promise$_setFollowing() {
this._bitField = this._bitField | 536870912;
};
Promise.prototype._setIsFinal = function Promise$_setIsFinal() {
this._bitField = this._bitField | 33554432;
};
Promise.prototype._isFinal = function Promise$_isFinal() {
return (this._bitField & 33554432) > 0;
};
Promise.prototype._cancellable = function Promise$_cancellable() {
return (this._bitField & 67108864) > 0;
};
Promise.prototype._setCancellable = function Promise$_setCancellable() {
this._bitField = this._bitField | 67108864;
};
Promise.prototype._unsetCancellable = function Promise$_unsetCancellable() {
this._bitField = this._bitField & (~67108864);
};
Promise.prototype._setRejectionIsUnhandled =
function Promise$_setRejectionIsUnhandled() {
this._bitField = this._bitField | 2097152;
};
Promise.prototype._unsetRejectionIsUnhandled =
function Promise$_unsetRejectionIsUnhandled() {
this._bitField = this._bitField & (~2097152);
if (this._isUnhandledRejectionNotified()) {
this._unsetUnhandledRejectionIsNotified();
this._notifyUnhandledRejectionIsHandled();
}
};
Promise.prototype._isRejectionUnhandled =
function Promise$_isRejectionUnhandled() {
return (this._bitField & 2097152) > 0;
};
Promise.prototype._setUnhandledRejectionIsNotified =
function Promise$_setUnhandledRejectionIsNotified() {
this._bitField = this._bitField | 524288;
};
Promise.prototype._unsetUnhandledRejectionIsNotified =
function Promise$_unsetUnhandledRejectionIsNotified() {
this._bitField = this._bitField & (~524288);
};
Promise.prototype._isUnhandledRejectionNotified =
function Promise$_isUnhandledRejectionNotified() {
return (this._bitField & 524288) > 0;
};
Promise.prototype._setCarriedStackTrace =
function Promise$_setCarriedStackTrace(capturedTrace) {
this._bitField = this._bitField | 1048576;
this._fulfillmentHandler0 = capturedTrace;
};
Promise.prototype._unsetCarriedStackTrace =
function Promise$_unsetCarriedStackTrace() {
this._bitField = this._bitField & (~1048576);
this._fulfillmentHandler0 = void 0;
};
Promise.prototype._isCarryingStackTrace =
function Promise$_isCarryingStackTrace() {
return (this._bitField & 1048576) > 0;
};
Promise.prototype._getCarriedStackTrace =
function Promise$_getCarriedStackTrace() {
return this._isCarryingStackTrace()
? this._fulfillmentHandler0
: void 0;
};
Promise.prototype._receiverAt = function Promise$_receiverAt(index) {
var ret = index === 0
? this._receiver0
: this[(index << 2) + index - 5 + 4];
if (this._isBound() && ret === void 0) {
return this._boundTo;
}
return ret;
};
Promise.prototype._promiseAt = function Promise$_promiseAt(index) {
return index === 0
? this._promise0
: this[(index << 2) + index - 5 + 3];
};
Promise.prototype._fulfillmentHandlerAt =
function Promise$_fulfillmentHandlerAt(index) {
return index === 0
? this._fulfillmentHandler0
: this[(index << 2) + index - 5 + 0];
};
Promise.prototype._rejectionHandlerAt =
function Promise$_rejectionHandlerAt(index) {
return index === 0
? this._rejectionHandler0
: this[(index << 2) + index - 5 + 1];
};
Promise.prototype._addCallbacks = function Promise$_addCallbacks(
fulfill,
reject,
progress,
promise,
receiver
) {
var index = this._length();
if (index >= 262143 - 5) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promise;
if (receiver !== void 0) this._receiver0 = receiver;
if (typeof fulfill === "function" && !this._isCarryingStackTrace())
this._fulfillmentHandler0 = fulfill;
if (typeof reject === "function") this._rejectionHandler0 = reject;
if (typeof progress === "function") this._progressHandler0 = progress;
} else {
var base = (index << 2) + index - 5;
this[base + 3] = promise;
this[base + 4] = receiver;
this[base + 0] = typeof fulfill === "function"
? fulfill : void 0;
this[base + 1] = typeof reject === "function"
? reject : void 0;
this[base + 2] = typeof progress === "function"
? progress : void 0;
}
this._setLength(index + 1);
return index;
};
Promise.prototype._setProxyHandlers =
function Promise$_setProxyHandlers(receiver, promiseSlotValue) {
var index = this._length();
if (index >= 262143 - 5) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promiseSlotValue;
this._receiver0 = receiver;
} else {
var base = (index << 2) + index - 5;
this[base + 3] = promiseSlotValue;
this[base + 4] = receiver;
this[base + 0] =
this[base + 1] =
this[base + 2] = void 0;
}
this._setLength(index + 1);
};
Promise.prototype._proxyPromiseArray =
function Promise$_proxyPromiseArray(promiseArray, index) {
this._setProxyHandlers(promiseArray, index);
};
Promise.prototype._proxyPromise = function Promise$_proxyPromise(promise) {
promise._setProxied();
this._setProxyHandlers(promise, -15);
};
Promise.prototype._setBoundTo = function Promise$_setBoundTo(obj) {
if (obj !== void 0) {
this._bitField = this._bitField | 8388608;
this._boundTo = obj;
} else {
this._bitField = this._bitField & (~8388608);
}
};
Promise.prototype._isBound = function Promise$_isBound() {
return (this._bitField & 8388608) === 8388608;
};
Promise.prototype._resolveFromResolver =
function Promise$_resolveFromResolver(resolver) {
var promise = this;
this._setTrace(void 0);
this._pushContext();
function Promise$_resolver(val) {
if (promise._tryFollow(val)) {
return;
}
promise._fulfill(val);
}
function Promise$_rejecter(val) {
var trace = canAttach(val) ? val : new Error(val + "");
promise._attachExtraTrace(trace);
markAsOriginatingFromRejection(val);
promise._reject(val, trace === val ? void 0 : trace);
}
var r = tryCatch2(resolver, void 0, Promise$_resolver, Promise$_rejecter);
this._popContext();
if (r !== void 0 && r === errorObj) {
var e = r.e;
var trace = canAttach(e) ? e : new Error(e + "");
promise._reject(e, trace);
}
};
Promise.prototype._spreadSlowCase =
function Promise$_spreadSlowCase(targetFn, promise, values, boundTo) {
var promiseForAll = new PromiseArray(values).promise();
var promise2 = promiseForAll._then(function() {
return targetFn.apply(boundTo, arguments);
}, void 0, void 0, APPLY, void 0);
promise._follow(promise2);
};
Promise.prototype._callSpread =
function Promise$_callSpread(handler, promise, value) {
var boundTo = this._boundTo;
if (isArray(value)) {
for (var i = 0, len = value.length; i < len; ++i) {
if (cast(value[i], void 0) instanceof Promise) {
this._spreadSlowCase(handler, promise, value, boundTo);
return;
}
}
}
promise._pushContext();
return tryCatchApply(handler, value, boundTo);
};
Promise.prototype._callHandler =
function Promise$_callHandler(
handler, receiver, promise, value) {
var x;
if (receiver === APPLY && !this.isRejected()) {
x = this._callSpread(handler, promise, value);
} else {
promise._pushContext();
x = tryCatch1(handler, receiver, value);
}
promise._popContext();
return x;
};
Promise.prototype._settlePromiseFromHandler =
function Promise$_settlePromiseFromHandler(
handler, receiver, value, promise
) {
if (!(promise instanceof Promise)) {
handler.call(receiver, value, promise);
return;
}
var x = this._callHandler(handler, receiver, promise, value);
if (promise._isFollowing()) return;
if (x === errorObj || x === promise || x === NEXT_FILTER) {
var err = x === promise
? makeSelfResolutionError()
: x.e;
var trace = canAttach(err) ? err : new Error(err + "");
if (x !== NEXT_FILTER) promise._attachExtraTrace(trace);
promise._rejectUnchecked(err, trace);
} else {
var castValue = cast(x, promise);
if (castValue instanceof Promise) {
if (castValue.isRejected() &&
!castValue._isCarryingStackTrace() &&
!canAttach(castValue._settledValue)) {
var trace = new Error(castValue._settledValue + "");
promise._attachExtraTrace(trace);
castValue._setCarriedStackTrace(trace);
}
promise._follow(castValue);
promise._propagateFrom(castValue, 1);
} else {
promise._fulfillUnchecked(x);
}
}
};
Promise.prototype._follow =
function Promise$_follow(promise) {
this._setFollowing();
if (promise.isPending()) {
this._propagateFrom(promise, 1);
promise._proxyPromise(this);
} else if (promise.isFulfilled()) {
this._fulfillUnchecked(promise._settledValue);
} else {
this._rejectUnchecked(promise._settledValue,
promise._getCarriedStackTrace());
}
if (promise._isRejectionUnhandled()) promise._unsetRejectionIsUnhandled();
if (debugging &&
promise._traceParent == null) {
promise._traceParent = this;
}
};
Promise.prototype._tryFollow =
function Promise$_tryFollow(value) {
if (this._isFollowingOrFulfilledOrRejected() ||
value === this) {
return false;
}
var maybePromise = cast(value, void 0);
if (!(maybePromise instanceof Promise)) {
return false;
}
this._follow(maybePromise);
return true;
};
Promise.prototype._resetTrace = function Promise$_resetTrace() {
if (debugging) {
this._trace = new CapturedTrace(this._peekContext() === void 0);
}
};
Promise.prototype._setTrace = function Promise$_setTrace(parent) {
if (debugging) {
var context = this._peekContext();
this._traceParent = context;
var isTopLevel = context === void 0;
if (parent !== void 0 &&
parent._traceParent === context) {
this._trace = parent._trace;
} else {
this._trace = new CapturedTrace(isTopLevel);
}
}
return this;
};
Promise.prototype._attachExtraTrace =
function Promise$_attachExtraTrace(error) {
if (debugging) {
var promise = this;
var stack = error.stack;
stack = typeof stack === "string" ? stack.split("\n") : [];
CapturedTrace.protectErrorMessageNewlines(stack);
var headerLineCount = 1;
var combinedTraces = 1;
while(promise != null &&
promise._trace != null) {
stack = CapturedTrace.combine(
stack,
promise._trace.stack.split("\n")
);
promise = promise._traceParent;
combinedTraces++;
}
var stackTraceLimit = Error.stackTraceLimit || 10;
var max = (stackTraceLimit + headerLineCount) * combinedTraces;
var len = stack.length;
if (len > max) {
stack.length = max;
}
if (len > 0)
stack[0] = stack[0].split("\u0002\u0000\u0001").join("\n");
if (stack.length <= headerLineCount) {
error.stack = "(No stack trace)";
} else {
error.stack = stack.join("\n");
}
}
};
Promise.prototype._cleanValues = function Promise$_cleanValues() {
if (this._cancellable()) {
this._cancellationParent = void 0;
}
};
Promise.prototype._propagateFrom =
function Promise$_propagateFrom(parent, flags) {
if ((flags & 1) > 0 && parent._cancellable()) {
this._setCancellable();
this._cancellationParent = parent;
}
if ((flags & 4) > 0) {
this._setBoundTo(parent._boundTo);
}
if ((flags & 2) > 0) {
this._setTrace(parent);
}
};
Promise.prototype._fulfill = function Promise$_fulfill(value) {
if (this._isFollowingOrFulfilledOrRejected()) return;
this._fulfillUnchecked(value);
};
Promise.prototype._reject =
function Promise$_reject(reason, carriedStackTrace) {
if (this._isFollowingOrFulfilledOrRejected()) return;
this._rejectUnchecked(reason, carriedStackTrace);
};
Promise.prototype._settlePromiseAt = function Promise$_settlePromiseAt(index) {
var handler = this.isFulfilled()
? this._fulfillmentHandlerAt(index)
: this._rejectionHandlerAt(index);
var value = this._settledValue;
var receiver = this._receiverAt(index);
var promise = this._promiseAt(index);
if (typeof handler === "function") {
this._settlePromiseFromHandler(handler, receiver, value, promise);
} else {
var done = false;
var isFulfilled = this.isFulfilled();
if (receiver !== void 0) {
if (receiver instanceof Promise &&
receiver._isProxied()) {
receiver._unsetProxied();
if (isFulfilled) receiver._fulfillUnchecked(value);
else receiver._rejectUnchecked(value,
this._getCarriedStackTrace());
done = true;
} else if (receiver instanceof PromiseArray) {
if (isFulfilled) receiver._promiseFulfilled(value, promise);
else receiver._promiseRejected(value, promise);
done = true;
}
}
if (!done) {
if (isFulfilled) promise._fulfill(value);
else promise._reject(value, this._getCarriedStackTrace());
}
}
if (index >= 4) {
this._queueGC();
}
};
Promise.prototype._isProxied = function Promise$_isProxied() {
return (this._bitField & 4194304) === 4194304;
};
Promise.prototype._setProxied = function Promise$_setProxied() {
this._bitField = this._bitField | 4194304;
};
Promise.prototype._unsetProxied = function Promise$_unsetProxied() {
this._bitField = this._bitField & (~4194304);
};
Promise.prototype._isGcQueued = function Promise$_isGcQueued() {
return (this._bitField & -1073741824) === -1073741824;
};
Promise.prototype._setGcQueued = function Promise$_setGcQueued() {
this._bitField = this._bitField | -1073741824;
};
Promise.prototype._unsetGcQueued = function Promise$_unsetGcQueued() {
this._bitField = this._bitField & (~-1073741824);
};
Promise.prototype._queueGC = function Promise$_queueGC() {
if (this._isGcQueued()) return;
this._setGcQueued();
async.invokeLater(this._gc, this, void 0);
};
Promise.prototype._gc = function Promise$gc() {
var len = this._length() * 5 - 5;
for (var i = 0; i < len; i++) {
delete this[i];
}
this._clearFirstHandlerData();
this._setLength(0);
this._unsetGcQueued();
};
Promise.prototype._clearFirstHandlerData =
function Promise$_clearFirstHandlerData() {
this._fulfillmentHandler0 = void 0;
this._rejectionHandler0 = void 0;
this._promise0 = void 0;
this._receiver0 = void 0;
};
Promise.prototype._queueSettleAt = function Promise$_queueSettleAt(index) {
if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled();
async.invoke(this._settlePromiseAt, this, index);
};
Promise.prototype._fulfillUnchecked =
function Promise$_fulfillUnchecked(value) {
if (!this.isPending()) return;
if (value === this) {
var err = makeSelfResolutionError();
this._attachExtraTrace(err);
return this._rejectUnchecked(err, void 0);
}
this._cleanValues();
this._setFulfilled();
this._settledValue = value;
var len = this._length();
if (len > 0) {
async.invoke(this._settlePromises, this, len);
}
};
Promise.prototype._rejectUncheckedCheckError =
function Promise$_rejectUncheckedCheckError(reason) {
var trace = canAttach(reason) ? reason : new Error(reason + "");
this._rejectUnchecked(reason, trace === reason ? void 0 : trace);
};
Promise.prototype._rejectUnchecked =
function Promise$_rejectUnchecked(reason, trace) {
if (!this.isPending()) return;
if (reason === this) {
var err = makeSelfResolutionError();
this._attachExtraTrace(err);
return this._rejectUnchecked(err);
}
this._cleanValues();
this._setRejected();
this._settledValue = reason;
if (this._isFinal()) {
async.invokeLater(thrower, void 0, trace === void 0 ? reason : trace);
return;
}
var len = this._length();
if (trace !== void 0) this._setCarriedStackTrace(trace);
if (len > 0) {
async.invoke(this._rejectPromises, this, null);
} else {
this._ensurePossibleRejectionHandled();
}
};
Promise.prototype._rejectPromises = function Promise$_rejectPromises() {
this._settlePromises();
this._unsetCarriedStackTrace();
};
Promise.prototype._settlePromises = function Promise$_settlePromises() {
var len = this._length();
for (var i = 0; i < len; i++) {
this._settlePromiseAt(i);
}
};
Promise.prototype._ensurePossibleRejectionHandled =
function Promise$_ensurePossibleRejectionHandled() {
this._setRejectionIsUnhandled();
if (CapturedTrace.possiblyUnhandledRejection !== void 0) {
async.invokeLater(this._notifyUnhandledRejection, this, void 0);
}
};
Promise.prototype._notifyUnhandledRejectionIsHandled =
function Promise$_notifyUnhandledRejectionIsHandled() {
if (typeof unhandledRejectionHandled === "function") {
async.invokeLater(unhandledRejectionHandled, void 0, this);
}
};
Promise.prototype._notifyUnhandledRejection =
function Promise$_notifyUnhandledRejection() {
if (this._isRejectionUnhandled()) {
var reason = this._settledValue;
var trace = this._getCarriedStackTrace();
this._setUnhandledRejectionIsNotified();
if (trace !== void 0) {
this._unsetCarriedStackTrace();
reason = trace;
}
if (typeof CapturedTrace.possiblyUnhandledRejection === "function") {
CapturedTrace.possiblyUnhandledRejection(reason, this);
}
}
};
var contextStack = [];
Promise.prototype._peekContext = function Promise$_peekContext() {
var lastIndex = contextStack.length - 1;
if (lastIndex >= 0) {
return contextStack[lastIndex];
}
return void 0;
};
Promise.prototype._pushContext = function Promise$_pushContext() {
if (!debugging) return;
contextStack.push(this);
};
Promise.prototype._popContext = function Promise$_popContext() {
if (!debugging) return;
contextStack.pop();
};
Promise.noConflict = function Promise$NoConflict() {
return noConflict(Promise);
};
Promise.setScheduler = function(fn) {
if (typeof fn !== "function") throw new TypeError("fn must be a function");
async._schedule = fn;
};
if (!CapturedTrace.isSupported()) {
Promise.longStackTraces = function(){};
debugging = false;
}
Promise._makeSelfResolutionError = makeSelfResolutionError;
_dereq_("./finally.js")(Promise, NEXT_FILTER, cast);
_dereq_("./direct_resolve.js")(Promise);
_dereq_("./synchronous_inspection.js")(Promise);
_dereq_("./join.js")(Promise, PromiseArray, cast, INTERNAL);
Promise.RangeError = RangeError;
Promise.CancellationError = CancellationError;
Promise.TimeoutError = TimeoutError;
Promise.TypeError = TypeError;
Promise.OperationalError = OperationalError;
Promise.RejectionError = OperationalError;
Promise.AggregateError = errors.AggregateError;
util.toFastProperties(Promise);
util.toFastProperties(Promise.prototype);
Promise.Promise = Promise;
_dereq_('./nodeify.js')(Promise);
Promise.prototype = Promise.prototype;
return Promise;
};
},{"./async.js":1,"./captured_trace.js":3,"./catch_filter.js":4,"./direct_resolve.js":5,"./errors.js":6,"./errors_api_rejection":7,"./finally.js":9,"./join.js":10,"./nodeify.js":11,"./promise_array.js":13,"./promise_resolver.js":14,"./synchronous_inspection.js":17,"./thenables.js":18,"./util.js":19}],13:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
module.exports = function(Promise, INTERNAL, cast) {
var canAttach = _dereq_("./errors.js").canAttach;
var util = _dereq_("./util.js");
var isArray = util.isArray;
function toResolutionValue(val) {
switch(val) {
case -1: return void 0;
case -2: return [];
case -3: return {};
}
}
function PromiseArray(values) {
var promise = this._promise = new Promise(INTERNAL);
var parent = void 0;
if (values instanceof Promise) {
parent = values;
promise._propagateFrom(parent, 1 | 4);
}
promise._setTrace(parent);
this._values = values;
this._length = 0;
this._totalResolved = 0;
this._init(void 0, -2);
}
PromiseArray.prototype.length = function PromiseArray$length() {
return this._length;
};
PromiseArray.prototype.promise = function PromiseArray$promise() {
return this._promise;
};
PromiseArray.prototype._init =
function PromiseArray$_init(_, resolveValueIfEmpty) {
var values = cast(this._values, void 0);
if (values instanceof Promise) {
this._values = values;
values._setBoundTo(this._promise._boundTo);
if (values.isFulfilled()) {
values = values._settledValue;
if (!isArray(values)) {
var err = new Promise.TypeError("expecting an array, a promise or a thenable");
this.__hardReject__(err);
return;
}
} else if (values.isPending()) {
values._then(
PromiseArray$_init,
this._reject,
void 0,
this,
resolveValueIfEmpty
);
return;
} else {
values._unsetRejectionIsUnhandled();
this._reject(values._settledValue);
return;
}
} else if (!isArray(values)) {
var err = new Promise.TypeError("expecting an array, a promise or a thenable");
this.__hardReject__(err);
return;
}
if (values.length === 0) {
if (resolveValueIfEmpty === -5) {
this._resolveEmptyArray();
}
else {
this._resolve(toResolutionValue(resolveValueIfEmpty));
}
return;
}
var len = this.getActualLength(values.length);
var newLen = len;
var newValues = this.shouldCopyValues() ? new Array(len) : this._values;
var isDirectScanNeeded = false;
for (var i = 0; i < len; ++i) {
var maybePromise = cast(values[i], void 0);
if (maybePromise instanceof Promise) {
if (maybePromise.isPending()) {
maybePromise._proxyPromiseArray(this, i);
} else {
maybePromise._unsetRejectionIsUnhandled();
isDirectScanNeeded = true;
}
} else {
isDirectScanNeeded = true;
}
newValues[i] = maybePromise;
}
this._values = newValues;
this._length = newLen;
if (isDirectScanNeeded) {
this._scanDirectValues(len);
}
};
PromiseArray.prototype._settlePromiseAt =
function PromiseArray$_settlePromiseAt(index) {
var value = this._values[index];
if (!(value instanceof Promise)) {
this._promiseFulfilled(value, index);
} else if (value.isFulfilled()) {
this._promiseFulfilled(value._settledValue, index);
} else if (value.isRejected()) {
this._promiseRejected(value._settledValue, index);
}
};
PromiseArray.prototype._scanDirectValues =
function PromiseArray$_scanDirectValues(len) {
for (var i = 0; i < len; ++i) {
if (this._isResolved()) {
break;
}
this._settlePromiseAt(i);
}
};
PromiseArray.prototype._isResolved = function PromiseArray$_isResolved() {
return this._values === null;
};
PromiseArray.prototype._resolve = function PromiseArray$_resolve(value) {
this._values = null;
this._promise._fulfill(value);
};
PromiseArray.prototype.__hardReject__ =
PromiseArray.prototype._reject = function PromiseArray$_reject(reason) {
this._values = null;
var trace = canAttach(reason) ? reason : new Error(reason + "");
this._promise._attachExtraTrace(trace);
this._promise._reject(reason, trace);
};
PromiseArray.prototype._promiseProgressed =
function PromiseArray$_promiseProgressed(progressValue, index) {
if (this._isResolved()) return;
this._promise._progress({
index: index,
value: progressValue
});
};
PromiseArray.prototype._promiseFulfilled =
function PromiseArray$_promiseFulfilled(value, index) {
if (this._isResolved()) return;
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
}
};
PromiseArray.prototype._promiseRejected =
function PromiseArray$_promiseRejected(reason, index) {
if (this._isResolved()) return;
this._totalResolved++;
this._reject(reason);
};
PromiseArray.prototype.shouldCopyValues =
function PromiseArray$_shouldCopyValues() {
return true;
};
PromiseArray.prototype.getActualLength =
function PromiseArray$getActualLength(len) {
return len;
};
return PromiseArray;
};
},{"./errors.js":6,"./util.js":19}],14:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
var util = _dereq_("./util.js");
var maybeWrapAsError = util.maybeWrapAsError;
var errors = _dereq_("./errors.js");
var TimeoutError = errors.TimeoutError;
var OperationalError = errors.OperationalError;
var async = _dereq_("./async.js");
var haveGetters = util.haveGetters;
var es5 = _dereq_("./es5.js");
function isUntypedError(obj) {
return obj instanceof Error &&
es5.getPrototypeOf(obj) === Error.prototype;
}
function wrapAsOperationalError(obj) {
var ret;
if (isUntypedError(obj)) {
ret = new OperationalError(obj);
} else {
ret = obj;
}
errors.markAsOriginatingFromRejection(ret);
return ret;
}
function nodebackForPromise(promise) {
function PromiseResolver$_callback(err, value) {
if (promise === null) return;
if (err) {
var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
promise._attachExtraTrace(wrapped);
promise._reject(wrapped);
} else if (arguments.length > 2) {
var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
promise._fulfill(args);
} else {
promise._fulfill(value);
}
promise = null;
}
return PromiseResolver$_callback;
}
var PromiseResolver;
if (!haveGetters) {
PromiseResolver = function PromiseResolver(promise) {
this.promise = promise;
this.asCallback = nodebackForPromise(promise);
this.callback = this.asCallback;
};
}
else {
PromiseResolver = function PromiseResolver(promise) {
this.promise = promise;
};
}
if (haveGetters) {
var prop = {
get: function() {
return nodebackForPromise(this.promise);
}
};
es5.defineProperty(PromiseResolver.prototype, "asCallback", prop);
es5.defineProperty(PromiseResolver.prototype, "callback", prop);
}
PromiseResolver._nodebackForPromise = nodebackForPromise;
PromiseResolver.prototype.toString = function PromiseResolver$toString() {
return "[object PromiseResolver]";
};
PromiseResolver.prototype.resolve =
PromiseResolver.prototype.fulfill = function PromiseResolver$resolve(value) {
if (!(this instanceof PromiseResolver)) {
throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.");
}
var promise = this.promise;
if (promise._tryFollow(value)) {
return;
}
async.invoke(promise._fulfill, promise, value);
};
PromiseResolver.prototype.reject = function PromiseResolver$reject(reason) {
if (!(this instanceof PromiseResolver)) {
throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.");
}
var promise = this.promise;
errors.markAsOriginatingFromRejection(reason);
var trace = errors.canAttach(reason) ? reason : new Error(reason + "");
promise._attachExtraTrace(trace);
async.invoke(promise._reject, promise, reason);
if (trace !== reason) {
async.invoke(this._setCarriedStackTrace, this, trace);
}
};
PromiseResolver.prototype.progress =
function PromiseResolver$progress(value) {
if (!(this instanceof PromiseResolver)) {
throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.");
}
async.invoke(this.promise._progress, this.promise, value);
};
PromiseResolver.prototype.cancel = function PromiseResolver$cancel() {
async.invoke(this.promise.cancel, this.promise, void 0);
};
PromiseResolver.prototype.timeout = function PromiseResolver$timeout() {
this.reject(new TimeoutError("timeout"));
};
PromiseResolver.prototype.isResolved = function PromiseResolver$isResolved() {
return this.promise.isResolved();
};
PromiseResolver.prototype.toJSON = function PromiseResolver$toJSON() {
return this.promise.toJSON();
};
PromiseResolver.prototype._setCarriedStackTrace =
function PromiseResolver$_setCarriedStackTrace(trace) {
if (this.promise.isRejected()) {
this.promise._setCarriedStackTrace(trace);
}
};
module.exports = PromiseResolver;
},{"./async.js":1,"./errors.js":6,"./es5.js":8,"./util.js":19}],15:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
function arrayCopy(src, srcIndex, dst, dstIndex, len) {
for (var j = 0; j < len; ++j) {
dst[j + dstIndex] = src[j + srcIndex];
}
}
function Queue(capacity) {
this._capacity = capacity;
this._length = 0;
this._front = 0;
this._makeCapacity();
}
Queue.prototype._willBeOverCapacity =
function Queue$_willBeOverCapacity(size) {
return this._capacity < size;
};
Queue.prototype._pushOne = function Queue$_pushOne(arg) {
var length = this.length();
this._checkCapacity(length + 1);
var i = (this._front + length) & (this._capacity - 1);
this[i] = arg;
this._length = length + 1;
};
Queue.prototype.push = function Queue$push(fn, receiver, arg) {
var length = this.length() + 3;
if (this._willBeOverCapacity(length)) {
this._pushOne(fn);
this._pushOne(receiver);
this._pushOne(arg);
return;
}
var j = this._front + length - 3;
this._checkCapacity(length);
var wrapMask = this._capacity - 1;
this[(j + 0) & wrapMask] = fn;
this[(j + 1) & wrapMask] = receiver;
this[(j + 2) & wrapMask] = arg;
this._length = length;
};
Queue.prototype.shift = function Queue$shift() {
var front = this._front,
ret = this[front];
this[front] = void 0;
this._front = (front + 1) & (this._capacity - 1);
this._length--;
return ret;
};
Queue.prototype.length = function Queue$length() {
return this._length;
};
Queue.prototype._makeCapacity = function Queue$_makeCapacity() {
var len = this._capacity;
for (var i = 0; i < len; ++i) {
this[i] = void 0;
}
};
Queue.prototype._checkCapacity = function Queue$_checkCapacity(size) {
if (this._capacity < size) {
this._resizeTo(this._capacity << 3);
}
};
Queue.prototype._resizeTo = function Queue$_resizeTo(capacity) {
var oldFront = this._front;
var oldCapacity = this._capacity;
var oldQueue = new Array(oldCapacity);
var length = this.length();
arrayCopy(this, 0, oldQueue, 0, oldCapacity);
this._capacity = capacity;
this._makeCapacity();
this._front = 0;
if (oldFront + length <= oldCapacity) {
arrayCopy(oldQueue, oldFront, this, 0, length);
} else { var lengthBeforeWrapping =
length - ((oldFront + length) & (oldCapacity - 1));
arrayCopy(oldQueue, oldFront, this, 0, lengthBeforeWrapping);
arrayCopy(oldQueue, 0, this, lengthBeforeWrapping,
length - lengthBeforeWrapping);
}
};
module.exports = Queue;
},{}],16:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
var schedule;
var _MutationObserver;
if (typeof process === "object" && typeof process.version === "string") {
schedule = function Promise$_Scheduler(fn) {
process.nextTick(fn);
};
}
else if ((typeof MutationObserver !== "undefined" &&
(_MutationObserver = MutationObserver)) ||
(typeof WebKitMutationObserver !== "undefined" &&
(_MutationObserver = WebKitMutationObserver))) {
schedule = (function() {
var div = document.createElement("div");
var queuedFn = void 0;
var observer = new _MutationObserver(
function Promise$_Scheduler() {
var fn = queuedFn;
queuedFn = void 0;
fn();
}
);
observer.observe(div, {
attributes: true
});
return function Promise$_Scheduler(fn) {
queuedFn = fn;
div.classList.toggle("foo");
};
})();
}
else if (typeof setTimeout !== "undefined") {
schedule = function Promise$_Scheduler(fn) {
setTimeout(fn, 0);
};
}
else throw new Error("no async scheduler available");
module.exports = schedule;
},{}],17:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
module.exports = function(Promise) {
function PromiseInspection(promise) {
if (promise !== void 0) {
this._bitField = promise._bitField;
this._settledValue = promise.isResolved()
? promise._settledValue
: void 0;
}
else {
this._bitField = 0;
this._settledValue = void 0;
}
}
PromiseInspection.prototype.isFulfilled =
Promise.prototype.isFulfilled = function Promise$isFulfilled() {
return (this._bitField & 268435456) > 0;
};
PromiseInspection.prototype.isRejected =
Promise.prototype.isRejected = function Promise$isRejected() {
return (this._bitField & 134217728) > 0;
};
PromiseInspection.prototype.isPending =
Promise.prototype.isPending = function Promise$isPending() {
return (this._bitField & 402653184) === 0;
};
PromiseInspection.prototype.value =
Promise.prototype.value = function Promise$value() {
if (!this.isFulfilled()) {
throw new TypeError("cannot get fulfillment value of a non-fulfilled promise");
}
return this._settledValue;
};
PromiseInspection.prototype.error =
PromiseInspection.prototype.reason =
Promise.prototype.reason = function Promise$reason() {
if (!this.isRejected()) {
throw new TypeError("cannot get rejection reason of a non-rejected promise");
}
return this._settledValue;
};
PromiseInspection.prototype.isResolved =
Promise.prototype.isResolved = function Promise$isResolved() {
return (this._bitField & 402653184) > 0;
};
Promise.PromiseInspection = PromiseInspection;
};
},{}],18:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
module.exports = function(Promise, INTERNAL) {
var util = _dereq_("./util.js");
var canAttach = _dereq_("./errors.js").canAttach;
var errorObj = util.errorObj;
var isObject = util.isObject;
function getThen(obj) {
try {
return obj.then;
}
catch(e) {
errorObj.e = e;
return errorObj;
}
}
function Promise$_Cast(obj, originalPromise) {
if (isObject(obj)) {
if (obj instanceof Promise) {
return obj;
}
else if (isAnyBluebirdPromise(obj)) {
var ret = new Promise(INTERNAL);
ret._setTrace(void 0);
obj._then(
ret._fulfillUnchecked,
ret._rejectUncheckedCheckError,
ret._progressUnchecked,
ret,
null
);
ret._setFollowing();
return ret;
}
var then = getThen(obj);
if (then === errorObj) {
if (originalPromise !== void 0 && canAttach(then.e)) {
originalPromise._attachExtraTrace(then.e);
}
return Promise.reject(then.e);
} else if (typeof then === "function") {
return Promise$_doThenable(obj, then, originalPromise);
}
}
return obj;
}
var hasProp = {}.hasOwnProperty;
function isAnyBluebirdPromise(obj) {
return hasProp.call(obj, "_promise0");
}
function Promise$_doThenable(x, then, originalPromise) {
var resolver = Promise.defer();
var called = false;
try {
then.call(
x,
Promise$_resolveFromThenable,
Promise$_rejectFromThenable,
Promise$_progressFromThenable
);
} catch(e) {
if (!called) {
called = true;
var trace = canAttach(e) ? e : new Error(e + "");
if (originalPromise !== void 0) {
originalPromise._attachExtraTrace(trace);
}
resolver.promise._reject(e, trace);
}
}
return resolver.promise;
function Promise$_resolveFromThenable(y) {
if (called) return;
called = true;
if (x === y) {
var e = Promise._makeSelfResolutionError();
if (originalPromise !== void 0) {
originalPromise._attachExtraTrace(e);
}
resolver.promise._reject(e, void 0);
return;
}
resolver.resolve(y);
}
function Promise$_rejectFromThenable(r) {
if (called) return;
called = true;
var trace = canAttach(r) ? r : new Error(r + "");
if (originalPromise !== void 0) {
originalPromise._attachExtraTrace(trace);
}
resolver.promise._reject(r, trace);
}
function Promise$_progressFromThenable(v) {
if (called) return;
var promise = resolver.promise;
if (typeof promise._progress === "function") {
promise._progress(v);
}
}
}
return Promise$_Cast;
};
},{"./errors.js":6,"./util.js":19}],19:[function(_dereq_,module,exports){
/**
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
"use strict";
var es5 = _dereq_("./es5.js");
var haveGetters = (function(){
try {
var o = {};
es5.defineProperty(o, "f", {
get: function () {
return 3;
}
});
return o.f === 3;
}
catch (e) {
return false;
}
})();
var canEvaluate = typeof navigator == "undefined";
var errorObj = {e: {}};
function tryCatch1(fn, receiver, arg) {
try { return fn.call(receiver, arg); }
catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch2(fn, receiver, arg, arg2) {
try { return fn.call(receiver, arg, arg2); }
catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch3(fn, receiver, arg, arg2, arg3) {
try { return fn.call(receiver, arg, arg2, arg3); }
catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch4(fn, receiver, arg, arg2, arg3, arg4) {
try { return fn.call(receiver, arg, arg2, arg3, arg4); }
catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatchApply(fn, args, receiver) {
try { return fn.apply(receiver, args); }
catch (e) {
errorObj.e = e;
return errorObj;
}
}
var inherits = function(Child, Parent) {
var hasProp = {}.hasOwnProperty;
function T() {
this.constructor = Child;
this.constructor$ = Parent;
for (var propertyName in Parent.prototype) {
if (hasProp.call(Parent.prototype, propertyName) &&
propertyName.charAt(propertyName.length-1) !== "$"
) {
this[propertyName + "$"] = Parent.prototype[propertyName];
}
}
}
T.prototype = Parent.prototype;
Child.prototype = new T();
return Child.prototype;
};
function asString(val) {
return typeof val === "string" ? val : ("" + val);
}
function isPrimitive(val) {
return val == null || val === true || val === false ||
typeof val === "string" || typeof val === "number";
}
function isObject(value) {
return !isPrimitive(value);
}
function maybeWrapAsError(maybeError) {
if (!isPrimitive(maybeError)) return maybeError;
return new Error(asString(maybeError));
}
function withAppended(target, appendee) {
var len = target.length;
var ret = new Array(len + 1);
var i;
for (i = 0; i < len; ++i) {
ret[i] = target[i];
}
ret[i] = appendee;
return ret;
}
function getDataPropertyOrDefault(obj, key, defaultValue) {
if (es5.isES5) {
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null) {
return desc.get == null && desc.set == null
? desc.value
: defaultValue;
}
} else {
return {}.hasOwnProperty.call(obj, key) ? obj[key] : void 0;
}
}
function notEnumerableProp(obj, name, value) {
if (isPrimitive(obj)) return obj;
var descriptor = {
value: value,
configurable: true,
enumerable: false,
writable: true
};
es5.defineProperty(obj, name, descriptor);
return obj;
}
var wrapsPrimitiveReceiver = (function() {
return this !== "string";
}).call("string");
function thrower(r) {
throw r;
}
var inheritedDataKeys = (function() {
if (es5.isES5) {
return function(obj, opts) {
var ret = [];
var visitedKeys = Object.create(null);
var getKeys = Object(opts).includeHidden
? Object.getOwnPropertyNames
: Object.keys;
while (obj != null) {
var keys;
try {
keys = getKeys(obj);
} catch (e) {
return ret;
}
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (visitedKeys[key]) continue;
visitedKeys[key] = true;
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null && desc.get == null && desc.set == null) {
ret.push(key);
}
}
obj = es5.getPrototypeOf(obj);
}
return ret;
};
} else {
return function(obj) {
var ret = [];
/*jshint forin:false */
for (var key in obj) {
ret.push(key);
}
return ret;
};
}
})();
function isClass(fn) {
try {
if (typeof fn === "function") {
var keys = es5.keys(fn.prototype);
return keys.length > 0 &&
!(keys.length === 1 && keys[0] === "constructor");
}
return false;
} catch (e) {
return false;
}
}
function toFastProperties(obj) {
/*jshint -W027*/
function f() {}
f.prototype = obj;
return f;
eval(obj);
}
var rident = /^[a-z$_][a-z$_0-9]*$/i;
function isIdentifier(str) {
return rident.test(str);
}
function filledRange(count, prefix, suffix) {
var ret = new Array(count);
for(var i = 0; i < count; ++i) {
ret[i] = prefix + i + suffix;
}
return ret;
}
var ret = {
isClass: isClass,
isIdentifier: isIdentifier,
inheritedDataKeys: inheritedDataKeys,
getDataPropertyOrDefault: getDataPropertyOrDefault,
thrower: thrower,
isArray: es5.isArray,
haveGetters: haveGetters,
notEnumerableProp: notEnumerableProp,
isPrimitive: isPrimitive,
isObject: isObject,
canEvaluate: canEvaluate,
errorObj: errorObj,
tryCatch1: tryCatch1,
tryCatch2: tryCatch2,
tryCatch3: tryCatch3,
tryCatch4: tryCatch4,
tryCatchApply: tryCatchApply,
inherits: inherits,
withAppended: withAppended,
asString: asString,
maybeWrapAsError: maybeWrapAsError,
wrapsPrimitiveReceiver: wrapsPrimitiveReceiver,
toFastProperties: toFastProperties,
filledRange: filledRange
};
module.exports = ret;
},{"./es5.js":8}]},{},[2])
(2)
}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
/** FILE: src/remotestorage.js **/
(function (global) {
var hasLocalStorage;
// wrapper to implement defer() functionality
Promise.defer = function () {
var resolve, reject;
var promise = new Promise(function() {
resolve = arguments[0];
reject = arguments[1];
});
return {
resolve: resolve,
reject: reject,
promise: promise
};
};
function logError(error) {
if (typeof(error) === 'string') {
console.error(error);
} else {
console.error(error.message, error.stack);
}
}
function emitUnauthorized(r) {
if (r.statusCode === 403 || r.statusCode === 401) {
this._emit('error', new RemoteStorage.Unauthorized());
}
return Promise.resolve(r);
}
function shareFirst(path) {
return ( this.backend === 'dropbox' &&
path.match(/^\/public\/.*[^\/]$/) );
}
var SyncedGetPutDelete = {
get: function (path, maxAge) {
var self = this;
if (this.local) {
if (maxAge === undefined) {
if ((typeof this.remote === 'object') &&
this.remote.connected && this.remote.online) {
maxAge = 2*this.getSyncInterval();
} else {
RemoteStorage.log('Not setting default maxAge, because remote is offline or not connected');
maxAge = false;
}
}
var maxAgeInvalid = function (maxAge) {
return maxAge !== false && typeof(maxAge) !== 'number';
};
if (maxAgeInvalid(maxAge)) {
return Promise.reject('Argument \'maxAge\' must be false or a number');
}
return this.local.get(path, maxAge, this.sync.queueGetRequest.bind(this.sync));
} else {
return this.remote.get(path);
}
},
put: function (path, body, contentType) {
if (shareFirst.bind(this)(path)) {
return SyncedGetPutDelete._wrapBusyDone.call(this, this.remote.put(path, body, contentType));
}
else if (this.local) {
return this.local.put(path, body, contentType);
} else {
return SyncedGetPutDelete._wrapBusyDone.call(this, this.remote.put(path, body, contentType));
}
},
'delete': function (path) {
if (this.local) {
return this.local.delete(path);
} else {
return SyncedGetPutDelete._wrapBusyDone.call(this, this.remote.delete(path));
}
},
_wrapBusyDone: function (result) {
var self = this;
this._emit('wire-busy');
return result.then(function (r) {
self._emit('wire-done', { success: true });
return Promise.resolve(r);
}, function (err) {
self._emit('wire-done', { success: false });
return Promise.reject(err);
});
}
};
/**
* Class: RemoteStorage
*
* TODO needs proper introduction and links to relevant classes etc
*
* Constructor for global remoteStorage object.
*
* This class primarily contains feature detection code and a global convenience API.
*
* Depending on which features are built in, it contains different attributes and
* functions. See the individual features for more information.
*
* (start code)
* var remoteStorage = new RemoteStorage({
* logging: true, // defaults to false
* cordovaRedirectUri: 'https://app.mygreatapp.com' // defaults to undefined
* });
* (end code)
*/
var RemoteStorage = function (cfg) {
/**
* Event: ready
*
* Fired when ready
**/
/**
* Event: not-connected
*
* Fired when ready, but no storage connected ("anonymous mode")
**/
/**
* Event: connected
*
* Fired when a remote storage has been connected
**/
/**
* Event: disconnected
*
* Fired after disconnect
**/
/**
* Event: error
*
* Fired when an error occurs
*
* Arguments:
* the error
**/
/**
* Event: features-loaded
*
* Fired when all features are loaded
**/
/**
* Event: connecting
*
* Fired before webfinger lookup
**/
/**
* Event: authing
*
* Fired before redirecting to the authing server
**/
/**
* Event: wire-busy
*
* Fired when a wire request starts
**/
/**
* Event: wire-done
*
* Fired when a wire request completes
**/
// Initial configuration property settings.
if (typeof cfg === 'object') {
RemoteStorage.config.logging = !!cfg.logging;
RemoteStorage.config.cordovaRedirectUri = cfg.cordovaRedirectUri;
}
RemoteStorage.eventHandling(
this, 'ready', 'connected', 'disconnected', 'not-connected', 'conflict',
'error', 'features-loaded', 'connecting', 'authing', 'wire-busy',
'wire-done', 'sync-interval-change'
);
// pending get/put/delete calls.
this._pending = [];
this._setGPD({
get: this._pendingGPD('get'),
put: this._pendingGPD('put'),
delete: this._pendingGPD('delete')
});
this._cleanups = [];
this._pathHandlers = { change: {} };
this.apiKeys = {};
hasLocalStorage = RemoteStorage.util.localStorageAvailable();
if (hasLocalStorage) {
try {
this.apiKeys = JSON.parse(localStorage.getItem('remotestorage:api-keys')) || {};
} catch(exc) {
// ignored
}
this.setBackend(localStorage.getItem('remotestorage:backend') || 'remotestorage');
}
var origOn = this.on;
this.on = function (eventName, handler) {
if (eventName === 'ready' && this.remote.connected && this._allLoaded) {
setTimeout(handler, 0);
} else if (eventName === 'features-loaded' && this._allLoaded) {
setTimeout(handler, 0);
}
return origOn.call(this, eventName, handler);
};
this._init();
this.fireInitial = function () {
if (this.local) {
setTimeout(this.local.fireInitial.bind(this.local), 0);
}
}.bind(this);
this.on('ready', this.fireInitial.bind(this));
};
RemoteStorage.SyncedGetPutDelete = SyncedGetPutDelete;
RemoteStorage.DiscoveryError = function (message) {
Error.apply(this, arguments);
this.message = message;
};
RemoteStorage.DiscoveryError.prototype = Object.create(Error.prototype);
RemoteStorage.Unauthorized = function () { Error.apply(this, arguments); };
RemoteStorage.Unauthorized.prototype = Object.create(Error.prototype);
/**
* Method: RemoteStorage.log
*
* Log using console.log, when remoteStorage logging is enabled.
*
* You can enable logging with <enableLog>.
*
* (In node.js you can also enable logging during remoteStorage object
* creation. See: <RemoteStorage>).
*/
RemoteStorage.log = function () {
if (RemoteStorage.config.logging) {
console.log.apply(console, arguments);
}
};
RemoteStorage.config = {
logging: false,
changeEvents: {
local: true,
window: false,
remote: true,
conflict: true
},
discoveryTimeout: 10000,
cordovaRedirectUri: undefined
};
RemoteStorage.prototype = {
/**
* Method: displayWidget
*
* Displays the widget at the top right of the page. Make sure to call this function
* once on every pageload (after the html 'body' tag), unless you use a custom widget.
*
* Parameters:
*
* domID: identifier of the DOM element which should embody the widget (optional)
*/
// (see src/widget.js for implementation)
/**
* Property: remote
*
* Properties:
*
* connected - Boolean, whether or not a remote store is connected
* online - Boolean, whether last sync action was successful or not
* userAddress - String, the user address of the connected user
* properties - String, the properties of the WebFinger link
*/
/**
* Method: scope
*
* Returns a BaseClient with a certain scope (base path). Please use this method
* only for debugging, and always use defineModule instead, to get access to a
* BaseClient from a module in an app.
*
* Parameters:
*
* scope - A string, with a leading and a trailing slash, specifying the
* base path of the BaseClient that will be returned.
*
* Code example:
*
* (start code)
* remoteStorage.scope('/pictures/').getListing('');
* remoteStorage.scope('/public/pictures/').getListing('');
*/
/**
* Method: connect
*
* Connect to a remoteStorage server.
*
* Parameters:
* userAddress - The user address (user@host) to connect to.
* token - (optional) A bearer token acquired beforehand
*
* Discovers the WebFinger profile of the given user address and initiates
* the OAuth dance.
*
* This method must be called *after* all required access has been claimed.
* When using the connect widget, it will call this method itself.
*
* Special cases:
*
* 1. If a bearer token is supplied as second argument, the OAuth dance
* will be skipped and the supplied token be used instead. This is
* useful outside of browser environments, where the token has been
* acquired in a different way.
*
* 2. If the Webfinger profile for the given user address doesn't contain
* an auth URL, the library will assume that client and server have
* established authorization among themselves, which will omit bearer
* tokens in all requests later on. This is useful for example when using
* Kerberos and similar protocols.
*/
connect: function (userAddress, token) {
this.setBackend('remotestorage');
if (userAddress.indexOf('@') < 0) {
this._emit('error', new RemoteStorage.DiscoveryError("User address doesn't contain an @."));
return;
}
if (global.cordova) {
if (typeof RemoteStorage.config.cordovaRedirectUri !== 'string') {
this._emit('error', new RemoteStorage.DiscoveryError("Please supply a custom HTTPS redirect URI for your Cordova app"));
return;
}
if (!global.cordova.InAppBrowser) {
this._emit('error', new RemoteStorage.DiscoveryError("Please include the InAppBrowser Cordova plugin to enable OAuth"));
return;
}
}
this.remote.configure({
userAddress: userAddress
});
this._emit('connecting');
var discoveryTimeout = setTimeout(function () {
this._emit('error', new RemoteStorage.DiscoveryError("No storage information found at that user address."));
}.bind(this), RemoteStorage.config.discoveryTimeout);
RemoteStorage.Discover(userAddress).then(function (info) {
// Info contains fields: href, storageApi, authURL (optional), properties
clearTimeout(discoveryTimeout);
this._emit('authing');
info.userAddress = userAddress;
this.remote.configure(info);
if (! this.remote.connected) {
if (info.authURL) {
if (typeof token === 'undefined') {
// Normal authorization step; the default way to connect
this.authorize(info.authURL, RemoteStorage.config.cordovaRedirectUri);
} else if (typeof token === 'string') {
// Token supplied directly by app/developer/user
RemoteStorage.log('Skipping authorization sequence and connecting with known token');
this.remote.configure({ token: token });
} else {
throw new Error("Supplied bearer token must be a string");
}
} else {
// In lieu of an excplicit authURL, assume that the browser and
// server handle any authorization needs; for instance, TLS may
// trigger the browser to use a client certificate, or a 401 Not
// Authorized response may make the browser send a Kerberos ticket
// using the SPNEGO method.
this.impliedauth();
}
}
}.bind(this), function(err) {
this._emit('error', new RemoteStorage.DiscoveryError("Failed to contact storage server."));
}.bind(this));
},
/**
* Method: disconnect
*
* "Disconnect" from remotestorage server to terminate current session.
* This method clears all stored settings and deletes the entire local
* cache.
*/
disconnect: function () {
if (this.remote) {
this.remote.configure({
userAddress: null,
href: null,
storageApi: null,
token: null,
properties: null
});
}
this._setGPD({
get: this._pendingGPD('get'),
put: this._pendingGPD('put'),
delete: this._pendingGPD('delete')
});
var n = this._cleanups.length, i = 0;
var oneDone = function () {
i++;
if (i >= n) {
this._init();
RemoteStorage.log('Done cleaning up, emitting disconnected and disconnect events');
this._emit('disconnected');
}
}.bind(this);
if (n > 0) {
this._cleanups.forEach(function (cleanup) {
var cleanupResult = cleanup(this);
if (typeof(cleanupResult) === 'object' && typeof(cleanupResult.then) === 'function') {
cleanupResult.then(oneDone);
} else {
oneDone();
}
}.bind(this));
} else {
oneDone();
}
},
setBackend: function (what) {
this.backend = what;
if (hasLocalStorage) {
if (what) {
localStorage.setItem('remotestorage:backend', what);
} else {
localStorage.removeItem('remotestorage:backend');
}
}
},
/**
* Method: onChange
*
* Add a "change" event handler to the given path. Whenever a "change"
* happens (as determined by the backend, such as e.g.
* <RemoteStorage.IndexedDB>) and the affected path is equal to or below
* the given 'path', the given handler is called.
*
* You should usually not use this method directly, but instead use the
* "change" events provided by <RemoteStorage.BaseClient>.
*
* Parameters:
* path - Absolute path to attach handler to.
* handler - Handler function.
*/
onChange: function (path, handler) {
if (! this._pathHandlers.change[path]) {
this._pathHandlers.change[path] = [];
}
this._pathHandlers.change[path].push(handler);
},
/**
* Method: enableLog
*
* Enable remoteStorage logging.
*/
enableLog: function () {
RemoteStorage.config.logging = true;
},
/**
* Method: disableLog
*
* Disable remoteStorage logging
*/
disableLog: function () {
RemoteStorage.config.logging = false;
},
/**
* Method: log
*
* The same as <RemoteStorage.log>.
*/
log: function () {
RemoteStorage.log.apply(RemoteStorage, arguments);
},
/**
* Method: setApiKeys (experimental)
*
* Set API keys for (currently) GoogleDrive and/or Dropbox backend support.
* See also the 'backends' example in the starter-kit. Note that support for
* both these backends is still experimental.
*
* Parameters:
* type - string, either 'googledrive' or 'dropbox'
* keys - object, with one string field; 'clientId' for GoogleDrive, or
* 'appKey' for Dropbox.
*
*/
setApiKeys: function (type, keys) {
if (keys) {
this.apiKeys[type] = keys;
if (type === 'dropbox' && (typeof this.dropbox === 'undefined' ||
this.dropbox.clientId !== keys.appKey)) {
RemoteStorage.Dropbox._rs_init(this);
} else if (type === 'googledrive' && (typeof this.googledrive === 'undefined' ||
this.googledrive.clientId !== keys.clientId)) {
RemoteStorage.GoogleDrive._rs_init(this);
}
} else {
delete this.apiKeys[type];
}
if (hasLocalStorage) {
localStorage.setItem('remotestorage:api-keys', JSON.stringify(this.apiKeys));
}
},
/**
* Method: setCordovaRedirectUri
*
* Set redirect URI to be used for the OAuth redirect within the
* in-app-browser window in Cordova apps.
*
* Parameters:
* uri - string, valid HTTP(S) URI
*/
setCordovaRedirectUri: function (uri) {
if (typeof uri !== 'string' || !uri.match(/http(s)?\:\/\//)) {
throw new Error("Cordova redirect URI must be a URI string");
}
RemoteStorage.config.cordovaRedirectUri = uri;
},
/**
** INITIALIZATION
**/
_init: function () {
var self = this,
readyFired = false;
function fireReady() {
try {
if (!readyFired) {
self._emit('ready');
readyFired = true;
}
} catch(e) {
console.error("'ready' failed: ", e, e.stack);
self._emit('error', e);
}
}
this._loadFeatures(function (features) {
this.log('[RemoteStorage] All features loaded');
this.local = features.local && new features.local();
// this.remote set by WireClient._rs_init as lazy property on
// RS.prototype
if (this.local && this.remote) {
this._setGPD(SyncedGetPutDelete, this);
this._bindChange(this.local);
} else if (this.remote) {
this._setGPD(this.remote, this.remote);
}
if (this.remote) {
this.remote.on('connected', function (){
fireReady();
self._emit('connected');
});
this.remote.on('not-connected', function (){
fireReady();
self._emit('not-connected');
});
if (this.remote.connected) {
fireReady();
self._emit('connected');
}
if (!this.hasFeature('Authorize')) {
this.remote.stopWaitingForToken();
}
}
this._collectCleanupFunctions();
try {
this._allLoaded = true;
this._emit('features-loaded');
} catch(exc) {
logError(exc);
this._emit('error', exc);
}
this._processPending();
}.bind(this));
},
_collectCleanupFunctions: function () {
this._cleanups = [];
for (var i=0; i < this.features.length; i++) {
var cleanup = this.features[i].cleanup;
if (typeof(cleanup) === 'function') {
this._cleanups.push(cleanup);
}
}
},
/**
** FEATURE DETECTION
**/
_loadFeatures: function (callback) {
var featureList = [
'WireClient',
'I18n',
'Dropbox',
'GoogleDrive',
'Access',
'Caching',
'Discover',
'Authorize',
'Widget',
'IndexedDB',
'LocalStorage',
'InMemoryStorage',
'Sync',
'BaseClient',
'Env'
];
var features = [];
var featuresDone = 0;
var self = this;
function featureDone() {
featuresDone++;
if (featuresDone === featureList.length) {
setTimeout(function () {
features.caching = !!RemoteStorage.Caching;
features.sync = !!RemoteStorage.Sync;
[
'IndexedDB',
'LocalStorage',
'InMemoryStorage'
].some(function (cachingLayer) {
if (features.some(function (feature) { return feature.name === cachingLayer; })) {
features.local = RemoteStorage[cachingLayer];
return true;
}
});
self.features = features;
callback(features);
}, 0);
}
}
function featureInitialized(name) {
self.log("[RemoteStorage] [FEATURE "+name+"] initialized.");
features.push({
name : name,
init : RemoteStorage[name]._rs_init,
supported : true,
cleanup : RemoteStorage[name]._rs_cleanup
});
featureDone();
}
function featureFailed(name, err) {
self.log("[RemoteStorage] [FEATURE "+name+"] initialization failed ( "+err+")");
featureDone();
}
function featureSupported(name, success) {
self.log("[RemoteStorage] [FEATURE "+name+"]" + success ? "":" not"+" supported");
if (!success) {
featureDone();
}
}
function initFeature(name) {
var initResult;
try {
initResult = RemoteStorage[name]._rs_init(self);
} catch(e) {
featureFailed(name, e);
return;
}
if (typeof(initResult) === 'object' && typeof(initResult.then) === 'function') {
initResult.then(
function (){ featureInitialized(name); },
function (err){ featureFailed(name, err); }
);
} else {
featureInitialized(name);
}
}
featureList.forEach(function (featureName) {
self.log("[RemoteStorage] [FEATURE " + featureName + "] initializing...");
var impl = RemoteStorage[featureName];
var supported;
if (impl) {
supported = !impl._rs_supported || impl._rs_supported();
if (typeof supported === 'object') {
supported.then(
function (){
featureSupported(featureName, true);
initFeature(featureName);
},
function (){
featureSupported(featureName, false);
}
);
} else if (typeof supported === 'boolean') {
featureSupported(featureName, supported);
if (supported) {
initFeature(featureName);
}
}
} else {
featureSupported(featureName, false);
}
});
},
/**
* Method: hasFeature
*
* Checks whether a feature is enabled or not within remoteStorage.
* Returns a boolean.
*
* Parameters:
* name - Capitalized name of the feature. e.g. Authorize, or IndexedDB
*
* Example:
* (start code)
* if (remoteStorage.hasFeature('LocalStorage')) {
* console.log('LocalStorage is enabled!');
* }
* (end code)
*
*/
hasFeature: function (feature) {
for (var i = this.features.length - 1; i >= 0; i--) {
if (this.features[i].name === feature) {
return this.features[i].supported;
}
}
return false;
},
/**
** GET/PUT/DELETE INTERFACE HELPERS
**/
_setGPD: function (impl, context) {
function wrap(func) {
return function () {
return func.apply(context, arguments)
.then(emitUnauthorized.bind(this));
};
}
this.get = wrap(impl.get);
this.put = wrap(impl.put);
this.delete = wrap(impl.delete);
},
_pendingGPD: function (methodName) {
return function () {
var pending = Promise.defer();
this._pending.push({
method: methodName,
args: Array.prototype.slice.call(arguments),
promise: pending
});
return pending.promise;
}.bind(this);
},
_processPending: function () {
this._pending.forEach(function (pending) {
try {
this[pending.method].apply(this, pending.args).then(pending.promise.resolve, pending.promise.reject);
} catch(e) {
pending.promise.reject(e);
}
}.bind(this));
this._pending = [];
},
/**
** CHANGE EVENT HANDLING
**/
_bindChange: function (object) {
object.on('change', this._dispatchEvent.bind(this, 'change'));
},
_dispatchEvent: function (eventName, event) {
var self = this;
Object.keys(this._pathHandlers[eventName]).forEach(function (path) {
var pl = path.length;
if (event.path.substr(0, pl) === path) {
self._pathHandlers[eventName][path].forEach(function (handler) {
var ev = {};
for (var key in event) { ev[key] = event[key]; }
ev.relativePath = event.path.replace(new RegExp('^' + path), '');
try {
handler(ev);
} catch(e) {
console.error("'change' handler failed: ", e, e.stack);
self._emit('error', e);
}
});
}
});
}
};
/**
* Property: connected
*
* Boolean property indicating if remoteStorage is currently connected.
*/
Object.defineProperty(RemoteStorage.prototype, 'connected', {
get: function () {
return this.remote.connected;
}
});
/**
* Property: access
*
* Tracking claimed access scopes. A <RemoteStorage.Access> instance.
*
*
* Property: caching
*
* Caching settings. A <RemoteStorage.Caching> instance.
*
* Not available in no-cache builds.
*
*
* Property: remote
*
* Access to the remote backend used. Usually a <RemoteStorage.WireClient>.
*
*
* Property: local
*
* Access to the local caching backend used. Usually either a
* <RemoteStorage.IndexedDB> or <RemoteStorage.LocalStorage> instance.
*
* Not available in no-cache builds.
*/
global.RemoteStorage = RemoteStorage;
if ((typeof module === 'object') && (typeof module.exports !== 'undefined')){
module.exports = RemoteStorage;
}
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: src/util.js **/
/**
* Class: RemoteStorage.Util
*
* Provides reusable utility functions at RemoteStorage.util
*
*/
(function (global) {
/**
* Function: fixArrayBuffers
*
* Takes an object and its copy as produced by the _deepClone function
* below, and finds and fixes any ArrayBuffers that were cast to `{}` instead
* of being cloned to new ArrayBuffers with the same content.
*
* It recurses into sub-objects, but skips arrays if they occur.
*/
function fixArrayBuffers(srcObj, dstObj) {
var field, srcArr, dstArr;
if (typeof(srcObj) !== 'object' || Array.isArray(srcObj) || srcObj === null) {
return;
}
for (field in srcObj) {
if (typeof(srcObj[field]) === 'object' && srcObj[field] !== null) {
if (srcObj[field].toString() === '[object ArrayBuffer]') {
dstObj[field] = new ArrayBuffer(srcObj[field].byteLength);
srcArr = new Int8Array(srcObj[field]);
dstArr = new Int8Array(dstObj[field]);
dstArr.set(srcArr);
} else {
fixArrayBuffers(srcObj[field], dstObj[field]);
}
}
}
}
RemoteStorage.util = {
getEventEmitter: function () {
var object = {};
var args = Array.prototype.slice.call(arguments);
args.unshift(object);
RemoteStorage.eventHandling.apply(RemoteStorage, args);
object.emit = object._emit;
return object;
},
extend: function (target) {
var sources = Array.prototype.slice.call(arguments, 1);
sources.forEach(function (source) {
for (var key in source) {
target[key] = source[key];
}
});
return target;
},
asyncEach: function (array, callback) {
return this.asyncMap(array, callback).
then(function () { return array; });
},
asyncMap: function (array, callback) {
var pending = Promise.defer();
var n = array.length, i = 0;
var results = [], errors = [];
function oneDone() {
i++;
if (i === n) {
pending.resolve(results, errors);
}
}
array.forEach(function (item, index) {
var result;
try {
result = callback(item);
} catch(exc) {
oneDone();
errors[index] = exc;
}
if (typeof(result) === 'object' && typeof(result.then) === 'function') {
result.then(function (res) { results[index] = res; oneDone(); },
function (error) { errors[index] = error; oneDone(); });
} else {
oneDone();
results[index] = result;
}
});
return pending.promise;
},
containingFolder: function (path) {
if (path === '') {
return '/';
}
if (! path) {
throw "Path not given!";
}
return path.replace(/\/+/g, '/').replace(/[^\/]+\/?$/, '');
},
isFolder: function (path) {
return path.substr(-1) === '/';
},
isDocument: function (path) {
return !RemoteStorage.util.isFolder(path);
},
baseName: function (path) {
var parts = path.split('/');
if (this.isFolder(path)) {
return parts[parts.length-2]+'/';
} else {
return parts[parts.length-1];
}
},
cleanPath: function (path) {
return path.replace(/\/+/g, '/')
.split('/').map(encodeURIComponent).join('/')
.replace(/'/g, '%27');
},
bindAll: function (object) {
for (var key in this) {
if (typeof(object[key]) === 'function') {
object[key] = object[key].bind(object);
}
}
},
equal: function (a, b, seen) {
var key;
seen = seen || [];
if (typeof(a) !== typeof(b)) {
return false;
}
if (typeof(a) === 'number' || typeof(a) === 'boolean' || typeof(a) === 'string') {
return a === b;
}
if (typeof(a) === 'function') {
return a.toString() === b.toString();
}
if (a instanceof ArrayBuffer && b instanceof ArrayBuffer) {
// Without the following conversion the browsers wouldn't be able to
// tell the ArrayBuffer instances apart.
a = new Uint8Array(a);
b = new Uint8Array(b);
}
// If this point has been reached, a and b are either arrays or objects.
if (a instanceof Array) {
if (a.length !== b.length) {
return false;
}
for (var i = 0, c = a.length; i < c; i++) {
if (!RemoteStorage.util.equal(a[i], b[i], seen)) {
return false;
}
}
} else {
// Check that keys from a exist in b
for (key in a) {
if (a.hasOwnProperty(key) && !(key in b)) {
return false;
}
}
// Check that keys from b exist in a, and compare the values
for (key in b) {
if (!b.hasOwnProperty(key)) {
continue;
}
if (!(key in a)) {
return false;
}
var seenArg;
if (typeof(b[key]) === 'object') {
if (seen.indexOf(b[key]) >= 0) {
// Circular reference, don't attempt to compare this object.
// If nothing else returns false, the objects match.
continue;
}
seenArg = seen.slice();
seenArg.push(b[key]);
}
if (!RemoteStorage.util.equal(a[key], b[key], seenArg)) {
return false;
}
}
}
return true;
},
equalObj: function (obj1, obj2) {
console.warn('DEPRECATION WARNING: RemoteStorage.util.equalObj has been replaced by RemoteStorage.util.equal.');
return RemoteStorage.util.equal(obj1, obj2);
},
deepClone: function (obj) {
var clone;
if (obj === undefined) {
return undefined;
} else {
clone = JSON.parse(JSON.stringify(obj));
fixArrayBuffers(obj, clone);
return clone;
}
},
pathsFromRoot: function (path) {
var paths = [path];
var parts = path.replace(/\/$/, '').split('/');
while (parts.length > 1) {
parts.pop();
paths.push(parts.join('/')+'/');
}
return paths;
},
/* jshint ignore:start */
md5sum: function(str) {
//
// http://www.myersdaily.org/joseph/javascript/md5.js
//
function md5cycle(x, k) {
var a = x[0], b = x[1], c = x[2], d = x[3];
a = ff(a, b, c, d, k[0], 7, -680876936);
d = ff(d, a, b, c, k[1], 12, -389564586);
c = ff(c, d, a, b, k[2], 17, 606105819);
b = ff(b, c, d, a, k[3], 22, -1044525330);
a = ff(a, b, c, d, k[4], 7, -176418897);
d = ff(d, a, b, c, k[5], 12, 1200080426);
c = ff(c, d, a, b, k[6], 17, -1473231341);
b = ff(b, c, d, a, k[7], 22, -45705983);
a = ff(a, b, c, d, k[8], 7, 1770035416);
d = ff(d, a, b, c, k[9], 12, -1958414417);
c = ff(c, d, a, b, k[10], 17, -42063);
b = ff(b, c, d, a, k[11], 22, -1990404162);
a = ff(a, b, c, d, k[12], 7, 1804603682);
d = ff(d, a, b, c, k[13], 12, -40341101);
c = ff(c, d, a, b, k[14], 17, -1502002290);
b = ff(b, c, d, a, k[15], 22, 1236535329);
a = gg(a, b, c, d, k[1], 5, -165796510);
d = gg(d, a, b, c, k[6], 9, -1069501632);
c = gg(c, d, a, b, k[11], 14, 643717713);
b = gg(b, c, d, a, k[0], 20, -373897302);
a = gg(a, b, c, d, k[5], 5, -701558691);
d = gg(d, a, b, c, k[10], 9, 38016083);
c = gg(c, d, a, b, k[15], 14, -660478335);
b = gg(b, c, d, a, k[4], 20, -405537848);
a = gg(a, b, c, d, k[9], 5, 568446438);
d = gg(d, a, b, c, k[14], 9, -1019803690);
c = gg(c, d, a, b, k[3], 14, -187363961);
b = gg(b, c, d, a, k[8], 20, 1163531501);
a = gg(a, b, c, d, k[13], 5, -1444681467);
d = gg(d, a, b, c, k[2], 9, -51403784);
c = gg(c, d, a, b, k[7], 14, 1735328473);
b = gg(b, c, d, a, k[12], 20, -1926607734);
a = hh(a, b, c, d, k[5], 4, -378558);
d = hh(d, a, b, c, k[8], 11, -2022574463);
c = hh(c, d, a, b, k[11], 16, 1839030562);
b = hh(b, c, d, a, k[14], 23, -35309556);
a = hh(a, b, c, d, k[1], 4, -1530992060);
d = hh(d, a, b, c, k[4], 11, 1272893353);
c = hh(c, d, a, b, k[7], 16, -155497632);
b = hh(b, c, d, a, k[10], 23, -1094730640);
a = hh(a, b, c, d, k[13], 4, 681279174);
d = hh(d, a, b, c, k[0], 11, -358537222);
c = hh(c, d, a, b, k[3], 16, -722521979);
b = hh(b, c, d, a, k[6], 23, 76029189);
a = hh(a, b, c, d, k[9], 4, -640364487);
d = hh(d, a, b, c, k[12], 11, -421815835);
c = hh(c, d, a, b, k[15], 16, 530742520);
b = hh(b, c, d, a, k[2], 23, -995338651);
a = ii(a, b, c, d, k[0], 6, -198630844);
d = ii(d, a, b, c, k[7], 10, 1126891415);
c = ii(c, d, a, b, k[14], 15, -1416354905);
b = ii(b, c, d, a, k[5], 21, -57434055);
a = ii(a, b, c, d, k[12], 6, 1700485571);
d = ii(d, a, b, c, k[3], 10, -1894986606);
c = ii(c, d, a, b, k[10], 15, -1051523);
b = ii(b, c, d, a, k[1], 21, -2054922799);
a = ii(a, b, c, d, k[8], 6, 1873313359);
d = ii(d, a, b, c, k[15], 10, -30611744);
c = ii(c, d, a, b, k[6], 15, -1560198380);
b = ii(b, c, d, a, k[13], 21, 1309151649);
a = ii(a, b, c, d, k[4], 6, -145523070);
d = ii(d, a, b, c, k[11], 10, -1120210379);
c = ii(c, d, a, b, k[2], 15, 718787259);
b = ii(b, c, d, a, k[9], 21, -343485551);
x[0] = add32(a, x[0]);
x[1] = add32(b, x[1]);
x[2] = add32(c, x[2]);
x[3] = add32(d, x[3]);
}
function cmn(q, a, b, x, s, t) {
a = add32(add32(a, q), add32(x, t));
return add32((a << s) | (a >>> (32 - s)), b);
}
function ff(a, b, c, d, x, s, t) {
return cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function gg(a, b, c, d, x, s, t) {
return cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function hh(a, b, c, d, x, s, t) {
return cmn(b ^ c ^ d, a, b, x, s, t);
}
function ii(a, b, c, d, x, s, t) {
return cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function md51(s) {
txt = '';
var n = s.length,
state = [1732584193, -271733879, -1732584194, 271733878], i;
for (i=64; i<=s.length; i+=64) {
md5cycle(state, md5blk(s.substring(i-64, i)));
}
s = s.substring(i-64);
var tail = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0];
for (i=0; i<s.length; i++)
tail[i>>2] |= s.charCodeAt(i) << ((i%4) << 3);
tail[i>>2] |= 0x80 << ((i%4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i=0; i<16; i++) tail[i] = 0;
}
tail[14] = n*8;
md5cycle(state, tail);
return state;
}
function md5blk(s) {
var md5blks = [], i;
for (i=0; i<64; i+=4) {
md5blks[i>>2] = s.charCodeAt(i) + (s.charCodeAt(i+1) << 8) + (s.charCodeAt(i+2) << 16) + (s.charCodeAt(i+3) << 24);
}
return md5blks;
}
var hex_chr = '0123456789abcdef'.split('');
function rhex(n)
{
var s='', j=0;
for(; j<4; j++)
s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
return s;
}
function hex(x) {
for (var i=0; i<x.length; i++)
x[i] = rhex(x[i]);
return x.join('');
}
function md5(s) {
return hex(md51(s));
}
var add32 = function (a, b) {
return (a + b) & 0xFFFFFFFF;
};
if (md5('hello') !== '5d41402abc4b2a76b9719d911017c592') {
add32 = function (x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
};
}
return md5(str);
},
/* jshint ignore:end */
localStorageAvailable: function() {
if (!('localStorage' in global)) { return false }
try {
global.localStorage.setItem('rs-check', 1);
global.localStorage.removeItem('rs-check');
return true;
} catch(error) {
return false;
}
}
};
if (!RemoteStorage.prototype.util) {
Object.defineProperty(RemoteStorage.prototype, 'util', {
get: function () {
console.log('DEPRECATION WARNING: remoteStorage.util was moved to RemoteStorage.util');
return RemoteStorage.util;
}
});
}
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: src/eventhandling.js **/
(function (global) {
/**
* Interface: eventhandling
*/
var methods = {
/**
* Method: addEventListener
*
* Install an event handler for the given event name
*/
addEventListener: function (eventName, handler) {
if (typeof(eventName) !== 'string') {
throw new Error('Argument eventName should be a string');
}
if (typeof(handler) !== 'function') {
throw new Error('Argument handler should be a function');
}
RemoteStorage.log('[Eventhandling] Adding event listener', eventName, handler);
this._validateEvent(eventName);
this._handlers[eventName].push(handler);
},
/**
* Method: removeEventListener
*
* Remove a previously installed event handler
*/
removeEventListener: function (eventName, handler) {
this._validateEvent(eventName);
var hl = this._handlers[eventName].length;
for (var i=0;i<hl;i++) {
if (this._handlers[eventName][i] === handler) {
this._handlers[eventName].splice(i, 1);
return;
}
}
},
_emit: function (eventName) {
this._validateEvent(eventName);
var args = Array.prototype.slice.call(arguments, 1);
this._handlers[eventName].slice().forEach(function (handler) {
handler.apply(this, args);
});
},
_validateEvent: function (eventName) {
if (! (eventName in this._handlers)) {
throw new Error("Unknown event: " + eventName);
}
},
_delegateEvent: function (eventName, target) {
target.on(eventName, function (event) {
this._emit(eventName, event);
}.bind(this));
},
_addEvent: function (eventName) {
this._handlers[eventName] = [];
}
};
/**
* Method: eventhandling.on
*
* Alias for <addEventListener>
**/
methods.on = methods.addEventListener;
/**
* Function: eventHandling
*
* Mixes event handling functionality into an object.
*
* The first parameter is always the object to be extended.
* All remaining parameter are expected to be strings, interpreted as valid event
* names.
*
* Example:
* (start code)
* var MyConstructor = function () {
* eventHandling(this, 'connected', 'disconnected');
*
* this._emit('connected');
* this._emit('disconnected');
* // This would throw an exception:
* // this._emit('something-else');
* };
*
* var myObject = new MyConstructor();
* myObject.on('connected', function () { console.log('connected'); });
* myObject.on('disconnected', function () { console.log('disconnected'); });
* // This would throw an exception as well:
* // myObject.on('something-else', function () {});
* (end code)
*/
RemoteStorage.eventHandling = function (object) {
var eventNames = Array.prototype.slice.call(arguments, 1);
for (var key in methods) {
object[key] = methods[key];
}
object._handlers = {};
eventNames.forEach(function (eventName) {
object._addEvent(eventName);
});
};
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: src/wireclient.js **/
(function (global) {
var RS = RemoteStorage;
/**
* Class: RemoteStorage.WireClient
*
* WireClient Interface
* --------------------
*
* This file exposes a get/put/delete interface on top of XMLHttpRequest.
* It requires to be configured with parameters about the remotestorage server to
* connect to.
* Each instance of WireClient is always associated with a single remotestorage
* server and access token.
*
* Usually the WireClient instance can be accessed via `remoteStorage.remote`.
*
* This is the get/put/delete interface:
*
* - #get() takes a path and optionally a ifNoneMatch option carrying a version
* string to check. It returns a promise that will be fulfilled with the HTTP
* response status, the response body, the MIME type as returned in the
* 'Content-Type' header and the current revision, as returned in the 'ETag'
* header.
* - #put() takes a path, the request body and a content type string. It also
* accepts the ifMatch and ifNoneMatch options, that map to the If-Match and
* If-None-Match headers respectively. See the remotestorage-01 specification
* for details on handling these headers. It returns a promise, fulfilled with
* the same values as the one for #get().
* - #delete() takes a path and the ifMatch option as well. It returns a promise
* fulfilled with the same values as the one for #get().
*
* In addition to this, the WireClient has some compatibility features to work with
* remotestorage 2012.04 compatible storages. For example it will cache revisions
* from folder listings in-memory and return them accordingly as the "revision"
* parameter in response to #get() requests. Similarly it will return 404 when it
* receives an empty folder listing, to mimic remotestorage-01 behavior. Note
* that it is not always possible to know the revision beforehand, hence it may
* be undefined at times (especially for caching-roots).
*/
var hasLocalStorage;
var SETTINGS_KEY = 'remotestorage:wireclient';
var API_2012 = 1, API_00 = 2, API_01 = 3, API_02 = 4, API_HEAD = 5;
var STORAGE_APIS = {
'draft-dejong-remotestorage-00': API_00,
'draft-dejong-remotestorage-01': API_01,
'draft-dejong-remotestorage-02': API_02,
'https://www.w3.org/community/rww/wiki/read-write-web-00#simple': API_2012
};
var isArrayBufferView;
if (typeof(ArrayBufferView) === 'function') {
isArrayBufferView = function (object) { return object && (object instanceof ArrayBufferView); };
} else {
var arrayBufferViews = [
Int8Array, Uint8Array, Int16Array, Uint16Array,
Int32Array, Uint32Array, Float32Array, Float64Array
];
isArrayBufferView = function (object) {
for (var i=0;i<8;i++) {
if (object instanceof arrayBufferViews[i]) {
return true;
}
}
return false;
};
}
var isFolder = RemoteStorage.util.isFolder;
var cleanPath = RemoteStorage.util.cleanPath;
function addQuotes(str) {
if (typeof(str) !== 'string') {
return str;
}
if (str === '*') {
return '*';
}
return '"' + str + '"';
}
function stripQuotes(str) {
if (typeof(str) !== 'string') {
return str;
}
return str.replace(/^["']|["']$/g, '');
}
function readBinaryData(content, mimeType, callback) {
var blob;
global.BlobBuilder = global.BlobBuilder || global.WebKitBlobBuilder;
if (typeof global.BlobBuilder !== 'undefined') {
var bb = new global.BlobBuilder();
bb.append(content);
blob = bb.getBlob(mimeType);
} else {
blob = new Blob([content], { type: mimeType });
}
var reader = new FileReader();
if (typeof reader.addEventListener === 'function') {
reader.addEventListener('loadend', function () {
callback(reader.result); // reader.result contains the contents of blob as a typed array
});
} else {
reader.onloadend = function() {
callback(reader.result); // reader.result contains the contents of blob as a typed array
};
}
reader.readAsArrayBuffer(blob);
}
function getTextFromArrayBuffer(arrayBuffer, encoding) {
var pending = Promise.defer();
if (typeof Blob === 'undefined') {
var buffer = new Buffer(new Uint8Array(arrayBuffer));
pending.resolve(buffer.toString(encoding));
} else {
var blob;
global.BlobBuilder = global.BlobBuilder || global.WebKitBlobBuilder;
if (typeof global.BlobBuilder !== 'undefined') {
var bb = new global.BlobBuilder();
bb.append(arrayBuffer);
blob = bb.getBlob();
} else {
blob = new Blob([arrayBuffer]);
}
var fileReader = new FileReader();
if (typeof fileReader.addEventListener === 'function') {
fileReader.addEventListener('loadend', function (evt) {
pending.resolve(evt.target.result);
});
} else {
fileReader.onloadend = function(evt) {
pending.resolve(evt.target.result);
};
}
fileReader.readAsText(blob, encoding);
}
return pending.promise;
}
function determineCharset(mimeType) {
var charset = 'UTF-8';
var charsetMatch;
if (mimeType) {
charsetMatch = mimeType.match(/charset=(.+)$/);
if (charsetMatch) {
charset = charsetMatch[1];
}
}
return charset;
}
function isFolderDescription(body) {
return ((body['@context'] === 'http://remotestorage.io/spec/folder-description')
&& (typeof(body['items']) === 'object'));
}
function isSuccessStatus(status) {
return [201, 204, 304].indexOf(status) >= 0;
}
function isErrorStatus(status) {
return [401, 403, 404, 412].indexOf(status) >= 0;
}
var onErrorCb;
/**
* Class : RemoteStorage.WireClient
**/
RS.WireClient = function (rs) {
this.connected = false;
/**
* Event: change
* Never fired for some reason
* # TODO create issue and fix or remove
*
* Event: connected
* Fired when the wireclient connect method realizes that it is in
* possession of a token and href
**/
RS.eventHandling(this, 'change', 'connected', 'wire-busy', 'wire-done', 'not-connected');
onErrorCb = function (error){
if (error instanceof RemoteStorage.Unauthorized) {
this.configure({token: null});
}
}.bind(this);
rs.on('error', onErrorCb);
if (hasLocalStorage) {
var settings;
try { settings = JSON.parse(localStorage[SETTINGS_KEY]); } catch(e) {}
if (settings) {
setTimeout(function () {
this.configure(settings);
}.bind(this), 0);
}
}
this._revisionCache = {};
if (this.connected) {
setTimeout(this._emit.bind(this), 0, 'connected');
}
};
RS.WireClient.REQUEST_TIMEOUT = 30000;
RS.WireClient.prototype = {
/**
* Property: token
*
* Holds the bearer token of this WireClient, as obtained in the OAuth dance
*
* Example:
* (start code)
*
* remoteStorage.remote.token
* // -> 'DEADBEEF01=='
*/
/**
* Property: href
*
* Holds the server's base URL, as obtained in the Webfinger discovery
*
* Example:
* (start code)
*
* remoteStorage.remote.href
* // -> 'https://storage.example.com/users/jblogg/'
*/
/**
* Property: storageApi
*
* Holds the spec version the server claims to be compatible with
*
* Example:
* (start code)
*
* remoteStorage.remote.storageApi
* // -> 'draft-dejong-remotestorage-01'
*/
_request: function (method, uri, token, headers, body, getEtag, fakeRevision) {
if ((method === 'PUT' || method === 'DELETE') && uri[uri.length - 1] === '/') {
return Promise.reject('Don\'t ' + method + ' on directories!');
}
var revision;
var reqType;
var self = this;
if (token !== RemoteStorage.Authorize.IMPLIED_FAKE_TOKEN) {
headers['Authorization'] = 'Bearer ' + token;
}
this._emit('wire-busy', {
method: method,
isFolder: isFolder(uri)
});
return RS.WireClient.request(method, uri, {
body: body,
headers: headers,
responseType: 'arraybuffer'
}).then(function (response) {
self._emit('wire-done', {
method: method,
isFolder: isFolder(uri),
success: true
});
self.online = true;
if (isErrorStatus(response.status)) {
RemoteStorage.log('[WireClient] Error response status', response.status);
if (getEtag) {
revision = stripQuotes(response.getResponseHeader('ETag'));
} else {
revision = undefined;
}
return Promise.resolve({statusCode: response.status, revision: revision});
} else if (isSuccessStatus(response.status) ||
(response.status === 200 && method !== 'GET')) {
revision = stripQuotes(response.getResponseHeader('ETag'));
RemoteStorage.log('[WireClient] Successful request', revision);
return Promise.resolve({statusCode: response.status, revision: revision});
} else {
var mimeType = response.getResponseHeader('Content-Type');
var body;
if (getEtag) {
revision = stripQuotes(response.getResponseHeader('ETag'));
} else {
revision = response.status === 200 ? fakeRevision : undefined;
}
var charset = determineCharset(mimeType);
if ((!mimeType) || charset === 'binary') {
RemoteStorage.log('[WireClient] Successful request with unknown or binary mime-type', revision);
return Promise.resolve({statusCode: response.status, body: response.response, contentType: mimeType, revision: revision});
} else {
return getTextFromArrayBuffer(response.response, charset).then(function (body) {
RemoteStorage.log('[WireClient] Successful request', revision);
return Promise.resolve({statusCode: response.status, body: body, contentType: mimeType, revision: revision});
});
}
}
}, function (error) {
self._emit('wire-done', {
method: method,
isFolder: isFolder(uri),
success: false
});
return Promise.reject(error);
});
},
/**
*
* Method: configure
*
* Sets the userAddress, href, storageApi, token, and properties of a
* remote store. Also sets connected and online to true and emits the
* 'connected' event, if both token and href are present.
*
* Parameters:
* settings - An object that may contain userAddress (string or null),
* href (string or null), storageApi (string or null), token (string
* or null), and/or properties (the JSON-parsed properties object
* from the user's WebFinger record, see section 10 of
* http://tools.ietf.org/html/draft-dejong-remotestorage-03
* or null).
* Fields that are not included (i.e. `undefined`), stay at
* their current value. To set a field, include that field
* with a `string` value. To reset a field, for instance when
* the user disconnected their storage, or you found that the
* token you have has expired, simply set that field to `null`.
*/
configure: function (settings) {
if (typeof settings !== 'object') {
throw new Error('WireClient configure settings parameter should be an object');
}
if (typeof settings.userAddress !== 'undefined') {
this.userAddress = settings.userAddress;
}
if (typeof settings.href !== 'undefined') {
this.href = settings.href;
}
if (typeof settings.storageApi !== 'undefined') {
this.storageApi = settings.storageApi;
}
if (typeof settings.token !== 'undefined') {
this.token = settings.token;
}
if (typeof settings.properties !== 'undefined') {
this.properties = settings.properties;
}
if (typeof this.storageApi !== 'undefined') {
this._storageApi = STORAGE_APIS[this.storageApi] || API_HEAD;
this.supportsRevs = this._storageApi >= API_00;
}
if (this.href && this.token) {
this.connected = true;
this.online = true;
this._emit('connected');
} else {
this.connected = false;
}
if (hasLocalStorage) {
localStorage[SETTINGS_KEY] = JSON.stringify({
userAddress: this.userAddress,
href: this.href,
storageApi: this.storageApi,
token: this.token,
properties: this.properties
});
}
},
stopWaitingForToken: function () {
if (!this.connected) {
this._emit('not-connected');
}
},
get: function (path, options) {
var self = this;
if (!this.connected) {
return Promise.reject('not connected (path: ' + path + ')');
}
if (!options) { options = {}; }
var headers = {};
if (this.supportsRevs) {
if (options.ifNoneMatch) {
headers['If-None-Match'] = addQuotes(options.ifNoneMatch);
}
} else if (options.ifNoneMatch) {
var oldRev = this._revisionCache[path];
}
return this._request('GET', this.href + cleanPath(path), this.token, headers,
undefined, this.supportsRevs, this._revisionCache[path])
.then(function (r) {
if (!isFolder(path)) {
return Promise.resolve(r);
}
var itemsMap = {};
if (typeof(r.body) !== 'undefined') {
try {
r.body = JSON.parse(r.body);
} catch (e) {
return Promise.reject('Folder description at ' + self.href + cleanPath(path) + ' is not JSON');
}
}
if (r.statusCode === 200 && typeof(r.body) === 'object') {
// New folder listing received
if (Object.keys(r.body).length === 0) {
// Empty folder listing of any spec
r.statusCode = 404;
} else if (isFolderDescription(r.body)) {
// >= 02 spec
for (var item in r.body.items) {
self._revisionCache[path + item] = r.body.items[item].ETag;
}
itemsMap = r.body.items;
} else {
// < 02 spec
Object.keys(r.body).forEach(function (key){
self._revisionCache[path + key] = r.body[key];
itemsMap[key] = {'ETag': r.body[key]};
});
}
r.body = itemsMap;
return Promise.resolve(r);
} else {
return Promise.resolve(r);
}
});
},
put: function (path, body, contentType, options) {
if (!this.connected) {
return Promise.reject('not connected (path: ' + path + ')');
}
if (!options) { options = {}; }
if ((!contentType.match(/charset=/)) && (body instanceof ArrayBuffer || isArrayBufferView(body))) {
contentType += '; charset=binary';
}
var headers = { 'Content-Type': contentType };
if (this.supportsRevs) {
if (options.ifMatch) {
headers['If-Match'] = addQuotes(options.ifMatch);
}
if (options.ifNoneMatch) {
headers['If-None-Match'] = addQuotes(options.ifNoneMatch);
}
}
return this._request('PUT', this.href + cleanPath(path), this.token,
headers, body, this.supportsRevs);
},
'delete': function (path, options) {
if (!this.connected) {
throw new Error('not connected (path: ' + path + ')');
}
if (!options) { options = {}; }
var headers = {};
if (this.supportsRevs) {
if (options.ifMatch) {
headers['If-Match'] = addQuotes(options.ifMatch);
}
}
return this._request('DELETE', this.href + cleanPath(path), this.token,
headers,
undefined, this.supportsRevs);
}
};
// Shared cleanPath used by Dropbox
RS.WireClient.cleanPath = cleanPath;
// Shared isArrayBufferView used by WireClient and Dropbox
RS.WireClient.isArrayBufferView = isArrayBufferView;
RS.WireClient.readBinaryData = readBinaryData;
// Shared request function used by WireClient, GoogleDrive and Dropbox.
RS.WireClient.request = function (method, url, options) {
var pending = Promise.defer();
RemoteStorage.log('[WireClient]', method, url);
var timedOut = false;
var timer = setTimeout(function () {
timedOut = true;
pending.reject('timeout');
}, RS.WireClient.REQUEST_TIMEOUT);
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
if (options.responseType) {
xhr.responseType = options.responseType;
}
if (options.headers) {
for (var key in options.headers) {
xhr.setRequestHeader(key, options.headers[key]);
}
}
xhr.onload = function () {
if (timedOut) { return; }
clearTimeout(timer);
pending.resolve(xhr);
};
xhr.onerror = function (error) {
if (timedOut) { return; }
clearTimeout(timer);
pending.reject(error);
};
var body = options.body;
if (typeof(body) === 'object' && !isArrayBufferView(body) && body instanceof ArrayBuffer) {
body = new Uint8Array(body);
}
xhr.send(body);
return pending.promise;
};
Object.defineProperty(RemoteStorage.WireClient.prototype, 'storageType', {
get: function () {
if (this.storageApi) {
var spec = this.storageApi.match(/draft-dejong-(remotestorage-\d\d)/);
return spec ? spec[1] : '2012.04';
}
}
});
RS.WireClient._rs_init = function (remoteStorage) {
hasLocalStorage = RemoteStorage.util.localStorageAvailable();
remoteStorage.remote = new RS.WireClient(remoteStorage);
this.online = true;
};
RS.WireClient._rs_supported = function () {
return !! global.XMLHttpRequest;
};
RS.WireClient._rs_cleanup = function (remoteStorage){
if (hasLocalStorage){
delete localStorage[SETTINGS_KEY];
}
remoteStorage.removeEventListener('error', onErrorCb);
};
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: src/discover.js **/
(function (global) {
// feature detection flags
var haveXMLHttpRequest, hasLocalStorage;
// used to store settings in localStorage
var SETTINGS_KEY = 'remotestorage:discover';
// cache loaded from localStorage
var cachedInfo = {};
/**
* Class: RemoteStorage.Discover
*
* This function deals with the Webfinger lookup, discovering a connecting
* user's storage details.
*
* The discovery timeout can be configured via
* `RemoteStorage.config.discoveryTimeout` (in ms).
*
* Arguments:
*
* userAddress - user@host
*
* Returns:
*
* A promise for an object with the following properties.
*
* href - Storage base URL,
* storageType - Storage type,
* authUrl - OAuth URL,
* properties - Webfinger link properties
**/
RemoteStorage.Discover = function (userAddress) {
if (userAddress in cachedInfo) {
return Promise.resolve(cachedInfo[userAddress]);
}
var webFinger = new WebFinger({
tls_only: false,
uri_fallback: true,
request_timeout: 5000
});
var pending = Promise.defer();
webFinger.lookup(userAddress, function (err, response) {
if (err) {
return pending.reject(err.message);
} else if ((typeof response.idx.links.remotestorage !== 'object') ||
(typeof response.idx.links.remotestorage.length !== 'number') ||
(response.idx.links.remotestorage.length <= 0)) {
RemoteStorage.log("[Discover] WebFinger record for " + userAddress + " does not have remotestorage defined in the links section ", JSON.stringify(response.json));
return pending.reject("WebFinger record for " + userAddress + " does not have remotestorage defined in the links section.");
}
var rs = response.idx.links.remotestorage[0];
var authURL = rs.properties['http://tools.ietf.org/html/rfc6749#section-4.2'] ||
rs.properties['auth-endpoint'];
var storageType = rs.properties['http://remotestorage.io/spec/version'] ||
rs.type;
// cache fetched data
cachedInfo[userAddress] = { href: rs.href, storageType: storageType, authURL: authURL, properties: rs.properties };
if (hasLocalStorage) {
localStorage[SETTINGS_KEY] = JSON.stringify({ cache: cachedInfo });
}
return pending.resolve(cachedInfo[userAddress]);
});
return pending.promise;
};
RemoteStorage.Discover._rs_init = function (remoteStorage) {
hasLocalStorage = RemoteStorage.util.localStorageAvailable();
if (hasLocalStorage) {
var settings;
try { settings = JSON.parse(localStorage[SETTINGS_KEY]); } catch(e) {}
if (settings) {
cachedInfo = settings.cache;
}
}
};
RemoteStorage.Discover._rs_supported = function () {
haveXMLHttpRequest = !! global.XMLHttpRequest;
return haveXMLHttpRequest;
};
RemoteStorage.Discover._rs_cleanup = function () {
if (hasLocalStorage) {
delete localStorage[SETTINGS_KEY];
}
};
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: node_modules/webfinger.js/src/webfinger.js **/
/* global define */
/*!
* webfinger.js
* version 2.3.2
* http://github.com/silverbucket/webfinger.js
*
* Developed and Maintained by:
* Nick Jennings <[email protected]> 2012 - 2014
*
* webfinger.js is released under the AGPL (see LICENSE).
*
* You don't have to do anything special to choose one license or the other and you don't
* have to notify anyone which license you are using.
* Please see the corresponding license file for details of these licenses.
* You are free to use, modify and distribute this software, but all copyright
* information must remain.
*
*/
if (typeof XMLHttpRequest === 'undefined') {
XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
}
(function (undefined) {
// URI to property name map
var LINK_URI_MAPS = {
'http://webfist.org/spec/rel': 'webfist',
'http://webfinger.net/rel/avatar': 'avatar',
'remotestorage': 'remotestorage',
'http://tools.ietf.org/id/draft-dejong-remotestorage': 'remotestorage',
'remoteStorage': 'remotestorage',
'http://www.packetizer.com/rel/share': 'share',
'http://webfinger.net/rel/profile-page': 'profile',
'me': 'profile',
'vcard': 'vcard',
'blog': 'blog',
'http://packetizer.com/rel/blog': 'blog',
'http://schemas.google.com/g/2010#updates-from': 'updates',
'https://camlistore.org/rel/server': 'camilstore'
};
var LINK_PROPERTIES = {
'avatar': [],
'remotestorage': [],
'blog': [],
'vcard': [],
'updates': [],
'share': [],
'profile': [],
'webfist': [],
'camlistore': []
};
// list of endpoints to try, fallback from beginning to end.
var URIS = ['webfinger', 'host-meta', 'host-meta.json'];
function generateErrorObject(obj) {
obj.toString = function () {
return this.message;
};
return obj;
}
// given a URL ensures it's HTTPS.
// returns false for null string or non-HTTPS URL.
function isSecure(url) {
if (typeof url !== 'string') {
return false;
}
var parts = url.split('://');
if (parts[0] === 'https') {
return true;
}
return false;
}
/**
* Function: WebFinger
*
* WebFinger constructor
*
* Returns:
*
* return WebFinger object
*/
function WebFinger(config) {
if (typeof config !== 'object') {
config = {};
}
this.config = {
tls_only: (typeof config.tls_only !== 'undefined') ? config.tls_only : true,
webfist_fallback: (typeof config.webfist_fallback !== 'undefined') ? config.webfist_fallback : false,
uri_fallback: (typeof config.uri_fallback !== 'undefined') ? config.uri_fallback : false,
request_timeout: (typeof config.request_timeout !== 'undefined') ? config.request_timeout : 10000
};
}
// make an http request and look for JRD response, fails if request fails
// or response not json.
WebFinger.prototype.__fetchJRD = function (_url, errorHandler, sucessHandler) {
var self = this;
function __makeRequest(url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
if (self.__isValidJSON(xhr.responseText)) {
return sucessHandler(xhr.responseText);
} else {
return errorHandler(generateErrorObject({
message: 'invalid json',
url: url,
status: xhr.status
}));
}
} else if (xhr.status === 404) {
return errorHandler(generateErrorObject({
message: 'endpoint unreachable',
url: url,
status: xhr.status
}));
} else if ((xhr.status >= 301) && (xhr.status <= 302)) {
var location = xhr.getResponseHeader('Location');
if (isSecure(location)) {
return __makeRequest(location); // follow redirect
} else {
return errorHandler(generateErrorObject({
message: 'no redirect URL found',
url: url,
status: xhr.status
}));
}
} else {
return errorHandler(generateErrorObject({
message: 'error during request',
url: url,
status: xhr.status
}));
}
}
};
xhr.open('GET', url, true);
xhr.setRequestHeader('Accept', 'application/jrd+json, application/json');
xhr.send();
}
return __makeRequest(_url);
};
WebFinger.prototype.__isValidJSON = function (str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
};
WebFinger.prototype.__isLocalhost = function (host) {
var local = /^localhost(\.localdomain)?(\:[0-9]+)?$/;
return local.test(host);
};
// processes JRD object as if it's a webfinger response object
// looks for known properties and adds them to profile datat struct.
WebFinger.prototype.__processJRD = function (JRD, errorHandler, successHandler) {
var parsedJRD = JSON.parse(JRD);
if ((typeof parsedJRD !== 'object') ||
(typeof parsedJRD.links !== 'object')) {
if (typeof parsedJRD.error !== 'undefined') {
return errorHandler(generateErrorObject({ message: parsedJRD.error }));
} else {
return errorHandler(generateErrorObject({ message: 'unknown response from server' }));
}
return false;
}
var links = parsedJRD.links;
var result = { // webfinger JRD - object, json, and our own indexing
object: parsedJRD,
json: JRD,
idx: {}
};
result.idx.properties = {
'name': undefined
};
result.idx.links = JSON.parse(JSON.stringify(LINK_PROPERTIES));
// process links
links.map(function (link, i) {
if (LINK_URI_MAPS.hasOwnProperty(link.rel)) {
if (result.idx.links[LINK_URI_MAPS[link.rel]]) {
var entry = {};
Object.keys(link).map(function (item, n) {
entry[item] = link[item];
});
result.idx.links[LINK_URI_MAPS[link.rel]].push(entry);
}
}
});
// process properties
var props = JSON.parse(JRD).properties;
for (var key in props) {
if (props.hasOwnProperty(key)) {
if (key === 'http://packetizer.com/ns/name') {
result.idx.properties.name = props[key];
}
}
}
return successHandler(result);
};
WebFinger.prototype.lookup = function (address, cb) {
if (typeof address !== 'string') {
throw new Error('first parameter must be a user address');
} else if (typeof cb !== 'function') {
throw new Error('second parameter must be a callback');
}
var self = this;
var parts = address.replace(/ /g,'').split('@');
var host = parts[1]; // host name for this useraddress
var uri_index = 0; // track which URIS we've tried already
var protocol = 'https'; // we use https by default
if (parts.length !== 2) {
return cb(generateErrorObject({ message: 'invalid user address ' + address + ' ( expected format: [email protected] )' }));
} else if (self.__isLocalhost(host)) {
protocol = 'http';
}
function __buildURL() {
return protocol + '://' + host + '/.well-known/' +
URIS[uri_index] + '?resource=acct:' + address;
}
// control flow for failures, what to do in various cases, etc.
function __fallbackChecks(err) {
if ((self.config.uri_fallback) && (host !== 'webfist.org') && (uri_index !== URIS.length - 1)) { // we have uris left to try
uri_index = uri_index + 1;
return __call();
} else if ((!self.config.tls_only) && (protocol === 'https')) { // try normal http
uri_index = 0;
protocol = 'http';
return __call();
} else if ((self.config.webfist_fallback) && (host !== 'webfist.org')) { // webfist attempt
uri_index = 0;
protocol = 'http';
host = 'webfist.org';
// webfist will
// 1. make a query to the webfist server for the users account
// 2. from the response, get a link to the actual webfinger json data
// (stored somewhere in control of the user)
// 3. make a request to that url and get the json
// 4. process it like a normal webfinger response
self.__fetchJRD(__buildURL(), cb, function (data) { // get link to users JRD
self.__processJRD(data, cb, function (result) {
if ((typeof result.idx.links.webfist === 'object') &&
(typeof result.idx.links.webfist[0].href === 'string')) {
self.__fetchJRD(result.idx.links.webfist[0].href, cb, function (JRD) {
self.__processJRD(JRD, cb, function (result) {
return cb(null, cb);
});
});
}
});
});
} else {
return cb(err);
}
}
function __call() {
// make request
self.__fetchJRD(__buildURL(), __fallbackChecks, function (JRD) {
self.__processJRD(JRD, cb, function (result) { cb(null, result); });
});
}
return setTimeout(__call, 0);
};
WebFinger.prototype.lookupLink = function (address, rel, cb) {
if (LINK_PROPERTIES.hasOwnProperty(rel)) {
this.lookup(address, function (err, p) {
var links = p.idx.links[rel];
if (err) {
return cb(err);
} else if (links.length === 0) {
return cb('no links found with rel="' + rel + '"');
} else {
return cb(null, links[0]);
}
});
} else {
return cb('unsupported rel ' + rel);
}
};
if (typeof window === 'object') {
window.WebFinger = WebFinger;
} else if (typeof (define) === 'function' && define.amd) {
define([], function () { return WebFinger; });
} else {
try {
module.exports = WebFinger;
} catch (e) {}
}
})();
/** FILE: src/authorize.js **/
(function (global) {
function extractParams(url) {
//FF already decodes the URL fragment in document.location.hash, so use this instead:
var location = url || RemoteStorage.Authorize.getLocation().href,
hashPos = location.indexOf('#'),
hash;
if (hashPos === -1) { return; }
hash = location.substring(hashPos+1);
// if hash is not of the form #key=val&key=val, it's probably not for us
if (hash.indexOf('=') === -1) { return; }
return hash.split('&').reduce(function (params, kvs) {
var kv = kvs.split('=');
if (kv[0] === 'state' && kv[1].match(/rsDiscovery/)) {
// extract rsDiscovery data from the state param
var stateValue = decodeURIComponent(kv[1]);
var encodedData = stateValue.substr(stateValue.indexOf('rsDiscovery='))
.split('&')[0]
.split('=')[1];
params['rsDiscovery'] = JSON.parse(atob(encodedData));
// remove rsDiscovery param
stateValue = stateValue.replace(new RegExp('\&?rsDiscovery=' + encodedData), '');
if (stateValue.length > 0) {
params['state'] = stateValue;
}
} else {
params[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
}
return params;
}, {});
}
RemoteStorage.ImpliedAuth = function (storageApi, redirectUri) {
RemoteStorage.log('ImpliedAuth proceeding due to absent authURL; storageApi = ' + storageApi + ' redirectUri = ' + redirectUri);
// Set a fixed access token, signalling to not send it as Bearer
remoteStorage.remote.configure({
token: RemoteStorage.Authorize.IMPLIED_FAKE_TOKEN
});
document.location = redirectUri;
};
RemoteStorage.Authorize = function (remoteStorage, authURL, scope, redirectUri, clientId) {
RemoteStorage.log('[Authorize] authURL = ', authURL, 'scope = ', scope, 'redirectUri = ', redirectUri, 'clientId = ', clientId);
// keep track of the discovery data during redirect if we can't save it in localStorage
if (!RemoteStorage.util.localStorageAvailable() &&
remoteStorage.backend === 'remotestorage') {
redirectUri += redirectUri.indexOf('#') > 0 ? '&' : '#';
var discoveryData = {
userAddress: remoteStorage.remote.userAddress,
href: remoteStorage.remote.href,
storageApi: remoteStorage.remote.storageApi,
properties: remoteStorage.remote.properties
};
redirectUri += 'rsDiscovery=' + btoa(JSON.stringify(discoveryData));
}
var url = authURL, hashPos = redirectUri.indexOf('#');
url += authURL.indexOf('?') > 0 ? '&' : '?';
url += 'redirect_uri=' + encodeURIComponent(redirectUri.replace(/#.*$/, ''));
url += '&scope=' + encodeURIComponent(scope);
url += '&client_id=' + encodeURIComponent(clientId);
if (hashPos !== - 1 && hashPos+1 !== redirectUri.length) {
url += '&state=' + encodeURIComponent(redirectUri.substring(hashPos+1));
}
url += '&response_type=token';
if (global.cordova) {
return RemoteStorage.Authorize.openWindow(
url,
redirectUri,
'location=yes,clearsessioncache=yes,clearcache=yes'
)
.then(function(authResult) {
remoteStorage.remote.configure({
token: authResult.access_token
});
})
.then(null, function(error) {
console.error(error);
remoteStorage.widget.view.setState('initial');
});
}
RemoteStorage.Authorize.setLocation(url);
};
RemoteStorage.Authorize.IMPLIED_FAKE_TOKEN = false;
RemoteStorage.prototype.authorize = function (authURL, cordovaRedirectUri) {
this.access.setStorageType(this.remote.storageType);
var scope = this.access.scopeParameter;
var redirectUri = global.cordova ?
cordovaRedirectUri :
String(RemoteStorage.Authorize.getLocation());
var clientId = redirectUri.match(/^(https?:\/\/[^\/]+)/)[0];
RemoteStorage.Authorize(this, authURL, scope, redirectUri, clientId);
};
/**
* Get current document location
*
* Override this method if access to document.location is forbidden
*/
RemoteStorage.Authorize.getLocation = function () {
return global.document.location;
};
/**
* Set current document location
*
* Override this method if access to document.location is forbidden
*/
RemoteStorage.Authorize.setLocation = function (location) {
if (typeof location === 'string') {
global.document.location.href = location;
} else if (typeof location === 'object') {
global.document.location = location;
} else {
throw "Invalid location " + location;
}
};
/**
* Open new InAppBrowser window for OAuth in Cordova
*/
RemoteStorage.Authorize.openWindow = function (url, redirectUri, options) {
var pending = Promise.defer();
var newWindow = global.open(url, '_blank', options);
if (!newWindow || newWindow.closed) {
pending.reject('Authorization popup was blocked');
return pending.promise;
}
var handleExit = function () {
pending.reject('Authorization was canceled');
};
var handleLoadstart = function (event) {
if (event.url.indexOf(redirectUri) !== 0) {
return;
}
newWindow.removeEventListener('exit', handleExit);
newWindow.close();
var authResult = extractParams(event.url);
if (!authResult) {
return pending.reject('Authorization error');
}
return pending.resolve(authResult);
};
newWindow.addEventListener('loadstart', handleLoadstart);
newWindow.addEventListener('exit', handleExit);
return pending.promise;
};
RemoteStorage.prototype.impliedauth = function () {
RemoteStorage.ImpliedAuth(this.remote.storageApi, String(document.location));
};
RemoteStorage.Authorize._rs_supported = function () {
return typeof(document) !== 'undefined';
};
var onFeaturesLoaded;
RemoteStorage.Authorize._rs_init = function (remoteStorage) {
onFeaturesLoaded = function () {
var authParamsUsed = false;
if (params) {
if (params.error) {
throw "Authorization server errored: " + params.error;
}
// rsDiscovery came with the redirect, because it couldn't be
// saved in localStorage
if (params.rsDiscovery) {
remoteStorage.remote.configure(params.rsDiscovery);
}
if (params.access_token) {
remoteStorage.remote.configure({
token: params.access_token
});
authParamsUsed = true;
}
if (params.remotestorage) {
remoteStorage.connect(params.remotestorage);
authParamsUsed = true;
}
if (params.state) {
location = RemoteStorage.Authorize.getLocation();
RemoteStorage.Authorize.setLocation(location.href.split('#')[0]+'#'+params.state);
}
}
if (!authParamsUsed) {
remoteStorage.remote.stopWaitingForToken();
}
};
var params = extractParams(),
location;
if (params) {
location = RemoteStorage.Authorize.getLocation();
location.hash = '';
}
remoteStorage.on('features-loaded', onFeaturesLoaded);
};
RemoteStorage.Authorize._rs_cleanup = function (remoteStorage) {
remoteStorage.removeEventListener('features-loaded', onFeaturesLoaded);
};
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: src/access.js **/
(function(global) {
var SETTINGS_KEY = "remotestorage:access";
/**
* Class: RemoteStorage.Access
*
* Keeps track of claimed access and scopes.
*/
RemoteStorage.Access = function() {
this.reset();
};
RemoteStorage.Access.prototype = {
/**
* Method: claim
*
* Claim access on a given scope with given mode.
*
* Parameters:
* scope - An access scope, such as "contacts" or "calendar"
* mode - Access mode. Either "r" for read-only or "rw" for read/write
*
* Example:
* (start code)
* remoteStorage.access.claim('contacts', 'r');
* remoteStorage.access.claim('pictures', 'rw');
* (end code)
*
* Root access:
* Claiming root access, meaning complete access to all files and folders
* of a storage, can be done using an asterisk:
*
* (start code)
* remoteStorage.access.claim('*', 'rw');
* (end code)
*/
claim: function(scope, mode) {
if (typeof(scope) !== 'string' || scope.indexOf('/') !== -1 || scope.length === 0) {
throw new Error('Scope should be a non-empty string without forward slashes');
}
if (!mode.match(/^rw?$/)) {
throw new Error('Mode should be either \'r\' or \'rw\'');
}
this._adjustRootPaths(scope);
this.scopeModeMap[scope] = mode;
},
get: function(scope) {
return this.scopeModeMap[scope];
},
remove: function(scope) {
var savedMap = {};
var name;
for (name in this.scopeModeMap) {
savedMap[name] = this.scopeModeMap[name];
}
this.reset();
delete savedMap[scope];
for (name in savedMap) {
this.set(name, savedMap[name]);
}
},
/**
* Verify permission for a given scope.
*/
checkPermission: function(scope, mode) {
var actualMode = this.get(scope);
return actualMode && (mode === 'r' || actualMode === 'rw');
},
/**
* Verify permission for a given path.
*/
checkPathPermission: function(path, mode) {
if (this.checkPermission('*', mode)) {
return true;
}
return !!this.checkPermission(this._getModuleName(path), mode);
},
reset: function() {
this.rootPaths = [];
this.scopeModeMap = {};
},
/**
* Return the module name for a given path.
*/
_getModuleName: function(path) {
if (path[0] !== '/') {
throw new Error('Path should start with a slash');
}
var moduleMatch = path.replace(/^\/public/, '').match(/^\/([^\/]*)\//);
return moduleMatch ? moduleMatch[1] : '*';
},
_adjustRootPaths: function(newScope) {
if ('*' in this.scopeModeMap || newScope === '*') {
this.rootPaths = ['/'];
} else if (! (newScope in this.scopeModeMap)) {
this.rootPaths.push('/' + newScope + '/');
this.rootPaths.push('/public/' + newScope + '/');
}
},
_scopeNameForParameter: function(scope) {
if (scope.name === '*' && this.storageType) {
if (this.storageType === '2012.04') {
return '';
} else if (this.storageType.match(/remotestorage-0[01]/)) {
return 'root';
}
}
return scope.name;
},
setStorageType: function(type) {
this.storageType = type;
}
};
/**
* Property: scopes
*
* Holds an array of claimed scopes in the form
* > { name: "<scope-name>", mode: "<mode>" }
*/
Object.defineProperty(RemoteStorage.Access.prototype, 'scopes', {
get: function() {
return Object.keys(this.scopeModeMap).map(function(key) {
return { name: key, mode: this.scopeModeMap[key] };
}.bind(this));
}
});
Object.defineProperty(RemoteStorage.Access.prototype, 'scopeParameter', {
get: function() {
return this.scopes.map(function(scope) {
return this._scopeNameForParameter(scope) + ':' + scope.mode;
}.bind(this)).join(' ');
}
});
// Documented in src/remotestorage.js
Object.defineProperty(RemoteStorage.prototype, 'access', {
get: function() {
var access = new RemoteStorage.Access();
Object.defineProperty(this, 'access', {
value: access
});
return access;
},
configurable: true
});
RemoteStorage.Access._rs_init = function() {};
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: src/env.js **/
(function (pMode) {
var mode = pMode,
env = {},
isBackground = false;
RemoteStorage.Env = function () {
return env;
};
RemoteStorage.Env.isBrowser = function () {
return mode === "browser";
};
RemoteStorage.Env.isNode = function () {
return mode === "node";
};
RemoteStorage.Env.goBackground = function () {
isBackground = true;
RemoteStorage.Env._emit("background");
};
RemoteStorage.Env.goForeground = function () {
isBackground = false;
RemoteStorage.Env._emit("foreground");
};
RemoteStorage.Env._rs_init = function (remoteStorage) {
RemoteStorage.eventHandling(RemoteStorage.Env, "background", "foreground");
function visibility() {
if (document[env.hiddenProperty]) {
RemoteStorage.Env.goBackground();
} else {
RemoteStorage.Env.goForeground();
}
}
if ( mode === 'browser') {
if ( typeof(document.hidden) !== "undefined" ) {
env.hiddenProperty = "hidden";
env.visibilityChangeEvent = "visibilitychange";
} else if ( typeof(document.mozHidden) !== "undefined" ) {
env.hiddenProperty = "mozHidden";
env.visibilityChangeEvent = "mozvisibilitychange";
} else if ( typeof(document.msHidden) !== "undefined" ) {
env.hiddenProperty = "msHidden";
env.visibilityChangeEvent = "msvisibilitychange";
} else if ( typeof(document.webkitHidden) !== "undefined" ) {
env.hiddenProperty = "webkitHidden";
env.visibilityChangeEvent = "webkitvisibilitychange";
}
document.addEventListener(env.visibilityChangeEvent, visibility, false);
visibility();
}
};
RemoteStorage.Env._rs_cleanup = function (remoteStorage) {
};
})(typeof(window) !== 'undefined' ? 'browser' : 'node');
/** FILE: src/i18n.js **/
(function () {
/**
* Class: RemoteStorage.I18n
*
* TODO add documentation
**/
"use strict";
var dictionary = {
"view_info": 'This app allows you to use your own storage. <a href="http://remotestorage.io/" target="_blank">Learn more!</a>',
"view_connect": "<strong>Connect</strong> remote storage",
"view_connecting": "Connecting <strong>%s</strong>",
"view_offline": "Offline",
"view_error_occured": "Sorry! An error occured.",
"view_invalid_key": "Wrong key!",
"view_confirm_reset": "Are you sure you want to reset everything? This will clear your local data and reload the page.",
"view_get_me_out": "Get me out of here!",
"view_error_plz_report": 'If this problem persists, please <a href="http://remotestorage.io/community/" target="_blank">let us know</a>!',
"view_unauthorized": "Unauthorized! Click here to reconnect."
};
RemoteStorage.I18n = {
translate: function () {
var str = arguments[0],
params = Array.prototype.splice.call(arguments, 1);
if (typeof dictionary[str] !== "string") {
throw "Unknown translation string: " + str;
} else {
str = dictionary[str];
}
return (str.replace(/%s/g, function (){ return params.shift(); }));
},
getDictionary: function () {
return dictionary;
},
setDictionary: function (newDictionary) {
dictionary = newDictionary;
},
_rs_init: function() {
}
};
})();
/** FILE: src/assets.js **/
/** THIS FILE WAS GENERATED BY build/compile-assets.js. DO NOT CHANGE IT MANUALLY, BUT INSTEAD CHANGE THE ASSETS IN assets/. **/
RemoteStorage.Assets = {
cipherIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTQiIHdpZHRoPSIyNS4xNzciIHZlcnNpb249IjEuMSIgeG1sbnM6Y2M9Imh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL25zIyIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj4KIDxwYXRoIGQ9Im0yNS4xNzcgNS41MzIzYy0wLjA1NjQtMC4xMTI5MS0wLjA1NjQtMC4yMjU4MS0wLjE2OTM2LTAuMzM4NzEtMC4xMTI5LTAuMTEyOS0wLjI4MjI1LTAuMTY5MzYtMC4zOTUxNi0wLjE2OTM2aC0xMS40MDNjLTAuNzMzLTIuODc5LTMuMzg2NC01LjAyNDItNi40OTEzLTUuMDI0Mi0zLjY2OTMgMC02LjcxNzcgMy4wNDg0LTYuNzE3NyA2LjcxNzcgMCAzLjcyNjMgMy4wNDg0IDYuNzE3MyA2LjcxNzcgNi43MTczIDMuMzMwNyAwIDYuMDQwMy0yLjQyNzQgNi42MDQ4LTUuNTg4N2gyLjU0MDN2My42Njk0YzAgMC4yODIyNiAwLjI4MjI2IDAuNTA4MDYgMC41NjQ1MiAwLjUwODA2aDEuNzVjMC4yODIyNiAwIDAuNTY0NTItMC4yMjU4IDAuNTY0NTItMC41MDgwNnYtMy42Njk0aDEuNDY3N3Y1LjY0NTJjMCAwLjI4MjI1IDAuMjI1OCAwLjUwODA2IDAuNTA4MDYgMC41MDgwNmgxLjgwNjRjMC4yODIyNiAwIDAuNTA4MDctMC4yMjU4MSAwLjU2NDUyLTAuNTA4MDZ2LTUuNjQ1MmgxLjUyNDJjMC4xMTI5MSAwIDAuMjgyMjYgMCAwLjM5NTE2LTAuMTEyOSAwLjExMjkxLTAuMTEyOSAwLjE2OTM2LTAuMjgyMjYgMC4xNjkzNi0wLjM5NTE2di0xLjgwNjR6bS0xOC40NTkgNS4wODA3Yy0yLjA4ODcgMC0zLjgzODctMS42OTM2LTMuODM4Ny0zLjgzODcgMC0yLjE0NTIgMS43NS0zLjgzODcgMy44Mzg3LTMuODM4NyAyLjE0NTIgMCAzLjgzODcgMS42OTM2IDMuODM4NyAzLjgzODcgMCAyLjE0NTItMS42OTM2IDMuODM4Ny0zLjgzODcgMy44Mzg3eiIgZmlsbD0iI2ZmZiIvPgo8L3N2Zz4K',
connectIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTYiIHdpZHRoPSIxNiIgdmVyc2lvbj0iMS4xIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iPgogPGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMCAtMTAzNi40KSI+CiAgPHBhdGggZD0ibTEgMTA0Ny40di02aDd2LTRsNyA3LTcgN3YtNHoiIGZpbGw9IiNmZmYiLz4KIDwvZz4KPC9zdmc+Cg==',
disconnectIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTYiIHdpZHRoPSIxNiIgdmVyc2lvbj0iMS4wIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj4KIDxwYXRoIHN0eWxlPSJibG9jay1wcm9ncmVzc2lvbjp0Yjt0ZXh0LWluZGVudDowO2NvbG9yOiMwMDAwMDA7dGV4dC10cmFuc2Zvcm06bm9uZSIgZD0ibTguMDAwMSAwYy0wLjQ3MTQgMC0wLjk2MTAzIDAuNTQxOS0wLjk1IDF2NmMtMC4wMDc0NyAwLjUyODMxIDAuNDIxNjMgMSAwLjk1IDFzMC45NTc0Ny0wLjQ3MTY5IDAuOTUtMXYtNmMwLjAxNDYyMi0wLjYwNTEtMC40Nzg2LTEtMC45NS0xem0tMy4zNDM4IDIuNWMtMC4wODcxODYgMC4wMTkyOTQtMC4xNzE2MyAwLjA1MDk1OS0wLjI1IDAuMDkzNzUtMi45OTk1IDEuNTcxNS0zLjkxODQgNC43OTc5LTMuMTI1IDcuNDY4OCAwLjc5MzQgMi42NyAzLjI3OTkgNC45MzcgNi42ODc1IDQuOTM3IDMuMzU5MiAwIDUuODc3Mi0yLjE0OSA2LjcxOTItNC43ODEgMC44NDEtMi42MzIxLTAuMDU4LTUuODIzNC0zLjEyNS03LjU5NC0wLjQzNC0wLjI1MzYtMS4wNTktMC4wODk5LTEuMzEzIDAuMzQzNy0wLjI1MzYgMC40MzM2LTAuMDkgMS4wNTg5IDAuMzQ0IDEuMzEyNSAyLjM5MDggMS4zNzk4IDIuODgyNSAzLjQ5NDQgMi4yODEyIDUuMzc1LTAuNjAxMiAxLjg4MDYtMi4zNDQgMy40Mzc1LTQuOTA2MiAzLjQzNzUtMi41NzU5IDAtNC4yOTc2LTEuNjUwMi00Ljg3NS0zLjU5MzgtMC41Nzc2LTEuOTQzNS0wLjA0Ny00LjA0OCAyLjE4NzMtNS4yMTg3IDAuMzc4Ny0wLjIwNjMgMC41NzkxLTAuNjkyNSAwLjQ1NTgtMS4xMDU3LTAuMTIzMi0wLjQxMzMtMC41NTcyLTAuNzEwMy0wLjk4Ny0wLjY3NTUtMC4wMzEzLTAuMDAxNS0wLjA2MjYtMC4wMDE1LTAuMDkzOCAweiIgZmlsbD0iI2ZmZiIvPgo8L3N2Zz4K',
dropbox: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QgPEBAhEOpfuQAABhZJREFUWMPVl31snVUdxz+/5/2577e3b7QbHaOD0nXshW4ZZkpGQmJYZkJUDAaZzCBGAxGd+pdZQsJIjCaKgFu09GWybIggm8yhMCsY92rcOkPHunbdtKOUbX36svX23uc+xz+eDsrWlztiNJzk5D7JPS+fc8739/2dA5+EsqJtyK18ZlCKbX9Lk6fd1uo5xbTVZmtwa4v35Np5Mry4TLYXCzAnyhsry2SwrmnokdnaTruq6i3e0lXl0tqQlkURCxwdDp9Th5p3+p9iS8afqk/VZq9kaZoDN8apdU3B1KFnmLde7AkezH0n3V0UQOJpz2hIsqEhLU+WOeAagmtCxISYBe1nVf4vfWrByYdSpyf3W9ziLapy6JgbAduAiBn2S1rCQBYODAQP7H01/zxby4JpAW5s8mproxypiRKNGIJrQNT8EMA1wTGEU8MBP/q7umPw0dSbAA3N3n3zI2yLG2oScPgbNYWICY4Be86o/le6g0W576bPXQWwcqvXdJ2t1idMsA1hJoCoCRfGYdOhwsa4TUWFrr7pGmDrzAiQCHfD//Xxwk/33Z/6HoA0tnhLXZ3XMoYqsy4PYs4M4Ohg6pB2ddqO+vR6BWL27AARXbBNiBjwh9Oqs+O8ukcT4eaopjLqGsJSCdSX29SX23x/lctXlzgE1zBAANxWIQuGxlWNACxr8WozJp0lljKsGXbA0qGu1GRBxsTUQRAGLgboIuQVvHI8S+f7eeK2TLsDSQd296rhPaeDm09+PdX/gQYqN3uZ+jh7ro+oRusKDdgmVEY1GqstSiOhdegCmoQAIoImIWTPYIHdXVlyBYhaVwLA70+rPz7fllvLi2W5KcPw9q3eS/VJ7kmYgm1A3BIWV5osq7IIlMLUQJOrAXQBXQtr1BR2d2XpOu8TtULR+gq2nQh+vv8rqUdnNaKGZm/9qnJpmp/U+fxCB5lYsaGFdTYAY9L3jmNj9F9S7OgKVh9/KNVelBVf8untv8TYSS8gbsrHyh8C2LqQtGE0z9CJYfVuUblgRZv3WGOJvJG0cF8/lWPNdo+O93xsHYoVuqkL/xzIs/HPHt2DPg0Zko+v0I8vbfHun9aKE5sH9YaobJsf5V4mRLXv33kSlmAYwspqgw23R7A1EJlahKYOSsHTB0cZHQ9IOBA3NSrjGo4hWAY82xH8rH1b/jF2laoPAOb80jPqYtKTMdRcTQNd+xAgbgmuJbiGELfh3lsc7q41KQSTABBcC1qPjLH/XzniNqScsP1kgMsm9nJ34e2mNcmFAMby1qFPZyz1WlxXrprhuEUgUPDbd8Y59n6edbe61KZ1TF14vSfPLw5dYjhXIOMIM6lGAV+u0+tv+ttI/2+6/LsMQVXpUFCAqJkS9MT5anB2NGDjWxf5Yp3DvjN5th/LUhETolaRTqigxMGIWVKtHVyX2tGTJd2X5agUIfi8CmvUFOKGT++gT8wqLlKUgnwATxwq7P32m35Z+32pPQZA54MpH1iSb/XWZmx2VthTD1AATCBlCZ+dpwNg6EJjlUH3hQIKRaCujhZFaOPtfUH+8HvBnQceSP11yjA8vC616+A5FevL8jt/YiCR0HiQcAUVrnDHHO0jHTUNllXrpC0NRXiefjAxM4rhHLzQpZqf+eFFd/LkM17JGlu9p+xC8IgPhGlaqE1rNJZrxOzQok0dnjviY+nhbSntCH3DAWN+QMIWEhYsqTD4wYHChrPfSP9kqnmM6QAMkYtz4xqmDqeGA+rLNObGZVozkglx1ZfqZAvC2ZGAz9RYlEbAlsLoNd+Kx5RqO5/njKXDsnKdhCXFOaFAZUzjznlhyt5xIjiSLbBz2oVO98fRdalOoGZ5m/dUQ4pvJZ3Zr/CXlS5A74gabzlYePztr6U2faxr+eRy/RYvtjgjHauvkxvi9oTDXaGBuAUJWyh1hb3vqsOvfiG5/L/yMAE483BqdNeuXO3LvcGX3vEUhsZVsaYL9IzACz3BXcVOXvQOfKRsupBZv8R4bnW19rmqGPzqHz4BcMGn5U/Hgod5oiT3P3kvVj7rrfnx/pHBu7d7Azc1eY3/l0drzWbPXNjsGXySy38AbtMqneWU7BkAAAAASUVORK5CYII=',
googledrive: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QgPEA85ztzJcQAABZVJREFUWMPtl1uoXVcVhr8x5tprn7M1NG1i0pQqSG2jLcXipYJXjPogqFgpaHMSFUkpIjU+leKbDxIQSiHgjZgmrfXgQ6SKj5Ji7YVS05aUUqKQlNLQeDnN5Zzk9Jy99xy/D3OttU/StDlV33TBZM3FXmuMf/5jjv+fG/7XL1vti9tnv3Dtnnf+87JY8YmZNxEMM1sZ7tWpjz764mriVqvKvmfb1ONLy3+dGyWu6EWbvQwoydv5BMSqFuereakmfnls1GP25IDaBGYYjplhljDz5tk7YMtPfurAf6UE9Z6tNwDPAPXwtcxL1x9n4zRgDjjm1gCyC6JpCLoW/OX65of1nzCwG6gNo3aYeXF981mTvK2/WWFiMmoj7X+z5JcE0N87c4e7b3EvyTwZT5/r8ezZHu6GuWGpSegJ8/ZeBu6fHv35s1/7t0rQv29mjWF/ATZ1L4bQwohrpkYc/sBpwhJYAVdKYECzYAESIk4Am3sf+sPCW2LAzb9jbpvMDXfD3fEqkRIcGdbsevlt9LylPYG1K6/K3QzK75uAr78lBgb3b7sc2cl2Uaa21sDiGMvB2iQeu/EMm6bKHjD3SUsCEChnpEAKiLisd/PB+UsyMPjZNwzzh1ixcnOfsFCX51NU/PTvA6pkTUdYw4R3zyu1ArMDqyvBQB82+FiJUQJ4C8YgVT1SSvSTs+vEmkcwe7qEsUnt233Aij0BW4ZPbfngKpRQs7hXpYQNvRiuEtATWOW4bLi+z04pJbCnBAkBJggBQlIBIZCUJM0Cm9+QgcED2+/G7BprdMZaAFZExm1FWcz+NLdj32G/6XfPCB5GoJKp7H5FARHRtgRI1y0/+cm7Lwpg+v7t64DvNd5S2mqirKXHy6RoArp1Ykrc2hKtKCtXlNEyoQ6Ydi498fF1F2FAdwEbV9UnZne+8q19Z7o63vTb+TPnRneeWxwxHGdyziii6wApQNEydKUUd5wHYGrftvci7tKKLSME5bvCaruynI9rNL7vdZgiHhiP898Wl8bMnxty+uyIhcURo1FgjSg1DCDph4uPfuR9AFbvvS25p2cxbiyKVuh2o1O44n2lLLacb5v75v5fX6yl5h753IwUD+YcRAQ5B6FMMhj0jboSRhnAE258wvp7Z7aYcbCYCeCGt97ubfICLDP/q4WZ32x7M20fPfb+hxbH9ZdjHOQIIoR74EDywA3coa6MqtJnrP+LmRmcB63ob8dA1wllRm95LVc//22S16TGeKqqpqoHk10ESGJj/zjjgIhAISKCyJmcY6Uu8Pbq7C0V6ABh35dzvYWQG0QAhmSYCaUlNhzdCrlX2jpE6tV4b9DYcGFKEgG8svQucoicC4CsII8zeTxutAEQzx1duPL3vrxjdlnou0SDLdTulxJQmalXNzN98jpEJiSo+qTeoEnsnWC5lVZNRhkOZiq0G8XCmz1gpp3j/ZYdYLhj9qCkn3fJQ4QKeh9OccWxz6O0hGKM9wakeoBEZ1BmqfOMyYFk4gXS+edG4J4ju6/644VK+AOJhSIYpVRBpn/qPVRL65A51dRavJoG2UQkOqf0hgVrGG7u6syoJDObB+55nRANb589Afy40W0UwkY91h39CiLweg1UU+W3ohLNvC2VurJ1htR6A3QaYPCjI7uvOvGGOlfv2XoSuBzEhmNfZXDqBrweUPVqUlWodneSG+6J1NTevThfDpEjmnsmzuuCPPfCvRvfcakT0S2Aeq9tYPr0ZryeBvOOlZBKUIEiCAVZwTgy41x6v6hm0LFZ4o7N7IuXPA+EDx+XjQ+tP/4lUrW2vCI1ydR0iYgmWdtu4yzG7bOiAdn8iYlA0iFJh1Z1JJv+ye2b3n1419XRH2riP0aqqlKClABIjUMW+rtSlw5qmCpgsynnl56/d+M/+P91wfUvQjDgTzx9h9AAAAAASUVORK5CYII=',
nocipherIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTYiIHdpZHRoPSIxNiIgdmVyc2lvbj0iMS4xIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iPgogPHBhdGggZD0ibSAxMy4yMDMxMjQsMTEuNzczNDM4IGMgMC4yODEyNSwwLjI4MTI1IDAuNDIxODc1LDAuNjA5Mzc1IDAuNDIxODc1LDEuMDMxMjUgMCwwLjM3NSAtMC4xNDA2MjUsMC43NSAtMC40MjE4NzUsMS4wMzEyNSAtMC4yODEyNSwwLjIzNDM3NSAtMC42MDkzNzUsMC4zNzUgLTEuMDMxMjUsMC4zNzUgLTAuMzc1LDAgLTAuNzUsLTAuMTQwNjI1IC0xLjAzMTI1LC0wLjM3NSAwLDAgLTMuMTg3NDk4MSwtMy42NTYyNSAtMy4xODc0OTgxLC0zLjY1NjI1IDAsMCAtMy4xNDA2MjUsMy42NTYyNSAtMy4xNDA2MjUsMy42NTYyNSAtMC4yODEyNSwwLjIzNDM3NSAtMC42NTYyNSwwLjM3NSAtMS4wMzEyNSwwLjM3NSAtMC40MjE4NzUsMCAtMC43NSwtMC4xNDA2MjUgLTEuMDMxMjUsLTAuMzc1IC0wLjI4MTI1LC0wLjI4MTI1IC0wLjM3NSwtMC42NTYyNSAtMC4zNzUsLTEuMDMxMjUgMCwtMC40MjE4NzUgMC4wOTM3NSwtMC43NSAwLjM3NSwtMS4wMzEyNSAwLDAgMy4zMjgxMjUsLTMuNzUwMDAwNSAzLjMyODEyNSwtMy43NTAwMDA1IDAsMCAtMy4zMjgxMjUsLTMuNzk2ODc1IC0zLjMyODEyNSwtMy43OTY4NzUgLTAuMjgxMjUsLTAuMjgxMjUgLTAuMzc1LC0wLjYwOTM3NSAtMC4zNzUsLTEuMDMxMjUgMCwtMC4zNzUgMC4wOTM3NSwtMC43NSAwLjM3NSwtMS4wMzEyNSAwLjI4MTI1LC0wLjIzNDM3NSAwLjYwOTM3NSwtMC4zNzUgMS4wMzEyNSwtMC4zNzUgMC4zNzUsMCAwLjc1LDAuMTQwNjI1IDEuMDMxMjUsMC4zNzUgMCwwIDMuMTQwNjI1LDMuNjU2MjUgMy4xNDA2MjUsMy42NTYyNSAwLDAgMy4xODc0OTgxLC0zLjY1NjI1IDMuMTg3NDk4MSwtMy42NTYyNSAwLjI4MTI1LC0wLjIzNDM3NSAwLjY1NjI1LC0wLjM3NSAxLjAzMTI1LC0wLjM3NSAwLjQyMTg3NSwwIDAuNzUsMC4xNDA2MjUgMS4wMzEyNSwwLjM3NSAwLjI4MTI1LDAuMjgxMjUgMC40MjE4NzUsMC42NTYyNSAwLjQyMTg3NSwxLjAzMTI1IDAsMC40MjE4NzUgLTAuMTQwNjI1LDAuNzUgLTAuNDIxODc1LDEuMDMxMjUgMCwwIC0zLjMyODEyMzEsMy43OTY4NzUgLTMuMzI4MTIzMSwzLjc5Njg3NSAwLDAgMy4zMjgxMjMxLDMuNzUwMDAwNSAzLjMyODEyMzEsMy43NTAwMDA1IiBmaWxsPSIjZmZmIi8+Cjwvc3ZnPgo=',
remoteStorageIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMzIiIHdpZHRoPSIzMiIgdmVyc2lvbj0iMS4xIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj4KIDxkZWZzPgogIDxyYWRpYWxHcmFkaWVudCBpZD0iYSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGN5PSI1NzEuNDIiIGN4PSIxMDQ2LjUiIGdyYWRpZW50VHJhbnNmb3JtPSJtYXRyaXgoLjE0NDMzIDAgMCAuMTY2NjcgMTIwMS41IDg3Ny4xMSkiIHI9Ijk2Ij4KICAgPHN0b3Agc3RvcC1jb2xvcj0iI2ZmNGEwNCIgc3RvcC1vcGFjaXR5PSIuNzYxNTQiIG9mZnNldD0iMCIvPgogICA8c3RvcCBzdG9wLWNvbG9yPSIjZmY0YTA0IiBvZmZzZXQ9IjEiLz4KICA8L3JhZGlhbEdyYWRpZW50PgogPC9kZWZzPgogPGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTEzMzYuNiAtOTU2LjM1KSI+CiAgPHBhdGggc3R5bGU9ImNvbG9yOiMwMDAwMDAiIGQ9Im0xMzUyLjYgOTU2LjM1IDAuMjg4NiAxNS4xMzYgMTMuNTY3LTcuMTM1Mi0xMy44NTUtOC4wMDExemwtMTMuODU1IDguMDAxMSAxMy41NjcgNy4xMzUyIDAuMjg4Ny0xNS4xMzZ6bS0xMy44NTUgOC4wMDExdjE1Ljk5OGwxMi45NTgtNy44MTYyLTEyLjk1OC04LjE4MTV6bTAgMTUuOTk4IDEzLjg1NSA4LjAwMTEtMC42MDg5LTE1LjMxNy0xMy4yNDYgNy4zMTU2em0xMy44NTUgOC4wMDExIDEzLjg1NS04LjAwMTEtMTMuMjUxLTcuMzE1Ni0wLjYwNDQgMTUuMzE3em0xMy44NTUtOC4wMDExdi0xNS45OThsLTEyLjk2MiA4LjE4MTUgMTIuOTYyIDcuODE2MnoiIGZpbGw9InVybCgjYSkiLz4KIDwvZz4KPC9zdmc+Cg==',
remoteStorageIconCiphered: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMzIiIHdpZHRoPSIzMiIgdmVyc2lvbj0iMS4xIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj4KIDxkZWZzPgogIDxyYWRpYWxHcmFkaWVudCBpZD0iYSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGN5PSI1NzEuNDIiIGN4PSIxMDQ2LjUiIGdyYWRpZW50VHJhbnNmb3JtPSJtYXRyaXgoLjE0NDMzIDAgMCAuMTY2NjcgMTIwMS41IDg3Ny4xMSkiIHI9Ijk2Ij4KICAgPHN0b3Agc3RvcC1jb2xvcj0iI2ZmNGEwNCIgc3RvcC1vcGFjaXR5PSIuNzYxNTQiIG9mZnNldD0iMCIvPgogICA8c3RvcCBzdG9wLWNvbG9yPSIjZmY0YTA0IiBvZmZzZXQ9IjEiLz4KICA8L3JhZGlhbEdyYWRpZW50PgogPC9kZWZzPgogPHBhdGggc3R5bGU9ImNvbG9yOiMwMDAwMDAiIGQ9Im0xNiAwbDAuMTI1IDYuMzc1YzIuMDk4IDAuMDY3IDMuNzUgMS43NTk1IDMuNzUgMy44NzV2MS45NjloMS45MzcgMC4wMzJsOC00LjIxOS0xMy44NDQtOHpsLTEzLjg0NCA4IDggNC4yMTloMC4wMzIgMS45MDZ2LTEuOTY5YzAtMi4xMTU1IDEuNjgzLTMuODA4IDMuNzgxLTMuODc1bDAuMTI1LTYuMzc1em0tMTMuODQ0IDh2MTZsNy45OTk4LTQuODQ0di02LjA5NGwtNy45OTk4LTUuMDYyem0wIDE2bDEzLjg0NCA4LTAuMzc1LTEwLjA2MmgtNS40Njl2LTIuMzQ0bC03Ljk5OTggNC40MDZ6bTEzLjg0NCA4bDEzLjg0NC04LTgtNC40MDZ2Mi4zNDRoLTUuNDY5bC0wLjM3NSAxMC4wNjJ6bTEzLjg0NC04di0xNmwtOCA1LjA2MnY2LjA5NGw4IDQuODQ0em0tMTMuOTY5LTE3Yy0xLjczNSAwLjA2NjYtMy4xMjUgMS40OTg3LTMuMTI1IDMuMjV2MS45NjloMy4wMzFsMC4wOTQtNS4yMTl6bTAuMjUgMGwwLjA5NCA1LjIxOWgzLjAzMXYtMS45NjljMC0xLjc1MTMtMS4zOS0zLjE4MzQtMy4xMjUtMy4yNXptLTQuNzUgNS44NDRsNC4zNDQgMi4yODEgMC4wMzEtMi4yODFoLTQuMzc1em00Ljg3NSAwbDAuMDMxIDIuMjgxIDQuMzQ0LTIuMjgxaC00LjM3NXptLTUuNDM4IDAuNjI1djUuMzEybDQuMjgyLTIuNTkzLTQuMjgyLTIuNzE5em0xMC4zNzYgMGwtNC4yODIgMi43MTkgNC4yODIgMi41OTN2LTUuMzEyem0tNS43ODIgMy4yMTlsLTQuNTk0IDIuNTMxdjIuMDYyaDQuNzgybC0wLjE4OC00LjU5M3ptMS4xODggMGwtMC4xODggNC41OTNoNC43ODJ2LTIuMDYybC00LjU5NC0yLjUzMXoiIGZpbGw9InVybCgjYSkiLz4KPC9zdmc+Cg==',
remoteStorageIconError: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMzIiIHdpZHRoPSIzMiIgdmVyc2lvbj0iMS4xIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj4KIDxkZWZzPgogIDxyYWRpYWxHcmFkaWVudCBpZD0iYSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGN5PSI1NzEuNDIiIGN4PSIxMDQ2LjUiIGdyYWRpZW50VHJhbnNmb3JtPSJtYXRyaXgoLjE0NDMzIDAgMCAuMTY2NjcgMTIwMS41IDg3Ny4xMSkiIHI9Ijk2Ij4KICAgPHN0b3Agc3RvcC1jb2xvcj0iI2U5MDAwMCIgc3RvcC1vcGFjaXR5PSIuNzYwNzgiIG9mZnNldD0iMCIvPgogICA8c3RvcCBzdG9wLWNvbG9yPSIjZTkwMDAwIiBvZmZzZXQ9IjEiLz4KICA8L3JhZGlhbEdyYWRpZW50PgogPC9kZWZzPgogPGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTEzMzYuNiAtOTU2LjM1KSI+CiAgPHBhdGggc3R5bGU9ImNvbG9yOiMwMDAwMDAiIGQ9Im0xMzUyLjYgOTU2LjM1IDAuMjg4NiAxNS4xMzYgMTMuNTY3LTcuMTM1Mi0xMy44NTUtOC4wMDExemwtMTMuODU1IDguMDAxMSAxMy41NjcgNy4xMzUyIDAuMjg4Ny0xNS4xMzZ6bS0xMy44NTUgOC4wMDExdjE1Ljk5OGwxMi45NTgtNy44MTYyLTEyLjk1OC04LjE4MTV6bTAgMTUuOTk4IDEzLjg1NSA4LjAwMTEtMC42MDg5LTE1LjMxNy0xMy4yNDYgNy4zMTU2em0xMy44NTUgOC4wMDExIDEzLjg1NS04LjAwMTEtMTMuMjUxLTcuMzE1Ni0wLjYwNDQgMTUuMzE3em0xMy44NTUtOC4wMDExdi0xNS45OThsLTEyLjk2MiA4LjE4MTUgMTIuOTYyIDcuODE2MnoiIGZpbGw9InVybCgjYSkiLz4KIDwvZz4KPC9zdmc+Cg==',
remoteStorageIconOffline: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMzIiIHdpZHRoPSIzMiIgdmVyc2lvbj0iMS4xIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj4KIDxkZWZzPgogIDxyYWRpYWxHcmFkaWVudCBpZD0iYSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGN5PSI1NzEuNDIiIGN4PSIxMDQ2LjUiIGdyYWRpZW50VHJhbnNmb3JtPSJtYXRyaXgoLjE0NDMzIDAgMCAuMTY2NjcgMTIwMS41IDg3Ny4xMSkiIHI9Ijk2Ij4KICAgPHN0b3Agc3RvcC1jb2xvcj0iIzY5Njk2OSIgc3RvcC1vcGFjaXR5PSIuNzYxNTQiIG9mZnNldD0iMCIvPgogICA8c3RvcCBzdG9wLWNvbG9yPSIjNjc2NzY3IiBvZmZzZXQ9IjEiLz4KICA8L3JhZGlhbEdyYWRpZW50PgogPC9kZWZzPgogPGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTEzMzYuNiAtOTU2LjM1KSI+CiAgPHBhdGggc3R5bGU9ImNvbG9yOiMwMDAwMDAiIGQ9Im0xMzUyLjYgOTU2LjM1IDAuMjg4NiAxNS4xMzYgMTMuNTY3LTcuMTM1Mi0xMy44NTUtOC4wMDExemwtMTMuODU1IDguMDAxMSAxMy41NjcgNy4xMzUyIDAuMjg4Ny0xNS4xMzZ6bS0xMy44NTUgOC4wMDExdjE1Ljk5OGwxMi45NTgtNy44MTYyLTEyLjk1OC04LjE4MTV6bTAgMTUuOTk4IDEzLjg1NSA4LjAwMTEtMC42MDg5LTE1LjMxNy0xMy4yNDYgNy4zMTU2em0xMy44NTUgOC4wMDExIDEzLjg1NS04LjAwMTEtMTMuMjUxLTcuMzE1Ni0wLjYwNDQgMTUuMzE3em0xMy44NTUtOC4wMDExdi0xNS45OThsLTEyLjk2MiA4LjE4MTUgMTIuOTYyIDcuODE2MnoiIGZpbGw9InVybCgjYSkiLz4KIDwvZz4KPC9zdmc+Cg==',
syncIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDg3LjUgMTAwIiB4bWw6c3BhY2U9InByZXNlcnZlIiBoZWlnaHQ9IjE2IiB2aWV3Qm94PSIwIDAgMTUuOTk5OTk5IDE2IiB3aWR0aD0iMTYiIHZlcnNpb249IjEuMSIgeT0iMHB4IiB4PSIwcHgiIHhtbG5zOmNjPSJodHRwOi8vY3JlYXRpdmVjb21tb25zLm9yZy9ucyMiIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyI+CjxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKC01LjUxMTIgLTc2LjUyNSkiIGRpc3BsYXk9Im5vbmUiPgoJPHBhdGggZGlzcGxheT0iaW5saW5lIiBkPSJtNTEuNDczIDQyLjI1NS0yLjIwNSAyLjIxMmMxLjQ3OCAxLjQ3NyAyLjI5NSAzLjQ0MiAyLjI5NSA1LjUzMyAwIDQuMzA5LTMuNTA0IDcuODEyLTcuODEyIDcuODEydi0xLjU2MmwtMy4xMjUgMy4xMjUgMy4xMjQgMy4xMjV2LTEuNTYyYzYuMDI5IDAgMTAuOTM4LTQuOTA2IDEwLjkzOC0xMC45MzggMC0yLjkyNy0xLjE0MS01LjY3Ni0zLjIxNS03Ljc0NXoiLz4KCTxwYXRoIGRpc3BsYXk9ImlubGluZSIgZD0ibTQ2Ljg3NSA0MC42MjUtMy4xMjUtMy4xMjV2MS41NjJjLTYuMDMgMC0xMC45MzggNC45MDctMTAuOTM4IDEwLjkzOCAwIDIuOTI3IDEuMTQxIDUuNjc2IDMuMjE3IDcuNzQ1bDIuMjAzLTIuMjEyYy0xLjQ3Ny0xLjQ3OS0yLjI5NC0zLjQ0Mi0yLjI5NC01LjUzMyAwLTQuMzA5IDMuNTA0LTcuODEyIDcuODEyLTcuODEydjEuNTYybDMuMTI1LTMuMTI1eiIvPgo8L2c+CjxwYXRoIGZpbGw9IiNmZmYiIGQ9Im0xMCAwbC0wLjc1IDEuOTA2MmMtMS4wMDc4LTAuMjk0Mi0zLjQ1ODYtMC43NzA4LTUuNjU2MiAwLjkzNzYgMC0wLjAwMDItMy45MzAyIDIuNTk0MS0yLjA5MzggNy41OTQybDEuNjU2Mi0wLjcxOTJzLTEuNTM5OS0zLjExMjIgMS42ODc2LTUuNTMxM2MwIDAgMS42OTU3LTEuMTMzOSAzLjY4NzQtMC41OTM3bC0wLjcxODcgMS44MTI0IDMuODEyNS0xLjYyNS0xLjYyNS0zLjc4MTJ6Ii8+PHBhdGggZmlsbD0iI2ZmZiIgZD0ibTE0IDUuNTYyNWwtMS42NTYgMC43MTg3czEuNTQxIDMuMTEzNS0xLjY4OCA1LjUzMDhjMCAwLTEuNzI3MiAxLjEzNS0zLjcxODUgMC41OTRsMC43NS0xLjgxMi0zLjgxMjUgMS41OTQgMS41OTM4IDMuODEyIDAuNzgxMi0xLjkwNmMxLjAxMTMgMC4yOTUgMy40NjE1IDAuNzY2IDUuNjU2LTAuOTM4IDAgMCAzLjkyOC0yLjU5NCAyLjA5NC03LjU5MzV6Ii8+Cjwvc3ZnPgo=',
widget: '<div class="rs-bubble rs-hidden"> <div class="rs-bubble-text remotestorage-initial remotestorage-error remotestorage-authing remotestorage-offline"> <span class="rs-status-text">{{view_connect}}</span> </div> <div class="rs-bubble-expandable"> <!-- error --> <div class="remotestorage-error"> <pre class="rs-status-text rs-error-msg">{{ERROR_MSG}}</pre> <button class="remotestorage-reset">{{view_get_me_out}}</button> <p class="rs-centered-text rs-error-plz-report">{{view_error_plz_report}}</p> </div> <!-- connected --> <div class="rs-bubble-text remotestorage-connected"> <strong class="userAddress">{{USER_ADDRESS}}</strong> <p class="remotestorage-unauthorized">{{view_unauthorized}}</p> <p class="remotestorage-invalid-key">{{view_invalid_key}}</p> <form novalidate class="remotestorage-cipher-form"> <input placeholder="Secret key" name="userSecretKey" novalidate> <button class="rs-cipher" name="rs-cipher" title="cipher" disabled="disabled"> <img> </button> <button class="rs-nocipher" name="rs-nocipher" title="no cipher"> <img> </button> </form> </div> <div class="rs-content remotestorage-connected"> <button class="rs-sync" title="sync"><img></button> <button class="rs-disconnect" title="disconnect"><img></button> </div> <!-- initial --> <form novalidate class="remotestorage-initial"> <input type="email" placeholder="[email protected]" name="userAddress" novalidate> <button class="connect" name="connect" title="connect" disabled="disabled"> <img> </button> </form> <div class="rs-info-msg remotestorage-initial">{{view_info}}</div> </div> </div> <img class="rs-dropbox rs-backends rs-action" alt="Connect to Dropbox"> <img class="rs-googledrive rs-backends rs-action" alt="Connect to Google Drive"> <img class="rs-cube rs-action"> ',
widgetCss: '/** encoding:utf-8 **/ /* RESET */ #remotestorage-widget{text-align:left;}#remotestorage-widget input, #remotestorage-widget button{font-size:11px;}#remotestorage-widget form input[type=email]{margin-bottom:0;/* HTML5 Boilerplate */}#remotestorage-widget form input[type=submit]{margin-top:0;/* HTML5 Boilerplate */}/* /RESET */ #remotestorage-widget, #remotestorage-widget *{-moz-box-sizing:border-box;box-sizing:border-box;}#remotestorage-widget{position:absolute;right:10px;top:10px;font:normal 16px/100% sans-serif !important;user-select:none;-webkit-user-select:none;-moz-user-select:-moz-none;cursor:default;z-index:10000;}#remotestorage-widget .rs-bubble{background:rgba(80, 80, 80, .7);border-radius:5px 15px 5px 5px;color:white;font-size:0.8em;padding:5px;position:absolute;right:3px;top:9px;min-height:24px;white-space:nowrap;text-decoration:none;}.rs-bubble .rs-bubble-text{padding-right:32px;/* make sure the bubble doesn\'t "jump" when initially opening. */ min-width:182px;}#remotestorage-widget .rs-action{cursor:pointer;}/* less obtrusive cube when connected */ #remotestorage-widget.remotestorage-state-connected .rs-cube, #remotestorage-widget.remotestorage-state-busy .rs-cube{opacity:.3;-webkit-transition:opacity .3s ease;-moz-transition:opacity .3s ease;-ms-transition:opacity .3s ease;-o-transition:opacity .3s ease;transition:opacity .3s ease;}#remotestorage-widget.remotestorage-state-connected:hover .rs-cube, #remotestorage-widget.remotestorage-state-busy:hover .rs-cube, #remotestorage-widget.remotestorage-state-connected .rs-bubble:not(.rs-hidden) + .rs-cube{opacity:1 !important;}#remotestorage-widget .rs-backends{position:relative;top:5px;right:0;}#remotestorage-widget .rs-cube{position:relative;top:5px;right:0;}/* pulsing animation for cube when loading */ #remotestorage-widget .rs-cube.remotestorage-loading{-webkit-animation:remotestorage-loading .5s ease-in-out infinite alternate;-moz-animation:remotestorage-loading .5s ease-in-out infinite alternate;-o-animation:remotestorage-loading .5s ease-in-out infinite alternate;-ms-animation:remotestorage-loading .5s ease-in-out infinite alternate;animation:remotestorage-loading .5s ease-in-out infinite alternate;}@-webkit-keyframes remotestorage-loading{to{opacity:.7}}@-moz-keyframes remotestorage-loading{to{opacity:.7}}@-o-keyframes remotestorage-loading{to{opacity:.7}}@-ms-keyframes remotestorage-loading{to{opacity:.7}}@keyframes remotestorage-loading{to{opacity:.7}}#remotestorage-widget a{text-decoration:underline;color:inherit;}#remotestorage-widget form{margin-top:.7em;position:relative;}#remotestorage-widget form input{display:table-cell;vertical-align:top;border:none;border-radius:6px;font-weight:bold;color:white;outline:none;line-height:1.5em;height:2em;}#remotestorage-widget form input:disabled{color:#999;background:#444 !important;cursor:default !important;}#remotestorage-widget form input[type=email]:focus, #remotestorage-widget form input[type=password]:focus{background:#223;}#remotestorage-widget form input[type=email], #remotestorage-widget form input[type=password]{background:#000;width:100%;height:26px;padding:0 30px 0 5px;border-top:1px solid #111;border-bottom:1px solid #999;}#remotestorage-widget form input[type=email]:focus, #remotestorage-widget form input[type=password]:focus{background:#223;}#remotestorage-widget button:focus, #remotestorage-widget input:focus{box-shadow:0 0 4px #ccc;}#remotestorage-widget form input[type=email]::-webkit-input-placeholder, #remotestorage-widget form input[type=password]::-webkit-input-placeholder{color:#999;}#remotestorage-widget form input[type=email]:-moz-placeholder, #remotestorage-widget form input[type=password]:-moz-placeholder{color:#999;}#remotestorage-widget form input[type=email]::-moz-placeholder, #remotestorage-widget form input[type=password]::-moz-placeholder{color:#999;}#remotestorage-widget form input[type=email]:-ms-input-placeholder, #remotestorage-widget form input[type=password]:-ms-input-placeholder{color:#999;}#remotestorage-widget form input[type=submit]{background:#000;cursor:pointer;padding:0 5px;}#remotestorage-widget form input[type=submit]:hover{background:#333;}#remotestorage-widget .rs-info-msg{font-size:10px;color:#eee;margin-top:0.7em;white-space:normal;}#remotestorage-widget .rs-info-msg.last-synced-message{display:inline;white-space:nowrap;margin-bottom:.7em}#remotestorage-widget .rs-info-msg a:hover, #remotestorage-widget .rs-info-msg a:active{color:#fff;}#remotestorage-widget button img{vertical-align:baseline;}#remotestorage-widget button{border:none;border-radius:6px;font-weight:bold;color:white;outline:none;line-height:1.5em;height:26px;width:26px;background:#000;cursor:pointer;margin:0;padding:5px;}#remotestorage-widget button:hover{background:#333;}#remotestorage-widget .rs-bubble button.connect, #remotestorage-widget .rs-bubble button.rs-cipher, #remotestorage-widget .rs-bubble button.rs-nocipher{display:block;background:none;position:absolute;right:0;top:0;opacity:1;/* increase clickable area of connect, rs-cipher & rs-nocipher buttons */ margin:-5px;padding:10px;width:36px;height:36px;}#remotestorage-widget .rs-bubble button.rs-cipher{width:46px;}#remotestorage-widget .rs-bubble button.rs-nocipher{height:26px;margin:0;padding:4px 5px 5px;right:-32px;width:26px;}#remotestorage-widget .rs-bubble button.connect:not([disabled]):hover, #remotestorage-widget .rs-bubble button.rs-cipher:not([disabled]):hover, #remotestorage-widget .rs-bubble button.rs-nocipher:not([disabled]):hover{background:rgba(150,150,150,.5);}#remotestorage-widget .rs-bubble button.connect[disabled], #remotestorage-widget .rs-bubble button.rs-cipher[disabled]{opacity:.5;cursor:default !important;}#remotestorage-widget .rs-bubble button.rs-sync{position:relative;left:-5px;bottom:-5px;padding:4px 4px 0 4px;background:#555;}#remotestorage-widget .rs-bubble button.rs-sync:hover{background:#444;}#remotestorage-widget .rs-bubble button.rs-disconnect{background:#721;position:absolute;right:0;bottom:0;padding:4px 4px 0 4px;}#remotestorage-widget .rs-bubble button.rs-disconnect:hover{background:#921;}#remotestorage-widget .remotestorage-error-info{color:#f92;}#remotestorage-widget .remotestorage-reset{width:100%;background:#721;}#remotestorage-widget .remotestorage-reset:hover{background:#921;}#remotestorage-widget .rs-bubble .rs-content{margin-top:7px;}#remotestorage-widget pre{user-select:initial;-webkit-user-select:initial;-moz-user-select:text;max-width:27em;margin-top:1em;overflow:auto;}#remotestorage-widget .rs-centered-text{text-align:center;}#remotestorage-widget .rs-bubble.rs-hidden{padding-bottom:2px;border-radius:5px 15px 15px 5px;}#remotestorage-widget .rs-error-msg{min-height:5em;}.rs-bubble.rs-hidden .rs-bubble-expandable{display:none;}.remotestorage-state-connected .rs-bubble.rs-hidden{display:none;}.remotestorage-connected{display:none;}.remotestorage-state-connected .remotestorage-connected{display:block;}.remotestorage-cipher-form{display:none;}.remotestorage-cipher .remotestorage-cipher-form{display:block;}.remotestorage-invalid-key{display:none;}.remotestorage-invalid-key.remotestorage-cipher-error{display:block;}.remotestorage-initial{display:none;}.remotestorage-state-initial .remotestorage-initial{display:block;}.remotestorage-error{display:none;}.remotestorage-state-error .remotestorage-error{display:block;}.remotestorage-state-authing .remotestorage-authing{display:block;}.remotestorage-state-offline .remotestorage-connected, .remotestorage-state-offline .remotestorage-offline{display:block;}.remotestorage-unauthorized{display:none;}.remotestorage-state-unauthorized .rs-bubble.rs-hidden{display:none;}.remotestorage-state-unauthorized .remotestorage-connected, .remotestorage-state-unauthorized .remotestorage-unauthorized{display:block;}.remotestorage-state-unauthorized .rs-sync{display:none;}.remotestorage-state-busy .rs-bubble.rs-hidden{display:none;}.remotestorage-state-busy .rs-bubble{display:block;}.remotestorage-state-busy .remotestorage-connected{display:block;}.remotestorage-state-authing .rs-bubble-expandable{display:none;}'
};
/** FILE: src/widget.js **/
(function (window) {
var hasLocalStorage;
var LS_STATE_KEY = 'remotestorage:widget:state';
// states allowed to immediately jump into after a reload.
var VALID_ENTRY_STATES = {
initial: true,
connected: true,
offline: true
};
/**
* Class: RemoteStorage.Widget
*
* The widget controller that communicates with the view and listens to
* its remoteStorage instance.
*
* While listening to the events emitted by its remoteStorage it sets
* corresponding states of the view.
*
* - connected -> connected
* - disconnected -> initial
* - connecting -> authing
* - authing -> authing
* - wire-busy -> busy
* - wire-done -> connected
* - error -> one of initial, offline, unauthorized, or error
**/
RemoteStorage.Widget = function (remoteStorage) {
var self = this;
var requestsToFlashFor = 0;
// setting event listeners on rs events to put
// the widget into corresponding states
this.rs = remoteStorage;
this.rs.remote.on('connected', stateSetter(this, 'connected'));
this.rs.on('disconnected', stateSetter(this, 'initial'));
this.rs.on('connecting', stateSetter(this, 'authing'));
this.rs.on('authing', stateSetter(this, 'authing'));
this.rs.on('error', errorsHandler(this));
if (this.rs.remote) {
this.rs.remote.on('wire-busy', function (evt) {
if (flashFor(evt)) {
requestsToFlashFor++;
stateSetter(self, 'busy')();
}
});
this.rs.remote.on('wire-done', function (evt) {
if (flashFor(evt)) {
requestsToFlashFor--;
}
if (requestsToFlashFor <= 0 && evt.success) {
stateSetter(self, 'connected')();
}
});
}
if (hasLocalStorage) {
var state = localStorage[LS_STATE_KEY];
if (state && VALID_ENTRY_STATES[state]) {
this._rememberedState = state;
}
}
};
RemoteStorage.Widget.prototype = {
/**
* Method: display
*
* Displays the widget via the view.display method
*
* Parameters:
*
* options
**/
display: function (options) {
if (typeof(options) === 'string') {
options = { domID: options };
} else if (typeof(options) === 'undefined') {
options = {};
}
if (! this.view) {
this.setView(new RemoteStorage.Widget.View(this.rs));
}
this.view.display(options);
return this;
},
linkWidgetToSync: function () {
if (typeof(this.rs.sync) === 'object' && typeof(this.rs.sync.sync) === 'function') {
this.view.on('sync', this.rs.sync.sync.bind(this.rs.sync));
} else {
RemoteStorage.log('[Widget] typeof this.rs.sync check fail', this.rs.sync);
setTimeout(this.linkWidgetToSync.bind(this), 1000);
}
},
/**
* Method: setView(view)
*
* Sets the view and initializes event listeners to react on
* widget (widget.view) events
**/
setView: function (view) {
this.view = view;
this.view.on('connect', function (options) {
if (typeof(options) === 'string') {
// options is simply a useraddress
this.rs.connect(options);
} else if (options.special) {
this.rs[options.special].connect(options);
}
}.bind(this));
this.view.on('secret-entered', function (secretKey) {
this.view.setUserSecretKey(secretKey);
stateSetter(this, 'ciphered')();
}.bind(this));
this.view.on('secret-cancelled', function () {
stateSetter(this, 'notciphered')();
}.bind(this));
this.view.on('disconnect', this.rs.disconnect.bind(this.rs));
this.linkWidgetToSync();
try {
this.view.on('reset', function (){
var location = RemoteStorage.Authorize.getLocation();
this.rs.on('disconnected', location.reload.bind(location));
this.rs.disconnect();
}.bind(this));
} catch(e) {
if (!(e.message && e.message.match(/Unknown event/))) { // ignored. (the 0.7 widget-view interface didn't have a 'reset' event)
throw e;
}
}
if (this._rememberedState) {
setTimeout(stateSetter(this, this._rememberedState), 0);
delete this._rememberedState;
}
}
};
/**
* Method: displayWidget
*
* Same as <display>
**/
RemoteStorage.prototype.displayWidget = function (options) {
return this.widget.display(options);
};
RemoteStorage.Widget._rs_init = function (remoteStorage) {
hasLocalStorage = RemoteStorage.util.localStorageAvailable();
if (! remoteStorage.widget) {
remoteStorage.widget = new RemoteStorage.Widget(remoteStorage);
}
};
RemoteStorage.Widget._rs_supported = function (remoteStorage) {
return typeof(document) !== 'undefined';
};
function stateSetter(widget, state) {
RemoteStorage.log('[Widget] Producing stateSetter for', state);
return function () {
RemoteStorage.log('[Widget] Setting state', state, arguments);
if (hasLocalStorage) {
localStorage[LS_STATE_KEY] = state;
}
if (widget.view) {
if (widget.rs.remote) {
widget.view.setUserAddress(widget.rs.remote.userAddress);
}
widget.view.setState(state, arguments);
} else {
widget._rememberedState = state;
}
};
}
function errorsHandler(widget) {
return function (error) {
var s;
if (error instanceof RemoteStorage.DiscoveryError) {
console.error('Discovery failed', error, '"' + error.message + '"');
s = stateSetter(widget, 'initial', [error.message]);
} else if (error instanceof RemoteStorage.SyncError) {
s = stateSetter(widget, 'offline', []);
} else if (error instanceof RemoteStorage.Unauthorized) {
s = stateSetter(widget, 'unauthorized');
} else {
RemoteStorage.log('[Widget] Unknown error');
s = stateSetter(widget, 'error', [error]);
}
s.apply();
};
}
function flashFor(evt) {
if (evt.method === 'GET' && evt.isFolder) {
return false;
}
return true;
}
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: src/view.js **/
(function (window){
var t = RemoteStorage.I18n.translate;
/**
* Class: RemoteStorage.Widget.View
*
* Controls the visible widget
*
* States:
*
* initial - not connected
* authing - in auth flow
* connected - connected to remote storage, not syncing at the moment
* ciphered - connected, with cipher
* notciphered - connected, without cipher
* busy - connected, syncing at the moment
* offline - connected, but no network connectivity
* error - connected, but sync error happened
* unauthorized - connected, but request returned 401
**/
RemoteStorage.Widget.View = function (remoteStorage) {
this.rs = remoteStorage;
if (typeof(document) === 'undefined') {
throw "Widget not supported";
}
RemoteStorage.eventHandling(this,
'connect',
'secret-entered',
'secret-cancelled',
'disconnect',
'sync',
'display',
'reset');
// Re-binding the event so they can be called from the window
for (var event in this.events){
this.events[event] = this.events[event].bind(this);
}
this.hideBubbleOnBodyClick = function (event) {
for (var p = event.target; p !== document.body; p = p.parentElement) {
if (p.id === 'remotestorage-widget') {
return;
}
}
this.hideBubble();
}.bind(this);
};
RemoteStorage.Widget.View.prototype = {
connectGdrive: function () {
this._emit('connect', { special: 'googledrive' });
},
connectDropbox: function (){
this._emit('connect', { special: 'dropbox'});
},
/**
* Method: setState
*
* Call the function that applies the state to the widget
*
* Parameters:
*
* state
* args
**/
setState: function (state, args) {
RemoteStorage.log('[View] widget.view.setState(',state,',',args,');');
var s = this.states[state];
if (typeof(s) === 'undefined') {
throw new Error("Bad State assigned to view: " + state);
}
s.apply(this, args);
},
/**
* Method: setUserAddress
*
* Set user address of the input field
**/
setUserAddress: function (addr) {
this.userAddress = addr || '';
var el;
if (this.div && (el = this.div.querySelector('form.remotestorage-initial').userAddress)) {
el.value = this.userAddress;
}
},
/**
* Method: setUserSecretKey
*
* Set user secret key
**/
setUserSecretKey: function (secretKey) {
this.userSecretKey = secretKey;
},
/**
* Method: toggleBubble
*
* Show the bubble when hidden and the other way around
**/
toggleBubble: function (event) {
if (this.bubble.className.search('rs-hidden') < 0) {
this.hideBubble(event);
} else {
this.showBubble(event);
}
},
/**
* Method: hideBubble
*
* Hide the bubble
**/
hideBubble: function (){
addClass(this.bubble, 'rs-hidden');
document.body.removeEventListener('click', this.hideBubbleOnBodyClick);
},
/**
* Method: showBubble
*
* Show the bubble
**/
showBubble: function (event){
removeClass(this.bubble, 'rs-hidden');
if (typeof(event) !== 'undefined') {
stopPropagation(event);
}
document.body.addEventListener('click', this.hideBubbleOnBodyClick);
if (this.div.querySelector('.remotestorage-connected').classList.contains('remotestorage-cipher') && !this.userSecretKey) {
this.bubble.querySelector('form.remotestorage-cipher-form').userSecretKey.focus();
} else {
this.bubble.querySelector('form.remotestorage-initial').userAddress.focus();
}
},
/**
* Method: display
*
* Draw the widget inside of the dom element with the id options.domID
*
* Parameters:
*
* options
*
* Returns:
*
* The widget div
**/
display: function (options) {
if (typeof this.div !== 'undefined') {
return this.div;
}
var element = document.createElement('div');
var style = document.createElement('style');
style.innerHTML = RemoteStorage.Assets.widgetCss;
element.id = "remotestorage-widget";
element.innerHTML = RemoteStorage.Assets.widget;
element.appendChild(style);
if (options.domID) {
var parent = document.getElementById(options.domID);
if (! parent) {
throw "Failed to find target DOM element with id=\"" + options.domID + "\"";
}
parent.appendChild(element);
} else {
document.body.appendChild(element);
}
// Sync button
setupButton(element, 'rs-sync', 'syncIcon', this.events.sync);
// Disconnect button
setupButton(element, 'rs-disconnect', 'disconnectIcon', this.events.disconnect);
// Get me out of here
setupButton(element, 'remotestorage-reset', undefined, this.events.reset);
// Connect button
var connectButton = setupButton(element, 'connect', 'connectIcon', this.events.connect);
// Handle connectButton state
this.form = element.querySelector('form.remotestorage-initial');
var el = this.form.userAddress;
el.addEventListener('load', handleButtonState);
el.addEventListener('keyup', handleButtonState);
if (this.userAddress) {
el.value = this.userAddress;
}
if (options.encryption) {
this.cipher = true;
var secretKeyInput = element.querySelector('form.remotestorage-cipher-form').userSecretKey;
// This is to avoid the 'password field on an insecured page' warning, when not used and on http (not https)
secretKeyInput.type = 'password';
// Cipher button
var cipherButton = setupButton(element, 'rs-cipher', 'cipherIcon', this.events['secret-entered']);
// Handle cipherButton state
secretKeyInput.addEventListener('load', handleButtonState);
secretKeyInput.addEventListener('keyup', handleButtonState);
// No cipher button
setupButton(element, 'rs-nocipher', 'nocipherIcon', this.events['secret-cancelled']);
}
// The cube
this.cube = setupButton(element, 'rs-cube', 'remoteStorageIcon', this.toggleBubble.bind(this));
// Google Drive and Dropbox icons
setupButton(element, 'rs-dropbox', 'dropbox', this.connectDropbox.bind(this));
setupButton(element, 'rs-googledrive', 'googledrive', this.connectGdrive.bind(this));
var bubbleDontCatch = { INPUT: true, BUTTON: true, IMG: true };
var eventListener = function (event) {
if (! bubbleDontCatch[event.target.tagName] && ! (this.div.classList.contains('remotestorage-state-unauthorized') )) {
this.showBubble(event);
}
}.bind(this);
this.bubble = setupButton(element, 'rs-bubble', undefined, eventListener);
this.hideBubble();
this.div = element;
this.states.initial.call(this);
this.events.display.call(this);
return this.div;
},
states: {
initial: function (message) {
var cube = this.cube;
var info = message || t("view_info");
cube.src = RemoteStorage.Assets.remoteStorageIcon;
this._renderTranslatedInitialContent();
if (message) {
cube.src = RemoteStorage.Assets.remoteStorageIconError;
removeClass(this.cube, 'remotestorage-loading');
this.showBubble();
// Show the red error cube for 5 seconds, then show the normal orange one again
setTimeout(function (){
cube.src = RemoteStorage.Assets.remoteStorageIcon;
},2000);
} else {
this.hideBubble();
}
this.div.className = "remotestorage-state-initial";
if (this.userSecretKey) {
delete this.userSecretKey;
}
// Google Drive and Dropbox icons
var backends = 1;
if (this._activateBackend('dropbox')) { backends += 1; }
if (this._activateBackend('googledrive')) { backends += 1; }
this.div.querySelector('.rs-bubble-text').style.paddingRight = backends*32+8+'px';
// If address not empty connect button enabled
var cb = this.div.querySelector('.connect');
if (this.form.userAddress.value) {
cb.removeAttribute('disabled');
}
var infoEl = this.div.querySelector('.rs-info-msg');
infoEl.innerHTML = info;
if (message) {
infoEl.classList.add('remotestorage-error-info');
} else {
infoEl.classList.remove('remotestorage-error-info');
}
},
authing: function () {
this.div.removeEventListener('click', this.events.connect);
this.div.className = "remotestorage-state-authing";
this.div.querySelector('.rs-status-text').innerHTML = t("view_connecting", this.userAddress);
addClass(this.cube, 'remotestorage-loading');
},
connected: function () {
var cube = this.cube;
this.div.className = "remotestorage-state-connected";
this.div.querySelector('.userAddress').innerHTML = this.userAddress;
cube.src = RemoteStorage.Assets.remoteStorageIcon;
removeClass(cube, 'remotestorage-loading');
if (this.cipher) {
if (this.userSecretKey) {
if (this.userSecretKeyError) {
cube.src = RemoteStorage.Assets.remoteStorageIconError;
addClass(this.div.querySelector('.remotestorage-connected'), 'remotestorage-cipher');
addClass(this.div.querySelector('.remotestorage-invalid-key'), 'remotestorage-cipher-error');
this.showBubble();
// Show the red error cube for 5 seconds, then show the normal orange one again
setTimeout(function (){
cube.src = RemoteStorage.Assets.remoteStorageIcon;
},5000);
} else {
removeClass(this.div.querySelector('.remotestorage-invalid-key'), 'remotestorage-cipher-error');
cube.src = RemoteStorage.Assets.remoteStorageIconCiphered;
}
} else {
addClass(this.div.querySelector('.remotestorage-connected'), 'remotestorage-cipher');
this.showBubble();
}
}
var icons = {
googledrive: this.div.querySelector('.rs-googledrive'),
dropbox: this.div.querySelector('.rs-dropbox')
};
icons.googledrive.style.display = icons.dropbox.style.display = 'none';
if (icons[this.rs.backend]) {
icons[this.rs.backend].style.display = 'inline-block';
this.div.querySelector('.rs-bubble-text').style.paddingRight = 2*32+8+'px';
} else {
this.div.querySelector('.rs-bubble-text').style.paddingRight = 32+8+'px';
}
},
ciphered: function () {
this.div.querySelector('form.remotestorage-cipher-form').userSecretKey.value = '';
removeClass(this.div.querySelector('.remotestorage-invalid-key'), 'remotestorage-cipher-error');
removeClass(this.div.querySelector('.remotestorage-connected'), 'remotestorage-cipher');
this.cube.src = RemoteStorage.Assets.remoteStorageIconCiphered;
this.hideBubble();
},
notciphered: function () {
this.cipher = false;
removeClass(this.div.querySelector('.remotestorage-invalid-key'), 'remotestorage-cipher-error');
removeClass(this.div.querySelector('.remotestorage-connected'), 'remotestorage-cipher');
this.hideBubble();
},
busy: function () {
this.div.className = "remotestorage-state-busy";
addClass(this.cube, 'remotestorage-loading'); //TODO needs to be undone when is that neccesary
},
offline: function () {
this.div.className = "remotestorage-state-offline";
this.cube.src = RemoteStorage.Assets.remoteStorageIconOffline;
this.div.querySelector('.rs-status-text').innerHTML = t("view_offline");
},
error: function (err) {
var errorMsg = err;
this.div.className = "remotestorage-state-error";
this.div.querySelector('.rs-bubble-text').innerHTML = '<strong>'+t('view_error_occured')+'</strong>';
//FIXME I don't know what an DOMError is and my browser doesn't know too(how to handle this?)
if (err instanceof Error /*|| err instanceof DOMError*/) {
errorMsg = err.message + '\n\n' +
err.stack;
}
this.div.querySelector('.rs-error-msg').textContent = errorMsg;
this.cube.src = RemoteStorage.Assets.remoteStorageIconError;
this.showBubble();
},
unauthorized: function () {
this.div.className = "remotestorage-state-unauthorized";
this.cube.src = RemoteStorage.Assets.remoteStorageIconError;
this.showBubble();
this.div.addEventListener('click', this.events.connect);
}
},
events: {
/**
* Event: connect
*
* Emitted when the connect button is clicked
**/
connect: function (event) {
stopPropagation(event);
event.preventDefault();
this._emit('connect', this.div.querySelector('form.remotestorage-initial').userAddress.value);
},
/**
* Event: secret-entered
*
* Emitted when the cipher button is clicked
**/
'secret-entered': function (event) {
stopPropagation(event);
event.preventDefault();
this._emit('secret-entered', this.div.querySelector('form.remotestorage-cipher-form').userSecretKey.value);
},
/**
* Event: secret-cancelled
*
* Emitted when the nocipher button is clicked
**/
'secret-cancelled': function (event) {
stopPropagation(event);
event.preventDefault();
this._emit('secret-cancelled');
},
/**
* Event: sync
*
* Emitted when the sync button is clicked
**/
sync: function (event) {
stopPropagation(event);
event.preventDefault();
this._emit('sync');
},
/**
* Event: disconnect
*
* Emitted when the disconnect button is clicked
**/
disconnect: function (event) {
stopPropagation(event);
event.preventDefault();
this._emit('disconnect');
},
/**
* Event: reset
*
* Emitted after crash triggers disconnect
**/
reset: function (event){
event.preventDefault();
var result = window.confirm(t('view_confirm_reset'));
if (result){
this._emit('reset');
}
},
/**
* Event: display
*
* Emitted when finished displaying the widget
**/
display : function (event) {
if (event) {
event.preventDefault();
}
this._emit('display');
}
},
_renderTranslatedInitialContent: function () {
this.div.querySelector('.rs-status-text').innerHTML = t("view_connect");
this.div.querySelector('.remotestorage-reset').innerHTML = t("view_get_me_out");
this.div.querySelector('.rs-error-plz-report').innerHTML = t("view_error_plz_report");
this.div.querySelector('.remotestorage-unauthorized').innerHTML = t("view_unauthorized");
this.div.querySelector('.remotestorage-invalid-key').innerHTML = t("view_invalid_key");
},
_activateBackend: function activateBackend(backendName) {
var className = 'rs-' + backendName;
if (this.rs.apiKeys[backendName]) {
this.div.querySelector('.' + className).style.display = 'inline-block';
return true;
} else {
this.div.querySelector('.' + className).style.display = 'none';
return false;
}
}
};
function removeClass(el, className) {
return el.classList.remove(className);
}
function addClass(el, className) {
return el.classList.add(className);
}
function stopPropagation(event) {
if (typeof(event.stopPropagation) === 'function') {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
}
function setupButton(parent, className, iconName, eventListener) {
var element = parent.querySelector('.' + className);
if (typeof iconName !== 'undefined') {
var img = element.querySelector('img');
(img || element).src = RemoteStorage.Assets[iconName];
}
element.addEventListener('click', eventListener);
return element;
}
function handleButtonState(event) {
if (event.target.value) {
event.target.nextElementSibling.removeAttribute('disabled');
} else {
event.target.nextElementSibling.setAttribute('disabled','disabled');
}
}
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: node_modules/tv4/tv4.js **/
/*
Author: Geraint Luff and others
Year: 2013
This code is released into the "public domain" by its author(s). Anybody may use, alter and distribute the code without restriction. The author makes no guarantees, and takes no liability of any kind for use of this code.
If you find a bug or make an improvement, it would be courteous to let the author know, but it is not compulsory.
*/
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else if (typeof module !== 'undefined' && module.exports){
// CommonJS. Define export.
module.exports = factory();
} else {
// Browser globals
global.tv4 = factory();
}
}(this, function () {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FObject%2Fkeys
if (!Object.keys) {
Object.keys = (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function (obj) {
if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
throw new TypeError('Object.keys called on non-object');
}
var result = [];
for (var prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (var i=0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
})();
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
if (!Object.create) {
Object.create = (function(){
function F(){}
return function(o){
if (arguments.length !== 1) {
throw new Error('Object.create implementation only accepts one parameter.');
}
F.prototype = o;
return new F();
};
})();
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2FisArray
if(!Array.isArray) {
Array.isArray = function (vArg) {
return Object.prototype.toString.call(vArg) === "[object Array]";
};
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2FindexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
if (this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n !== n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n !== 0 && n !== Infinity && n !== -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
// Grungey Object.isFrozen hack
if (!Object.isFrozen) {
Object.isFrozen = function (obj) {
var key = "tv4_test_frozen_key";
while (obj.hasOwnProperty(key)) {
key += Math.random();
}
try {
obj[key] = true;
delete obj[key];
return false;
} catch (e) {
return true;
}
};
}
// Based on: https://github.com/geraintluff/uri-templates, but with all the de-substitution stuff removed
var uriTemplateGlobalModifiers = {
"+": true,
"#": true,
".": true,
"/": true,
";": true,
"?": true,
"&": true
};
var uriTemplateSuffices = {
"*": true
};
function notReallyPercentEncode(string) {
return encodeURI(string).replace(/%25[0-9][0-9]/g, function (doubleEncoded) {
return "%" + doubleEncoded.substring(3);
});
}
function uriTemplateSubstitution(spec) {
var modifier = "";
if (uriTemplateGlobalModifiers[spec.charAt(0)]) {
modifier = spec.charAt(0);
spec = spec.substring(1);
}
var separator = "";
var prefix = "";
var shouldEscape = true;
var showVariables = false;
var trimEmptyString = false;
if (modifier === '+') {
shouldEscape = false;
} else if (modifier === ".") {
prefix = ".";
separator = ".";
} else if (modifier === "/") {
prefix = "/";
separator = "/";
} else if (modifier === '#') {
prefix = "#";
shouldEscape = false;
} else if (modifier === ';') {
prefix = ";";
separator = ";";
showVariables = true;
trimEmptyString = true;
} else if (modifier === '?') {
prefix = "?";
separator = "&";
showVariables = true;
} else if (modifier === '&') {
prefix = "&";
separator = "&";
showVariables = true;
}
var varNames = [];
var varList = spec.split(",");
var varSpecs = [];
var varSpecMap = {};
for (var i = 0; i < varList.length; i++) {
var varName = varList[i];
var truncate = null;
if (varName.indexOf(":") !== -1) {
var parts = varName.split(":");
varName = parts[0];
truncate = parseInt(parts[1], 10);
}
var suffices = {};
while (uriTemplateSuffices[varName.charAt(varName.length - 1)]) {
suffices[varName.charAt(varName.length - 1)] = true;
varName = varName.substring(0, varName.length - 1);
}
var varSpec = {
truncate: truncate,
name: varName,
suffices: suffices
};
varSpecs.push(varSpec);
varSpecMap[varName] = varSpec;
varNames.push(varName);
}
var subFunction = function (valueFunction) {
var result = "";
var startIndex = 0;
for (var i = 0; i < varSpecs.length; i++) {
var varSpec = varSpecs[i];
var value = valueFunction(varSpec.name);
if (value === null || value === undefined || (Array.isArray(value) && value.length === 0) || (typeof value === 'object' && Object.keys(value).length === 0)) {
startIndex++;
continue;
}
if (i === startIndex) {
result += prefix;
} else {
result += (separator || ",");
}
if (Array.isArray(value)) {
if (showVariables) {
result += varSpec.name + "=";
}
for (var j = 0; j < value.length; j++) {
if (j > 0) {
result += varSpec.suffices['*'] ? (separator || ",") : ",";
if (varSpec.suffices['*'] && showVariables) {
result += varSpec.name + "=";
}
}
result += shouldEscape ? encodeURIComponent(value[j]).replace(/!/g, "%21") : notReallyPercentEncode(value[j]);
}
} else if (typeof value === "object") {
if (showVariables && !varSpec.suffices['*']) {
result += varSpec.name + "=";
}
var first = true;
for (var key in value) {
if (!first) {
result += varSpec.suffices['*'] ? (separator || ",") : ",";
}
first = false;
result += shouldEscape ? encodeURIComponent(key).replace(/!/g, "%21") : notReallyPercentEncode(key);
result += varSpec.suffices['*'] ? '=' : ",";
result += shouldEscape ? encodeURIComponent(value[key]).replace(/!/g, "%21") : notReallyPercentEncode(value[key]);
}
} else {
if (showVariables) {
result += varSpec.name;
if (!trimEmptyString || value !== "") {
result += "=";
}
}
if (varSpec.truncate != null) {
value = value.substring(0, varSpec.truncate);
}
result += shouldEscape ? encodeURIComponent(value).replace(/!/g, "%21"): notReallyPercentEncode(value);
}
}
return result;
};
subFunction.varNames = varNames;
return {
prefix: prefix,
substitution: subFunction
};
}
function UriTemplate(template) {
if (!(this instanceof UriTemplate)) {
return new UriTemplate(template);
}
var parts = template.split("{");
var textParts = [parts.shift()];
var prefixes = [];
var substitutions = [];
var varNames = [];
while (parts.length > 0) {
var part = parts.shift();
var spec = part.split("}")[0];
var remainder = part.substring(spec.length + 1);
var funcs = uriTemplateSubstitution(spec);
substitutions.push(funcs.substitution);
prefixes.push(funcs.prefix);
textParts.push(remainder);
varNames = varNames.concat(funcs.substitution.varNames);
}
this.fill = function (valueFunction) {
var result = textParts[0];
for (var i = 0; i < substitutions.length; i++) {
var substitution = substitutions[i];
result += substitution(valueFunction);
result += textParts[i + 1];
}
return result;
};
this.varNames = varNames;
this.template = template;
}
UriTemplate.prototype = {
toString: function () {
return this.template;
},
fillFromObject: function (obj) {
return this.fill(function (varName) {
return obj[varName];
});
}
};
var ValidatorContext = function ValidatorContext(parent, collectMultiple, errorReporter, checkRecursive, trackUnknownProperties) {
this.missing = [];
this.missingMap = {};
this.formatValidators = parent ? Object.create(parent.formatValidators) : {};
this.schemas = parent ? Object.create(parent.schemas) : {};
this.collectMultiple = collectMultiple;
this.errors = [];
this.handleError = collectMultiple ? this.collectError : this.returnError;
if (checkRecursive) {
this.checkRecursive = true;
this.scanned = [];
this.scannedFrozen = [];
this.scannedFrozenSchemas = [];
this.scannedFrozenValidationErrors = [];
this.validatedSchemasKey = 'tv4_validation_id';
this.validationErrorsKey = 'tv4_validation_errors_id';
}
if (trackUnknownProperties) {
this.trackUnknownProperties = true;
this.knownPropertyPaths = {};
this.unknownPropertyPaths = {};
}
this.errorReporter = errorReporter || defaultErrorReporter('en');
if (typeof this.errorReporter === 'string') {
throw new Error('debug');
}
this.definedKeywords = {};
if (parent) {
for (var key in parent.definedKeywords) {
this.definedKeywords[key] = parent.definedKeywords[key].slice(0);
}
}
};
ValidatorContext.prototype.defineKeyword = function (keyword, keywordFunction) {
this.definedKeywords[keyword] = this.definedKeywords[keyword] || [];
this.definedKeywords[keyword].push(keywordFunction);
};
ValidatorContext.prototype.createError = function (code, messageParams, dataPath, schemaPath, subErrors, data, schema) {
var error = new ValidationError(code, messageParams, dataPath, schemaPath, subErrors);
error.message = this.errorReporter(error, data, schema);
return error;
};
ValidatorContext.prototype.returnError = function (error) {
return error;
};
ValidatorContext.prototype.collectError = function (error) {
if (error) {
this.errors.push(error);
}
return null;
};
ValidatorContext.prototype.prefixErrors = function (startIndex, dataPath, schemaPath) {
for (var i = startIndex; i < this.errors.length; i++) {
this.errors[i] = this.errors[i].prefixWith(dataPath, schemaPath);
}
return this;
};
ValidatorContext.prototype.banUnknownProperties = function (data, schema) {
for (var unknownPath in this.unknownPropertyPaths) {
var error = this.createError(ErrorCodes.UNKNOWN_PROPERTY, {path: unknownPath}, unknownPath, "", null, data, schema);
var result = this.handleError(error);
if (result) {
return result;
}
}
return null;
};
ValidatorContext.prototype.addFormat = function (format, validator) {
if (typeof format === 'object') {
for (var key in format) {
this.addFormat(key, format[key]);
}
return this;
}
this.formatValidators[format] = validator;
};
ValidatorContext.prototype.resolveRefs = function (schema, urlHistory) {
if (schema['$ref'] !== undefined) {
urlHistory = urlHistory || {};
if (urlHistory[schema['$ref']]) {
return this.createError(ErrorCodes.CIRCULAR_REFERENCE, {urls: Object.keys(urlHistory).join(', ')}, '', '', null, undefined, schema);
}
urlHistory[schema['$ref']] = true;
schema = this.getSchema(schema['$ref'], urlHistory);
}
return schema;
};
ValidatorContext.prototype.getSchema = function (url, urlHistory) {
var schema;
if (this.schemas[url] !== undefined) {
schema = this.schemas[url];
return this.resolveRefs(schema, urlHistory);
}
var baseUrl = url;
var fragment = "";
if (url.indexOf('#') !== -1) {
fragment = url.substring(url.indexOf("#") + 1);
baseUrl = url.substring(0, url.indexOf("#"));
}
if (typeof this.schemas[baseUrl] === 'object') {
schema = this.schemas[baseUrl];
var pointerPath = decodeURIComponent(fragment);
if (pointerPath === "") {
return this.resolveRefs(schema, urlHistory);
} else if (pointerPath.charAt(0) !== "/") {
return undefined;
}
var parts = pointerPath.split("/").slice(1);
for (var i = 0; i < parts.length; i++) {
var component = parts[i].replace(/~1/g, "/").replace(/~0/g, "~");
if (schema[component] === undefined) {
schema = undefined;
break;
}
schema = schema[component];
}
if (schema !== undefined) {
return this.resolveRefs(schema, urlHistory);
}
}
if (this.missing[baseUrl] === undefined) {
this.missing.push(baseUrl);
this.missing[baseUrl] = baseUrl;
this.missingMap[baseUrl] = baseUrl;
}
};
ValidatorContext.prototype.searchSchemas = function (schema, url) {
if (Array.isArray(schema)) {
for (var i = 0; i < schema.length; i++) {
this.searchSchemas(schema[i], url);
}
} else if (schema && typeof schema === "object") {
if (typeof schema.id === "string") {
if (isTrustedUrl(url, schema.id)) {
if (this.schemas[schema.id] === undefined) {
this.schemas[schema.id] = schema;
}
}
}
for (var key in schema) {
if (key !== "enum") {
if (typeof schema[key] === "object") {
this.searchSchemas(schema[key], url);
} else if (key === "$ref") {
var uri = getDocumentUri(schema[key]);
if (uri && this.schemas[uri] === undefined && this.missingMap[uri] === undefined) {
this.missingMap[uri] = uri;
}
}
}
}
}
};
ValidatorContext.prototype.addSchema = function (url, schema) {
//overload
if (typeof url !== 'string' || typeof schema === 'undefined') {
if (typeof url === 'object' && typeof url.id === 'string') {
schema = url;
url = schema.id;
}
else {
return;
}
}
if (url === getDocumentUri(url) + "#") {
// Remove empty fragment
url = getDocumentUri(url);
}
this.schemas[url] = schema;
delete this.missingMap[url];
normSchema(schema, url);
this.searchSchemas(schema, url);
};
ValidatorContext.prototype.getSchemaMap = function () {
var map = {};
for (var key in this.schemas) {
map[key] = this.schemas[key];
}
return map;
};
ValidatorContext.prototype.getSchemaUris = function (filterRegExp) {
var list = [];
for (var key in this.schemas) {
if (!filterRegExp || filterRegExp.test(key)) {
list.push(key);
}
}
return list;
};
ValidatorContext.prototype.getMissingUris = function (filterRegExp) {
var list = [];
for (var key in this.missingMap) {
if (!filterRegExp || filterRegExp.test(key)) {
list.push(key);
}
}
return list;
};
ValidatorContext.prototype.dropSchemas = function () {
this.schemas = {};
this.reset();
};
ValidatorContext.prototype.reset = function () {
this.missing = [];
this.missingMap = {};
this.errors = [];
};
ValidatorContext.prototype.validateAll = function (data, schema, dataPathParts, schemaPathParts, dataPointerPath) {
var topLevel;
schema = this.resolveRefs(schema);
if (!schema) {
return null;
} else if (schema instanceof ValidationError) {
this.errors.push(schema);
return schema;
}
var startErrorCount = this.errors.length;
var frozenIndex, scannedFrozenSchemaIndex = null, scannedSchemasIndex = null;
if (this.checkRecursive && data && typeof data === 'object') {
topLevel = !this.scanned.length;
if (data[this.validatedSchemasKey]) {
var schemaIndex = data[this.validatedSchemasKey].indexOf(schema);
if (schemaIndex !== -1) {
this.errors = this.errors.concat(data[this.validationErrorsKey][schemaIndex]);
return null;
}
}
if (Object.isFrozen(data)) {
frozenIndex = this.scannedFrozen.indexOf(data);
if (frozenIndex !== -1) {
var frozenSchemaIndex = this.scannedFrozenSchemas[frozenIndex].indexOf(schema);
if (frozenSchemaIndex !== -1) {
this.errors = this.errors.concat(this.scannedFrozenValidationErrors[frozenIndex][frozenSchemaIndex]);
return null;
}
}
}
this.scanned.push(data);
if (Object.isFrozen(data)) {
if (frozenIndex === -1) {
frozenIndex = this.scannedFrozen.length;
this.scannedFrozen.push(data);
this.scannedFrozenSchemas.push([]);
}
scannedFrozenSchemaIndex = this.scannedFrozenSchemas[frozenIndex].length;
this.scannedFrozenSchemas[frozenIndex][scannedFrozenSchemaIndex] = schema;
this.scannedFrozenValidationErrors[frozenIndex][scannedFrozenSchemaIndex] = [];
} else {
if (!data[this.validatedSchemasKey]) {
try {
Object.defineProperty(data, this.validatedSchemasKey, {
value: [],
configurable: true
});
Object.defineProperty(data, this.validationErrorsKey, {
value: [],
configurable: true
});
} catch (e) {
//IE 7/8 workaround
data[this.validatedSchemasKey] = [];
data[this.validationErrorsKey] = [];
}
}
scannedSchemasIndex = data[this.validatedSchemasKey].length;
data[this.validatedSchemasKey][scannedSchemasIndex] = schema;
data[this.validationErrorsKey][scannedSchemasIndex] = [];
}
}
var errorCount = this.errors.length;
var error = this.validateBasic(data, schema, dataPointerPath)
|| this.validateNumeric(data, schema, dataPointerPath)
|| this.validateString(data, schema, dataPointerPath)
|| this.validateArray(data, schema, dataPointerPath)
|| this.validateObject(data, schema, dataPointerPath)
|| this.validateCombinations(data, schema, dataPointerPath)
|| this.validateHypermedia(data, schema, dataPointerPath)
|| this.validateFormat(data, schema, dataPointerPath)
|| this.validateDefinedKeywords(data, schema, dataPointerPath)
|| null;
if (topLevel) {
while (this.scanned.length) {
var item = this.scanned.pop();
delete item[this.validatedSchemasKey];
}
this.scannedFrozen = [];
this.scannedFrozenSchemas = [];
}
if (error || errorCount !== this.errors.length) {
while ((dataPathParts && dataPathParts.length) || (schemaPathParts && schemaPathParts.length)) {
var dataPart = (dataPathParts && dataPathParts.length) ? "" + dataPathParts.pop() : null;
var schemaPart = (schemaPathParts && schemaPathParts.length) ? "" + schemaPathParts.pop() : null;
if (error) {
error = error.prefixWith(dataPart, schemaPart);
}
this.prefixErrors(errorCount, dataPart, schemaPart);
}
}
if (scannedFrozenSchemaIndex !== null) {
this.scannedFrozenValidationErrors[frozenIndex][scannedFrozenSchemaIndex] = this.errors.slice(startErrorCount);
} else if (scannedSchemasIndex !== null) {
data[this.validationErrorsKey][scannedSchemasIndex] = this.errors.slice(startErrorCount);
}
return this.handleError(error);
};
ValidatorContext.prototype.validateFormat = function (data, schema) {
if (typeof schema.format !== 'string' || !this.formatValidators[schema.format]) {
return null;
}
var errorMessage = this.formatValidators[schema.format].call(null, data, schema);
if (typeof errorMessage === 'string' || typeof errorMessage === 'number') {
return this.createError(ErrorCodes.FORMAT_CUSTOM, {message: errorMessage}, '', '/format', null, data, schema);
} else if (errorMessage && typeof errorMessage === 'object') {
return this.createError(ErrorCodes.FORMAT_CUSTOM, {message: errorMessage.message || "?"}, errorMessage.dataPath || '', errorMessage.schemaPath || "/format", null, data, schema);
}
return null;
};
ValidatorContext.prototype.validateDefinedKeywords = function (data, schema, dataPointerPath) {
for (var key in this.definedKeywords) {
if (typeof schema[key] === 'undefined') {
continue;
}
var validationFunctions = this.definedKeywords[key];
for (var i = 0; i < validationFunctions.length; i++) {
var func = validationFunctions[i];
var result = func(data, schema[key], schema, dataPointerPath);
if (typeof result === 'string' || typeof result === 'number') {
return this.createError(ErrorCodes.KEYWORD_CUSTOM, {key: key, message: result}, '', '', null, data, schema).prefixWith(null, key);
} else if (result && typeof result === 'object') {
var code = result.code;
if (typeof code === 'string') {
if (!ErrorCodes[code]) {
throw new Error('Undefined error code (use defineError): ' + code);
}
code = ErrorCodes[code];
} else if (typeof code !== 'number') {
code = ErrorCodes.KEYWORD_CUSTOM;
}
var messageParams = (typeof result.message === 'object') ? result.message : {key: key, message: result.message || "?"};
var schemaPath = result.schemaPath || ("/" + key.replace(/~/g, '~0').replace(/\//g, '~1'));
return this.createError(code, messageParams, result.dataPath || null, schemaPath, null, data, schema);
}
}
}
return null;
};
function recursiveCompare(A, B) {
if (A === B) {
return true;
}
if (A && B && typeof A === "object" && typeof B === "object") {
if (Array.isArray(A) !== Array.isArray(B)) {
return false;
} else if (Array.isArray(A)) {
if (A.length !== B.length) {
return false;
}
for (var i = 0; i < A.length; i++) {
if (!recursiveCompare(A[i], B[i])) {
return false;
}
}
} else {
var key;
for (key in A) {
if (B[key] === undefined && A[key] !== undefined) {
return false;
}
}
for (key in B) {
if (A[key] === undefined && B[key] !== undefined) {
return false;
}
}
for (key in A) {
if (!recursiveCompare(A[key], B[key])) {
return false;
}
}
}
return true;
}
return false;
}
ValidatorContext.prototype.validateBasic = function validateBasic(data, schema, dataPointerPath) {
var error;
if (error = this.validateType(data, schema, dataPointerPath)) {
return error.prefixWith(null, "type");
}
if (error = this.validateEnum(data, schema, dataPointerPath)) {
return error.prefixWith(null, "type");
}
return null;
};
ValidatorContext.prototype.validateType = function validateType(data, schema) {
if (schema.type === undefined) {
return null;
}
var dataType = typeof data;
if (data === null) {
dataType = "null";
} else if (Array.isArray(data)) {
dataType = "array";
}
var allowedTypes = schema.type;
if (!Array.isArray(allowedTypes)) {
allowedTypes = [allowedTypes];
}
for (var i = 0; i < allowedTypes.length; i++) {
var type = allowedTypes[i];
if (type === dataType || (type === "integer" && dataType === "number" && (data % 1 === 0))) {
return null;
}
}
return this.createError(ErrorCodes.INVALID_TYPE, {type: dataType, expected: allowedTypes.join("/")}, '', '', null, data, schema);
};
ValidatorContext.prototype.validateEnum = function validateEnum(data, schema) {
if (schema["enum"] === undefined) {
return null;
}
for (var i = 0; i < schema["enum"].length; i++) {
var enumVal = schema["enum"][i];
if (recursiveCompare(data, enumVal)) {
return null;
}
}
return this.createError(ErrorCodes.ENUM_MISMATCH, {value: (typeof JSON !== 'undefined') ? JSON.stringify(data) : data}, '', '', null, data, schema);
};
ValidatorContext.prototype.validateNumeric = function validateNumeric(data, schema, dataPointerPath) {
return this.validateMultipleOf(data, schema, dataPointerPath)
|| this.validateMinMax(data, schema, dataPointerPath)
|| this.validateNaN(data, schema, dataPointerPath)
|| null;
};
var CLOSE_ENOUGH_LOW = Math.pow(2, -51);
var CLOSE_ENOUGH_HIGH = 1 - CLOSE_ENOUGH_LOW;
ValidatorContext.prototype.validateMultipleOf = function validateMultipleOf(data, schema) {
var multipleOf = schema.multipleOf || schema.divisibleBy;
if (multipleOf === undefined) {
return null;
}
if (typeof data === "number") {
var remainder = (data/multipleOf)%1;
if (remainder >= CLOSE_ENOUGH_LOW && remainder < CLOSE_ENOUGH_HIGH) {
return this.createError(ErrorCodes.NUMBER_MULTIPLE_OF, {value: data, multipleOf: multipleOf}, '', '', null, data, schema);
}
}
return null;
};
ValidatorContext.prototype.validateMinMax = function validateMinMax(data, schema) {
if (typeof data !== "number") {
return null;
}
if (schema.minimum !== undefined) {
if (data < schema.minimum) {
return this.createError(ErrorCodes.NUMBER_MINIMUM, {value: data, minimum: schema.minimum}, '', '/minimum', null, data, schema);
}
if (schema.exclusiveMinimum && data === schema.minimum) {
return this.createError(ErrorCodes.NUMBER_MINIMUM_EXCLUSIVE, {value: data, minimum: schema.minimum}, '', '/exclusiveMinimum', null, data, schema);
}
}
if (schema.maximum !== undefined) {
if (data > schema.maximum) {
return this.createError(ErrorCodes.NUMBER_MAXIMUM, {value: data, maximum: schema.maximum}, '', '/maximum', null, data, schema);
}
if (schema.exclusiveMaximum && data === schema.maximum) {
return this.createError(ErrorCodes.NUMBER_MAXIMUM_EXCLUSIVE, {value: data, maximum: schema.maximum}, '', '/exclusiveMaximum', null, data, schema);
}
}
return null;
};
ValidatorContext.prototype.validateNaN = function validateNaN(data, schema) {
if (typeof data !== "number") {
return null;
}
if (isNaN(data) === true || data === Infinity || data === -Infinity) {
return this.createError(ErrorCodes.NUMBER_NOT_A_NUMBER, {value: data}, '', '/type', null, data, schema);
}
return null;
};
ValidatorContext.prototype.validateString = function validateString(data, schema, dataPointerPath) {
return this.validateStringLength(data, schema, dataPointerPath)
|| this.validateStringPattern(data, schema, dataPointerPath)
|| null;
};
ValidatorContext.prototype.validateStringLength = function validateStringLength(data, schema) {
if (typeof data !== "string") {
return null;
}
if (schema.minLength !== undefined) {
if (data.length < schema.minLength) {
return this.createError(ErrorCodes.STRING_LENGTH_SHORT, {length: data.length, minimum: schema.minLength}, '', '/minLength', null, data, schema);
}
}
if (schema.maxLength !== undefined) {
if (data.length > schema.maxLength) {
return this.createError(ErrorCodes.STRING_LENGTH_LONG, {length: data.length, maximum: schema.maxLength}, '', '/maxLength', null, data, schema);
}
}
return null;
};
ValidatorContext.prototype.validateStringPattern = function validateStringPattern(data, schema) {
if (typeof data !== "string" || (typeof schema.pattern !== "string" && !(schema.pattern instanceof RegExp))) {
return null;
}
var regexp;
if (schema.pattern instanceof RegExp) {
regexp = schema.pattern;
}
else {
var body, flags = '';
// Check for regular expression literals
// @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5
var literal = schema.pattern.match(/^\/(.+)\/([img]*)$/);
if (literal) {
body = literal[1];
flags = literal[2];
}
else {
body = schema.pattern;
}
regexp = new RegExp(body, flags);
}
if (!regexp.test(data)) {
return this.createError(ErrorCodes.STRING_PATTERN, {pattern: schema.pattern}, '', '/pattern', null, data, schema);
}
return null;
};
ValidatorContext.prototype.validateArray = function validateArray(data, schema, dataPointerPath) {
if (!Array.isArray(data)) {
return null;
}
return this.validateArrayLength(data, schema, dataPointerPath)
|| this.validateArrayUniqueItems(data, schema, dataPointerPath)
|| this.validateArrayItems(data, schema, dataPointerPath)
|| null;
};
ValidatorContext.prototype.validateArrayLength = function validateArrayLength(data, schema) {
var error;
if (schema.minItems !== undefined) {
if (data.length < schema.minItems) {
error = this.createError(ErrorCodes.ARRAY_LENGTH_SHORT, {length: data.length, minimum: schema.minItems}, '', '/minItems', null, data, schema);
if (this.handleError(error)) {
return error;
}
}
}
if (schema.maxItems !== undefined) {
if (data.length > schema.maxItems) {
error = this.createError(ErrorCodes.ARRAY_LENGTH_LONG, {length: data.length, maximum: schema.maxItems}, '', '/maxItems', null, data, schema);
if (this.handleError(error)) {
return error;
}
}
}
return null;
};
ValidatorContext.prototype.validateArrayUniqueItems = function validateArrayUniqueItems(data, schema) {
if (schema.uniqueItems) {
for (var i = 0; i < data.length; i++) {
for (var j = i + 1; j < data.length; j++) {
if (recursiveCompare(data[i], data[j])) {
var error = this.createError(ErrorCodes.ARRAY_UNIQUE, {match1: i, match2: j}, '', '/uniqueItems', null, data, schema);
if (this.handleError(error)) {
return error;
}
}
}
}
}
return null;
};
ValidatorContext.prototype.validateArrayItems = function validateArrayItems(data, schema, dataPointerPath) {
if (schema.items === undefined) {
return null;
}
var error, i;
if (Array.isArray(schema.items)) {
for (i = 0; i < data.length; i++) {
if (i < schema.items.length) {
if (error = this.validateAll(data[i], schema.items[i], [i], ["items", i], dataPointerPath + "/" + i)) {
return error;
}
} else if (schema.additionalItems !== undefined) {
if (typeof schema.additionalItems === "boolean") {
if (!schema.additionalItems) {
error = (this.createError(ErrorCodes.ARRAY_ADDITIONAL_ITEMS, {}, '/' + i, '/additionalItems', null, data, schema));
if (this.handleError(error)) {
return error;
}
}
} else if (error = this.validateAll(data[i], schema.additionalItems, [i], ["additionalItems"], dataPointerPath + "/" + i)) {
return error;
}
}
}
} else {
for (i = 0; i < data.length; i++) {
if (error = this.validateAll(data[i], schema.items, [i], ["items"], dataPointerPath + "/" + i)) {
return error;
}
}
}
return null;
};
ValidatorContext.prototype.validateObject = function validateObject(data, schema, dataPointerPath) {
if (typeof data !== "object" || data === null || Array.isArray(data)) {
return null;
}
return this.validateObjectMinMaxProperties(data, schema, dataPointerPath)
|| this.validateObjectRequiredProperties(data, schema, dataPointerPath)
|| this.validateObjectProperties(data, schema, dataPointerPath)
|| this.validateObjectDependencies(data, schema, dataPointerPath)
|| null;
};
ValidatorContext.prototype.validateObjectMinMaxProperties = function validateObjectMinMaxProperties(data, schema) {
var keys = Object.keys(data);
var error;
if (schema.minProperties !== undefined) {
if (keys.length < schema.minProperties) {
error = this.createError(ErrorCodes.OBJECT_PROPERTIES_MINIMUM, {propertyCount: keys.length, minimum: schema.minProperties}, '', '/minProperties', null, data, schema);
if (this.handleError(error)) {
return error;
}
}
}
if (schema.maxProperties !== undefined) {
if (keys.length > schema.maxProperties) {
error = this.createError(ErrorCodes.OBJECT_PROPERTIES_MAXIMUM, {propertyCount: keys.length, maximum: schema.maxProperties}, '', '/maxProperties', null, data, schema);
if (this.handleError(error)) {
return error;
}
}
}
return null;
};
ValidatorContext.prototype.validateObjectRequiredProperties = function validateObjectRequiredProperties(data, schema) {
if (schema.required !== undefined) {
for (var i = 0; i < schema.required.length; i++) {
var key = schema.required[i];
if (data[key] === undefined) {
var error = this.createError(ErrorCodes.OBJECT_REQUIRED, {key: key}, '', '/required/' + i, null, data, schema);
if (this.handleError(error)) {
return error;
}
}
}
}
return null;
};
ValidatorContext.prototype.validateObjectProperties = function validateObjectProperties(data, schema, dataPointerPath) {
var error;
for (var key in data) {
var keyPointerPath = dataPointerPath + "/" + key.replace(/~/g, '~0').replace(/\//g, '~1');
var foundMatch = false;
if (schema.properties !== undefined && schema.properties[key] !== undefined) {
foundMatch = true;
if (error = this.validateAll(data[key], schema.properties[key], [key], ["properties", key], keyPointerPath)) {
return error;
}
}
if (schema.patternProperties !== undefined) {
for (var patternKey in schema.patternProperties) {
var regexp = new RegExp(patternKey);
if (regexp.test(key)) {
foundMatch = true;
if (error = this.validateAll(data[key], schema.patternProperties[patternKey], [key], ["patternProperties", patternKey], keyPointerPath)) {
return error;
}
}
}
}
if (!foundMatch) {
if (schema.additionalProperties !== undefined) {
if (this.trackUnknownProperties) {
this.knownPropertyPaths[keyPointerPath] = true;
delete this.unknownPropertyPaths[keyPointerPath];
}
if (typeof schema.additionalProperties === "boolean") {
if (!schema.additionalProperties) {
error = this.createError(ErrorCodes.OBJECT_ADDITIONAL_PROPERTIES, {key: key}, '', '/additionalProperties', null, data, schema).prefixWith(key, null);
if (this.handleError(error)) {
return error;
}
}
} else {
if (error = this.validateAll(data[key], schema.additionalProperties, [key], ["additionalProperties"], keyPointerPath)) {
return error;
}
}
} else if (this.trackUnknownProperties && !this.knownPropertyPaths[keyPointerPath]) {
this.unknownPropertyPaths[keyPointerPath] = true;
}
} else if (this.trackUnknownProperties) {
this.knownPropertyPaths[keyPointerPath] = true;
delete this.unknownPropertyPaths[keyPointerPath];
}
}
return null;
};
ValidatorContext.prototype.validateObjectDependencies = function validateObjectDependencies(data, schema, dataPointerPath) {
var error;
if (schema.dependencies !== undefined) {
for (var depKey in schema.dependencies) {
if (data[depKey] !== undefined) {
var dep = schema.dependencies[depKey];
if (typeof dep === "string") {
if (data[dep] === undefined) {
error = this.createError(ErrorCodes.OBJECT_DEPENDENCY_KEY, {key: depKey, missing: dep}, '', '', null, data, schema).prefixWith(null, depKey).prefixWith(null, "dependencies");
if (this.handleError(error)) {
return error;
}
}
} else if (Array.isArray(dep)) {
for (var i = 0; i < dep.length; i++) {
var requiredKey = dep[i];
if (data[requiredKey] === undefined) {
error = this.createError(ErrorCodes.OBJECT_DEPENDENCY_KEY, {key: depKey, missing: requiredKey}, '', '/' + i, null, data, schema).prefixWith(null, depKey).prefixWith(null, "dependencies");
if (this.handleError(error)) {
return error;
}
}
}
} else {
if (error = this.validateAll(data, dep, [], ["dependencies", depKey], dataPointerPath)) {
return error;
}
}
}
}
}
return null;
};
ValidatorContext.prototype.validateCombinations = function validateCombinations(data, schema, dataPointerPath) {
return this.validateAllOf(data, schema, dataPointerPath)
|| this.validateAnyOf(data, schema, dataPointerPath)
|| this.validateOneOf(data, schema, dataPointerPath)
|| this.validateNot(data, schema, dataPointerPath)
|| null;
};
ValidatorContext.prototype.validateAllOf = function validateAllOf(data, schema, dataPointerPath) {
if (schema.allOf === undefined) {
return null;
}
var error;
for (var i = 0; i < schema.allOf.length; i++) {
var subSchema = schema.allOf[i];
if (error = this.validateAll(data, subSchema, [], ["allOf", i], dataPointerPath)) {
return error;
}
}
return null;
};
ValidatorContext.prototype.validateAnyOf = function validateAnyOf(data, schema, dataPointerPath) {
if (schema.anyOf === undefined) {
return null;
}
var errors = [];
var startErrorCount = this.errors.length;
var oldUnknownPropertyPaths, oldKnownPropertyPaths;
if (this.trackUnknownProperties) {
oldUnknownPropertyPaths = this.unknownPropertyPaths;
oldKnownPropertyPaths = this.knownPropertyPaths;
}
var errorAtEnd = true;
for (var i = 0; i < schema.anyOf.length; i++) {
if (this.trackUnknownProperties) {
this.unknownPropertyPaths = {};
this.knownPropertyPaths = {};
}
var subSchema = schema.anyOf[i];
var errorCount = this.errors.length;
var error = this.validateAll(data, subSchema, [], ["anyOf", i], dataPointerPath);
if (error === null && errorCount === this.errors.length) {
this.errors = this.errors.slice(0, startErrorCount);
if (this.trackUnknownProperties) {
for (var knownKey in this.knownPropertyPaths) {
oldKnownPropertyPaths[knownKey] = true;
delete oldUnknownPropertyPaths[knownKey];
}
for (var unknownKey in this.unknownPropertyPaths) {
if (!oldKnownPropertyPaths[unknownKey]) {
oldUnknownPropertyPaths[unknownKey] = true;
}
}
// We need to continue looping so we catch all the property definitions, but we don't want to return an error
errorAtEnd = false;
continue;
}
return null;
}
if (error) {
errors.push(error.prefixWith(null, "" + i).prefixWith(null, "anyOf"));
}
}
if (this.trackUnknownProperties) {
this.unknownPropertyPaths = oldUnknownPropertyPaths;
this.knownPropertyPaths = oldKnownPropertyPaths;
}
if (errorAtEnd) {
errors = errors.concat(this.errors.slice(startErrorCount));
this.errors = this.errors.slice(0, startErrorCount);
return this.createError(ErrorCodes.ANY_OF_MISSING, {}, "", "/anyOf", errors, data, schema);
}
};
ValidatorContext.prototype.validateOneOf = function validateOneOf(data, schema, dataPointerPath) {
if (schema.oneOf === undefined) {
return null;
}
var validIndex = null;
var errors = [];
var startErrorCount = this.errors.length;
var oldUnknownPropertyPaths, oldKnownPropertyPaths;
if (this.trackUnknownProperties) {
oldUnknownPropertyPaths = this.unknownPropertyPaths;
oldKnownPropertyPaths = this.knownPropertyPaths;
}
for (var i = 0; i < schema.oneOf.length; i++) {
if (this.trackUnknownProperties) {
this.unknownPropertyPaths = {};
this.knownPropertyPaths = {};
}
var subSchema = schema.oneOf[i];
var errorCount = this.errors.length;
var error = this.validateAll(data, subSchema, [], ["oneOf", i], dataPointerPath);
if (error === null && errorCount === this.errors.length) {
if (validIndex === null) {
validIndex = i;
} else {
this.errors = this.errors.slice(0, startErrorCount);
return this.createError(ErrorCodes.ONE_OF_MULTIPLE, {index1: validIndex, index2: i}, "", "/oneOf", null, data, schema);
}
if (this.trackUnknownProperties) {
for (var knownKey in this.knownPropertyPaths) {
oldKnownPropertyPaths[knownKey] = true;
delete oldUnknownPropertyPaths[knownKey];
}
for (var unknownKey in this.unknownPropertyPaths) {
if (!oldKnownPropertyPaths[unknownKey]) {
oldUnknownPropertyPaths[unknownKey] = true;
}
}
}
} else if (error) {
errors.push(error);
}
}
if (this.trackUnknownProperties) {
this.unknownPropertyPaths = oldUnknownPropertyPaths;
this.knownPropertyPaths = oldKnownPropertyPaths;
}
if (validIndex === null) {
errors = errors.concat(this.errors.slice(startErrorCount));
this.errors = this.errors.slice(0, startErrorCount);
return this.createError(ErrorCodes.ONE_OF_MISSING, {}, "", "/oneOf", errors, data, schema);
} else {
this.errors = this.errors.slice(0, startErrorCount);
}
return null;
};
ValidatorContext.prototype.validateNot = function validateNot(data, schema, dataPointerPath) {
if (schema.not === undefined) {
return null;
}
var oldErrorCount = this.errors.length;
var oldUnknownPropertyPaths, oldKnownPropertyPaths;
if (this.trackUnknownProperties) {
oldUnknownPropertyPaths = this.unknownPropertyPaths;
oldKnownPropertyPaths = this.knownPropertyPaths;
this.unknownPropertyPaths = {};
this.knownPropertyPaths = {};
}
var error = this.validateAll(data, schema.not, null, null, dataPointerPath);
var notErrors = this.errors.slice(oldErrorCount);
this.errors = this.errors.slice(0, oldErrorCount);
if (this.trackUnknownProperties) {
this.unknownPropertyPaths = oldUnknownPropertyPaths;
this.knownPropertyPaths = oldKnownPropertyPaths;
}
if (error === null && notErrors.length === 0) {
return this.createError(ErrorCodes.NOT_PASSED, {}, "", "/not", null, data, schema);
}
return null;
};
ValidatorContext.prototype.validateHypermedia = function validateCombinations(data, schema, dataPointerPath) {
if (!schema.links) {
return null;
}
var error;
for (var i = 0; i < schema.links.length; i++) {
var ldo = schema.links[i];
if (ldo.rel === "describedby") {
var template = new UriTemplate(ldo.href);
var allPresent = true;
for (var j = 0; j < template.varNames.length; j++) {
if (!(template.varNames[j] in data)) {
allPresent = false;
break;
}
}
if (allPresent) {
var schemaUrl = template.fillFromObject(data);
var subSchema = {"$ref": schemaUrl};
if (error = this.validateAll(data, subSchema, [], ["links", i], dataPointerPath)) {
return error;
}
}
}
}
};
// parseURI() and resolveUrl() are from https://gist.github.com/1088850
// - released as public domain by author ("Yaffle") - see comments on gist
function parseURI(url) {
var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
// authority = '//' + user + ':' + pass '@' + hostname + ':' port
return (m ? {
href : m[0] || '',
protocol : m[1] || '',
authority: m[2] || '',
host : m[3] || '',
hostname : m[4] || '',
port : m[5] || '',
pathname : m[6] || '',
search : m[7] || '',
hash : m[8] || ''
} : null);
}
function resolveUrl(base, href) {// RFC 3986
function removeDotSegments(input) {
var output = [];
input.replace(/^(\.\.?(\/|$))+/, '')
.replace(/\/(\.(\/|$))+/g, '/')
.replace(/\/\.\.$/, '/../')
.replace(/\/?[^\/]*/g, function (p) {
if (p === '/..') {
output.pop();
} else {
output.push(p);
}
});
return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : '');
}
href = parseURI(href || '');
base = parseURI(base || '');
return !href || !base ? null : (href.protocol || base.protocol) +
(href.protocol || href.authority ? href.authority : base.authority) +
removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) +
(href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
href.hash;
}
function getDocumentUri(uri) {
return uri.split('#')[0];
}
function normSchema(schema, baseUri) {
if (schema && typeof schema === "object") {
if (baseUri === undefined) {
baseUri = schema.id;
} else if (typeof schema.id === "string") {
baseUri = resolveUrl(baseUri, schema.id);
schema.id = baseUri;
}
if (Array.isArray(schema)) {
for (var i = 0; i < schema.length; i++) {
normSchema(schema[i], baseUri);
}
} else {
if (typeof schema['$ref'] === "string") {
schema['$ref'] = resolveUrl(baseUri, schema['$ref']);
}
for (var key in schema) {
if (key !== "enum") {
normSchema(schema[key], baseUri);
}
}
}
}
}
function defaultErrorReporter(language) {
language = language || 'en';
var errorMessages = languages[language];
return function (error) {
var messageTemplate = errorMessages[error.code] || ErrorMessagesDefault[error.code];
if (typeof messageTemplate !== 'string') {
return "Unknown error code " + error.code + ": " + JSON.stringify(error.messageParams);
}
var messageParams = error.params;
// Adapted from Crockford's supplant()
return messageTemplate.replace(/\{([^{}]*)\}/g, function (whole, varName) {
var subValue = messageParams[varName];
return typeof subValue === 'string' || typeof subValue === 'number' ? subValue : whole;
});
};
}
var ErrorCodes = {
INVALID_TYPE: 0,
ENUM_MISMATCH: 1,
ANY_OF_MISSING: 10,
ONE_OF_MISSING: 11,
ONE_OF_MULTIPLE: 12,
NOT_PASSED: 13,
// Numeric errors
NUMBER_MULTIPLE_OF: 100,
NUMBER_MINIMUM: 101,
NUMBER_MINIMUM_EXCLUSIVE: 102,
NUMBER_MAXIMUM: 103,
NUMBER_MAXIMUM_EXCLUSIVE: 104,
NUMBER_NOT_A_NUMBER: 105,
// String errors
STRING_LENGTH_SHORT: 200,
STRING_LENGTH_LONG: 201,
STRING_PATTERN: 202,
// Object errors
OBJECT_PROPERTIES_MINIMUM: 300,
OBJECT_PROPERTIES_MAXIMUM: 301,
OBJECT_REQUIRED: 302,
OBJECT_ADDITIONAL_PROPERTIES: 303,
OBJECT_DEPENDENCY_KEY: 304,
// Array errors
ARRAY_LENGTH_SHORT: 400,
ARRAY_LENGTH_LONG: 401,
ARRAY_UNIQUE: 402,
ARRAY_ADDITIONAL_ITEMS: 403,
// Custom/user-defined errors
FORMAT_CUSTOM: 500,
KEYWORD_CUSTOM: 501,
// Schema structure
CIRCULAR_REFERENCE: 600,
// Non-standard validation options
UNKNOWN_PROPERTY: 1000
};
var ErrorCodeLookup = {};
for (var key in ErrorCodes) {
ErrorCodeLookup[ErrorCodes[key]] = key;
}
var ErrorMessagesDefault = {
INVALID_TYPE: "Invalid type: {type} (expected {expected})",
ENUM_MISMATCH: "No enum match for: {value}",
ANY_OF_MISSING: "Data does not match any schemas from \"anyOf\"",
ONE_OF_MISSING: "Data does not match any schemas from \"oneOf\"",
ONE_OF_MULTIPLE: "Data is valid against more than one schema from \"oneOf\": indices {index1} and {index2}",
NOT_PASSED: "Data matches schema from \"not\"",
// Numeric errors
NUMBER_MULTIPLE_OF: "Value {value} is not a multiple of {multipleOf}",
NUMBER_MINIMUM: "Value {value} is less than minimum {minimum}",
NUMBER_MINIMUM_EXCLUSIVE: "Value {value} is equal to exclusive minimum {minimum}",
NUMBER_MAXIMUM: "Value {value} is greater than maximum {maximum}",
NUMBER_MAXIMUM_EXCLUSIVE: "Value {value} is equal to exclusive maximum {maximum}",
NUMBER_NOT_A_NUMBER: "Value {value} is not a valid number",
// String errors
STRING_LENGTH_SHORT: "String is too short ({length} chars), minimum {minimum}",
STRING_LENGTH_LONG: "String is too long ({length} chars), maximum {maximum}",
STRING_PATTERN: "String does not match pattern: {pattern}",
// Object errors
OBJECT_PROPERTIES_MINIMUM: "Too few properties defined ({propertyCount}), minimum {minimum}",
OBJECT_PROPERTIES_MAXIMUM: "Too many properties defined ({propertyCount}), maximum {maximum}",
OBJECT_REQUIRED: "Missing required property: {key}",
OBJECT_ADDITIONAL_PROPERTIES: "Additional properties not allowed",
OBJECT_DEPENDENCY_KEY: "Dependency failed - key must exist: {missing} (due to key: {key})",
// Array errors
ARRAY_LENGTH_SHORT: "Array is too short ({length}), minimum {minimum}",
ARRAY_LENGTH_LONG: "Array is too long ({length}), maximum {maximum}",
ARRAY_UNIQUE: "Array items are not unique (indices {match1} and {match2})",
ARRAY_ADDITIONAL_ITEMS: "Additional items not allowed",
// Format errors
FORMAT_CUSTOM: "Format validation failed ({message})",
KEYWORD_CUSTOM: "Keyword failed: {key} ({message})",
// Schema structure
CIRCULAR_REFERENCE: "Circular $refs: {urls}",
// Non-standard validation options
UNKNOWN_PROPERTY: "Unknown property (not in schema)"
};
function ValidationError(code, params, dataPath, schemaPath, subErrors) {
Error.call(this);
if (code === undefined) {
throw new Error ("No error code supplied: " + schemaPath);
}
this.message = '';
this.params = params;
this.code = code;
this.dataPath = dataPath || "";
this.schemaPath = schemaPath || "";
this.subErrors = subErrors || null;
var err = new Error(this.message);
this.stack = err.stack || err.stacktrace;
if (!this.stack) {
try {
throw err;
}
catch(err) {
this.stack = err.stack || err.stacktrace;
}
}
}
ValidationError.prototype = Object.create(Error.prototype);
ValidationError.prototype.constructor = ValidationError;
ValidationError.prototype.name = 'ValidationError';
ValidationError.prototype.prefixWith = function (dataPrefix, schemaPrefix) {
if (dataPrefix !== null) {
dataPrefix = dataPrefix.replace(/~/g, "~0").replace(/\//g, "~1");
this.dataPath = "/" + dataPrefix + this.dataPath;
}
if (schemaPrefix !== null) {
schemaPrefix = schemaPrefix.replace(/~/g, "~0").replace(/\//g, "~1");
this.schemaPath = "/" + schemaPrefix + this.schemaPath;
}
if (this.subErrors !== null) {
for (var i = 0; i < this.subErrors.length; i++) {
this.subErrors[i].prefixWith(dataPrefix, schemaPrefix);
}
}
return this;
};
function isTrustedUrl(baseUrl, testUrl) {
if(testUrl.substring(0, baseUrl.length) === baseUrl){
var remainder = testUrl.substring(baseUrl.length);
if ((testUrl.length > 0 && testUrl.charAt(baseUrl.length - 1) === "/")
|| remainder.charAt(0) === "#"
|| remainder.charAt(0) === "?") {
return true;
}
}
return false;
}
var languages = {};
function createApi(language) {
var globalContext = new ValidatorContext();
var currentLanguage;
var customErrorReporter;
var api = {
setErrorReporter: function (reporter) {
if (typeof reporter === 'string') {
return this.language(reporter);
}
customErrorReporter = reporter;
return true;
},
addFormat: function () {
globalContext.addFormat.apply(globalContext, arguments);
},
language: function (code) {
if (!code) {
return currentLanguage;
}
if (!languages[code]) {
code = code.split('-')[0]; // fall back to base language
}
if (languages[code]) {
currentLanguage = code;
return code; // so you can tell if fall-back has happened
}
return false;
},
addLanguage: function (code, messageMap) {
var key;
for (key in ErrorCodes) {
if (messageMap[key] && !messageMap[ErrorCodes[key]]) {
messageMap[ErrorCodes[key]] = messageMap[key];
}
}
var rootCode = code.split('-')[0];
if (!languages[rootCode]) { // use for base language if not yet defined
languages[code] = messageMap;
languages[rootCode] = messageMap;
} else {
languages[code] = Object.create(languages[rootCode]);
for (key in messageMap) {
if (typeof languages[rootCode][key] === 'undefined') {
languages[rootCode][key] = messageMap[key];
}
languages[code][key] = messageMap[key];
}
}
return this;
},
freshApi: function (language) {
var result = createApi();
if (language) {
result.language(language);
}
return result;
},
validate: function (data, schema, checkRecursive, banUnknownProperties) {
var def = defaultErrorReporter(currentLanguage);
var errorReporter = customErrorReporter ? function (error, data, schema) {
return customErrorReporter(error, data, schema) || def(error, data, schema);
} : def;
var context = new ValidatorContext(globalContext, false, errorReporter, checkRecursive, banUnknownProperties);
if (typeof schema === "string") {
schema = {"$ref": schema};
}
context.addSchema("", schema);
var error = context.validateAll(data, schema, null, null, "");
if (!error && banUnknownProperties) {
error = context.banUnknownProperties(data, schema);
}
this.error = error;
this.missing = context.missing;
this.valid = (error === null);
return this.valid;
},
validateResult: function () {
var result = {};
this.validate.apply(result, arguments);
return result;
},
validateMultiple: function (data, schema, checkRecursive, banUnknownProperties) {
var def = defaultErrorReporter(currentLanguage);
var errorReporter = customErrorReporter ? function (error, data, schema) {
return customErrorReporter(error, data, schema) || def(error, data, schema);
} : def;
var context = new ValidatorContext(globalContext, true, errorReporter, checkRecursive, banUnknownProperties);
if (typeof schema === "string") {
schema = {"$ref": schema};
}
context.addSchema("", schema);
context.validateAll(data, schema, null, null, "");
if (banUnknownProperties) {
context.banUnknownProperties(data, schema);
}
var result = {};
result.errors = context.errors;
result.missing = context.missing;
result.valid = (result.errors.length === 0);
return result;
},
addSchema: function () {
return globalContext.addSchema.apply(globalContext, arguments);
},
getSchema: function () {
return globalContext.getSchema.apply(globalContext, arguments);
},
getSchemaMap: function () {
return globalContext.getSchemaMap.apply(globalContext, arguments);
},
getSchemaUris: function () {
return globalContext.getSchemaUris.apply(globalContext, arguments);
},
getMissingUris: function () {
return globalContext.getMissingUris.apply(globalContext, arguments);
},
dropSchemas: function () {
globalContext.dropSchemas.apply(globalContext, arguments);
},
defineKeyword: function () {
globalContext.defineKeyword.apply(globalContext, arguments);
},
defineError: function (codeName, codeNumber, defaultMessage) {
if (typeof codeName !== 'string' || !/^[A-Z]+(_[A-Z]+)*$/.test(codeName)) {
throw new Error('Code name must be a string in UPPER_CASE_WITH_UNDERSCORES');
}
if (typeof codeNumber !== 'number' || codeNumber%1 !== 0 || codeNumber < 10000) {
throw new Error('Code number must be an integer > 10000');
}
if (typeof ErrorCodes[codeName] !== 'undefined') {
throw new Error('Error already defined: ' + codeName + ' as ' + ErrorCodes[codeName]);
}
if (typeof ErrorCodeLookup[codeNumber] !== 'undefined') {
throw new Error('Error code already used: ' + ErrorCodeLookup[codeNumber] + ' as ' + codeNumber);
}
ErrorCodes[codeName] = codeNumber;
ErrorCodeLookup[codeNumber] = codeName;
ErrorMessagesDefault[codeName] = ErrorMessagesDefault[codeNumber] = defaultMessage;
for (var langCode in languages) {
var language = languages[langCode];
if (language[codeName]) {
language[codeNumber] = language[codeNumber] || language[codeName];
}
}
},
reset: function () {
globalContext.reset();
this.error = null;
this.missing = [];
this.valid = true;
},
missing: [],
error: null,
valid: true,
normSchema: normSchema,
resolveUrl: resolveUrl,
getDocumentUri: getDocumentUri,
errorCodes: ErrorCodes
};
api.language(language || 'en');
return api;
}
var tv4 = createApi();
tv4.addLanguage('en-gb', ErrorMessagesDefault);
//legacy property
tv4.tv4 = tv4;
return tv4; // used by _header.js to globalise.
}));
/** FILE: lib/Math.uuid.js **/
/*!
Math.uuid.js (v1.4)
http://www.broofa.com
mailto:[email protected]
Copyright (c) 2010 Robert Kieffer
Dual licensed under the MIT and GPL licenses.
********
Changes within remoteStorage.js:
2012-10-31:
- added AMD wrapper <[email protected]>
- moved extensions for Math object into exported object.
*/
/*
* Generate a random uuid.
*
* USAGE: Math.uuid(length, radix)
* length - the desired number of characters
* radix - the number of allowable values for each character.
*
* EXAMPLES:
* // No arguments - returns RFC4122, version 4 ID
* >>> Math.uuid()
* "92329D39-6F5C-4520-ABFC-AAB64544E172"
*
* // One argument - returns ID of the specified length
* >>> Math.uuid(15) // 15 character ID (default base=62)
* "VcydxgltxrVZSTV"
*
* // Two arguments - returns ID of the specified length, and radix. (Radix must be <= 62)
* >>> Math.uuid(8, 2) // 8 character ID (base=2)
* "01001010"
* >>> Math.uuid(8, 10) // 8 character ID (base=10)
* "47473046"
* >>> Math.uuid(8, 16) // 8 character ID (base=16)
* "098F4D35"
*/
// Private array of chars to use
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
Math.uuid = function (len, radix) {
var chars = CHARS, uuid = [], i;
radix = radix || chars.length;
if (len) {
// Compact form
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
} else {
// rfc4122, version 4 form
var r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random()*16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
};
/** FILE: src/baseclient.js **/
(function (global) {
function deprecate(thing, replacement) {
console.log('WARNING: ' + thing + ' is deprecated. Use ' +
replacement + ' instead.');
}
var RS = RemoteStorage;
/**
* Class: RemoteStorage.BaseClient
*
* Provides a high-level interface to access data below a given root path.
*
* A BaseClient deals with three types of data: folders, objects and files.
*
* <getListing> returns a mapping of all items within a folder. Items that
* end with a forward slash ("/") are child folders. For instance:
* {
* 'folder/': true,
* 'document.txt': true
* }
*
* <getObject> / <storeObject> operate on JSON objects. Each object has a type.
*
* <getFile> / <storeFile> operates on files. Each file has a MIME type.
*
* <remove> operates on either objects or files (but not folders, folders are
* created and removed implictly).
*/
RS.BaseClient = function (storage, base) {
if (base[base.length - 1] !== '/') {
throw "Not a folder: " + base;
}
if (base === '/') {
// allow absolute and relative paths for the root scope.
this.makePath = function (path) {
return (path[0] === '/' ? '' : '/') + path;
};
}
/**
* Property: storage
*
* The <RemoteStorage> instance this <BaseClient> operates on.
*/
this.storage = storage;
/**
* Property: base
*
* Base path this <BaseClient> operates on.
*
* For the module's privateClient this would be /<moduleName>/, for the
* corresponding publicClient /public/<moduleName>/.
*/
this.base = base;
var parts = this.base.split('/');
if (parts.length > 2) {
this.moduleName = parts[1];
} else {
this.moduleName = 'root';
}
// Defined in baseclient/types.js
/**
* Property: schemas
*
* Contains schema objects of all types known to the BaseClient instance
**/
/**
* Event: change
*
* Emitted when a node changes
*
* Arguments:
* event - Event object containing information about the changed node
*
* (start code)
* {
* path: path, // Absolute path of the changed node, from the storage root
* relativePath: relativePath, // Path of the changed node, relative to this baseclient's scope root
* origin: 'window', 'local', 'remote', or 'conflict' // emitted by user action within the app, local data store, remote sync, or versioning conflicts
* oldValue: oldBody, // Old body of the changed node (local version in conflicts; undefined if creation)
* newValue: newBody, // New body of the changed node (remote version in conflicts; undefined if deletion)
* lastCommonValue: lastCommonValue, //most recent known common ancestor body of 'yours' and 'theirs' in case of conflict
* oldContentType: oldContentType, // Old contentType of the changed node ('yours' for conflicts; undefined if creation)
* newContentType: newContentType, // New contentType of the changed node ('theirs' for conflicts; undefined if deletion)
* lastCommonContentType: lastCommonContentType // Most recent known common ancestor contentType of 'yours' and 'theirs' in case of conflict
* }
* (end code)
*
* Example of an event with origin 'local' (fired on page load):
*
* (start code)
* {
* path: '/public/design/color.txt',
* relativePath: 'color.txt',
* origin: 'local',
* oldValue: undefined,
* newValue: 'white',
* oldContentType: undefined,
* newContentType: 'text/plain'
* }
* (end code)
*
* Example of a conflict:
* Say you changed 'color.txt' from 'white' to 'blue'; if you have set `RemoteStorage.config.changeEvents.window` to `true`,
* then you will receive:
*
* (start code)
* {
* path: '/public/design/color.txt',
* relativePath: 'color.txt',
* origin: 'window',
* oldValue: 'white',
* newValue: 'blue',
* oldContentType: 'text/plain',
* newContentType: 'text/plain'
* }
* (end code)
*
* But when this change is pushed out by asynchronous synchronization, this change may rejected by the
* server, if the remote version has in the meantime changed from 'white' to for instance 'red'; this will then lead to a change
* event with origin 'conflict' (usually a few seconds after the event with origin 'window', if you had that activated). Note
* that since you already changed it from 'white' to 'blue' in the local version a few seconds ago, `oldValue` is now your local
* value of 'blue':
*
* (start code)
* {
* path: '/public/design/color.txt',
* relativePath: 'color.txt',
* origin: 'conflict',
* oldValue: 'blue',
* newValue: 'red',
* lastCommonValue: 'white',
* oldContentType: 'text/plain,
* newContentType: 'text/plain'
* lastCommonContentType: 'text/plain'
* }
* (end code)
*
* In practice, you should always redraw your views to display the content of the `newValue` field when a change event is received,
* regardless of its origin. Events with origin 'local' are fired conveniently during the page load, so that you can fill your views
* when the page loads. Events with origin 'window' are fired whenever you change a value by calling a method on the baseClient;
* these are disabled by default. Events with origin 'remote' are fired when remote changes are discovered during sync (only for caching
* startegies 'SEEN' and 'ALL'). Events with origin 'conflict' are fired when a conflict occurs while pushing out your local changes to
* the remote store in asynchronous synchronization (see example above).
**/
RS.eventHandling(this, 'change');
this.on = this.on.bind(this);
storage.onChange(this.base, this._fireChange.bind(this));
};
RS.BaseClient.prototype = {
extend: function (object) {
for (var key in object) {
this[key] = object[key];
}
return this;
},
/**
* Method: scope
*
* Returns a new <BaseClient> operating on a subpath of the current <base> path.
*/
scope: function (path) {
return new RS.BaseClient(this.storage, this.makePath(path));
},
// folder operations
/**
* Method: getListing
*
* Get a list of child nodes below a given path.
*
* The callback semantics of getListing are identical to those of getObject.
*
* Parameters:
* path - The path to query. It MUST end with a forward slash.
* maxAge - Either false or the maximum age of cached listing in
* milliseconds. Defaults to false in anonymous mode and to
* 2*syncInterval in connected mode.
*
* Returns:
*
* A promise for an object, representing child nodes. If the maxAge
* requirement cannot be met because of network problems, this promise
* will be rejected. If the maxAge requirement is set to false or the
* library is in offline state, the promise will always be fulfilled with
* data from the local store.
*
* Keys ending in a forward slash represent *folder nodes*, while all
* other keys represent *data nodes*.
*
* For spec versions <= 01, the data node information will contain only
* the item's ETag. For later spec versions, it will also contain the
* content type and -length of the item.
*
* Example:
* (start code)
* client.getListing('', false).then(function (listing) {
* // listing is for instance:
* // {
* // 'folder/': true,
* // 'document.txt': true
* // }
* });
* (end code)
*/
getListing: function (path, maxAge) {
if (typeof(path) !== 'string') {
path = '';
} else if (path.length > 0 && path[path.length - 1] !== '/') {
return Promise.reject("Not a folder: " + path);
}
return this.storage.get(this.makePath(path), maxAge).then(
function (r) {
return (r.statusCode === 404) ? {} : r.body;
}
);
},
/**
* Method: getAll
*
* Get all objects directly below a given path.
*
* Parameters:
* path - Path to the folder.
* maxAge - Either false or the maximum age of cached objects in
* milliseconds. Defaults to false in anonymous mode and to
* 2*syncInterval in connected mode.
*
* Returns:
* A promise for an object in the form { path : object, ... }. If the
* maxAge requirement cannot be met because of network problems, this
* promise will be rejected. If the maxAge requirement is set to false,
* the promise will always be fulfilled with data from the local store.
*
* For items that are not JSON-stringified objects (e.g. stored using
* `storeFile` instead of `storeObject`), the object's value is filled in
* with `true`.
*
* Example:
* (start code)
* client.getAll('', false).then(function (objects) {
* for (var key in objects) {
* console.log('- ' + key + ': ', objects[key]);
* }
* });
* (end code)
*/
getAll: function (path, maxAge) {
if (typeof(path) !== 'string') {
path = '';
} else if (path.length > 0 && path[path.length - 1] !== '/') {
return Promise.reject("Not a folder: " + path);
}
return this.storage.get(this.makePath(path), maxAge).then(function (r) {
if (r.statusCode === 404) { return {}; }
if (typeof(r.body) === 'object') {
var keys = Object.keys(r.body);
if (keys.length === 0) {
// treat this like 404. it probably means a folder listing that
// has changes that haven't been pushed out yet.
return {};
}
var calls = keys.map(function (key) {
return this.storage.get(this.makePath(path + key), maxAge)
.then(function (o) {
if (typeof(o.body) === 'string') {
try {
o.body = JSON.parse(o.body);
} catch (e) {
}
}
if (typeof(o.body) === 'object') {
r.body[key] = o.body;
}
});
}.bind(this));
return Promise.all(calls).then(function () {
return r.body;
});
}
}.bind(this));
},
// file operations
/**
* Method: getFile
*
* Get the file at the given path. A file is raw data, as opposed to
* a JSON object (use <getObject> for that).
*
* Except for the return value structure, getFile works exactly like
* getObject.
*
* Parameters:
* path - See getObject.
* maxAge - Either false or the maximum age of cached file in
* milliseconds. Defaults to false in anonymous mode and to
* 2*syncInterval in connected mode.
*
* Returns:
* A promise for an object:
*
* mimeType - String representing the MIME Type of the document.
* data - Raw data of the document (either a string or an ArrayBuffer)
*
* If the maxAge requirement cannot be met because of network problems, this
* promise will be rejected. If the maxAge requirement is set to false, the
* promise will always be fulfilled with data from the local store.
*
* Example:
* (start code)
* // Display an image:
* client.getFile('path/to/some/image', false).then(function (file) {
* var blob = new Blob([file.data], { type: file.mimeType });
* var targetElement = document.findElementById('my-image-element');
* targetElement.src = window.URL.createObjectURL(blob);
* });
* (end code)
*/
getFile: function (path, maxAge) {
if (typeof(path) !== 'string') {
return Promise.reject('Argument \'path\' of baseClient.getFile must be a string');
}
return this.storage.get(this.makePath(path), maxAge).then(function (r) {
return {
data: r.body,
contentType: r.contentType,
revision: r.revision // (this is new)
};
});
},
/**
* Method: storeFile
*
* Store raw data at a given path.
*
* Parameters:
* mimeType - MIME media type of the data being stored
* path - path relative to the module root. MAY NOT end in a forward slash.
* data - string, ArrayBuffer or ArrayBufferView of raw data to store
*
* The given mimeType will later be returned, when retrieving the data
* using <getFile>.
*
* Example (UTF-8 data):
* (start code)
* client.storeFile('text/html', 'index.html', '<h1>Hello World!</h1>');
* (end code)
*
* Example (Binary data):
* (start code)
* // MARKUP:
* <input type="file" id="file-input">
* // CODE:
* var input = document.getElementById('file-input');
* var file = input.files[0];
* var fileReader = new FileReader();
*
* fileReader.onload = function () {
* client.storeFile(file.type, file.name, fileReader.result);
* };
*
* fileReader.readAsArrayBuffer(file);
* (end code)
*
*/
storeFile: function (mimeType, path, body) {
if (typeof(mimeType) !== 'string') {
return Promise.reject('Argument \'mimeType\' of baseClient.storeFile must be a string');
}
if (typeof(path) !== 'string') {
return Promise.reject('Argument \'path\' of baseClient.storeFile must be a string');
}
if (typeof(body) !== 'string' && typeof(body) !== 'object') {
return Promise.reject('Argument \'body\' of baseClient.storeFile must be a string, ArrayBuffer, or ArrayBufferView');
}
if (!this.storage.access.checkPathPermission(this.makePath(path), 'rw')) {
console.warn('WARNING: Editing a document to which only read access (\'r\') was claimed');
}
return this.storage.put(this.makePath(path), body, mimeType).then(function (r) {
if (r.statusCode === 200 || r.statusCode === 201) {
return r.revision;
} else {
return Promise.reject("Request (PUT " + this.makePath(path) + ") failed with status: " + r.statusCode);
}
}.bind(this));
},
// object operations
/**
* Method: getObject
*
* Get a JSON object from given path.
*
* Parameters:
* path - Relative path from the module root (without leading slash).
* maxAge - Either false or the maximum age of cached object in
* milliseconds. Defaults to false in anonymous mode and to
* 2*syncInterval in connected mode.
*
* Returns:
* A promise for the object. If the maxAge requirement cannot be met
* because of network problems, this promise will be rejected. If the
* maxAge requirement is set to false, the promise will always be
* fulfilled with data from the local store.
*
* Example:
* (start code)
* client.getObject('/path/to/object', false).
* then(function (object) {
* // object is either an object or null
* });
* (end code)
*/
getObject: function (path, maxAge) {
if (typeof(path) !== 'string') {
return Promise.reject('Argument \'path\' of baseClient.getObject must be a string');
}
return this.storage.get(this.makePath(path), maxAge).then(function (r) {
if (typeof(r.body) === 'object') { // will be the case for documents stored with rs.js <= 0.10.0-beta2
return r.body;
} else if (typeof(r.body) === 'string') {
try {
return JSON.parse(r.body);
} catch (e) {
throw "Not valid JSON: " + this.makePath(path);
}
} else if (typeof(r.body) !== 'undefined' && r.statusCode === 200) {
return Promise.reject("Not an object: " + this.makePath(path));
}
}.bind(this));
},
/**
* Method: storeObject
*
* Store object at given path. Triggers synchronization.
*
* Parameters:
*
* type - unique type of this object within this module. See description below.
* path - path relative to the module root.
* object - an object to be saved to the given node. It must be serializable as JSON.
*
* Returns:
* A promise to store the object. The promise fails with a ValidationError, when validations fail.
*
*
* What about the type?:
*
* A great thing about having data on the web, is to be able to link to
* it and rearrange it to fit the current circumstances. To facilitate
* that, eventually you need to know how the data at hand is structured.
* For documents on the web, this is usually done via a MIME type. The
* MIME type of JSON objects however, is always application/json.
* To add that extra layer of "knowing what this object is", remoteStorage
* aims to use <JSON-LD at http://json-ld.org/>.
* A first step in that direction, is to add a *@context attribute* to all
* JSON data put into remoteStorage.
* Now that is what the *type* is for.
*
* Within remoteStorage.js, @context values are built using three components:
* http://remotestorage.io/spec/modules/ - A prefix to guarantee uniqueness
* the module name - module names should be unique as well
* the type given here - naming this particular kind of object within this module
*
* In retrospect that means, that whenever you introduce a new "type" in calls to
* storeObject, you should make sure that once your code is in the wild, future
* versions of the code are compatible with the same JSON structure.
*
* How to define types?:
*
* See <declareType> for examples.
*/
storeObject: function (typeAlias, path, object) {
if (typeof(typeAlias) !== 'string') {
return Promise.reject('Argument \'typeAlias\' of baseClient.storeObject must be a string');
}
if (typeof(path) !== 'string') {
return Promise.reject('Argument \'path\' of baseClient.storeObject must be a string');
}
if (typeof(object) !== 'object') {
return Promise.reject('Argument \'object\' of baseClient.storeObject must be an object');
}
this._attachType(object, typeAlias);
try {
var validationResult = this.validate(object);
if (! validationResult.valid) {
return Promise.reject(validationResult);
}
} catch(exc) {
return Promise.reject(exc);
}
return this.storage.put(this.makePath(path), JSON.stringify(object), 'application/json; charset=UTF-8').then(function (r) {
if (r.statusCode === 200 || r.statusCode === 201) {
return r.revision;
} else {
return Promise.reject("Request (PUT " + this.makePath(path) + ") failed with status: " + r.statusCode);
}
}.bind(this));
},
// generic operations
/**
* Method: remove
*
* Remove node at given path from storage. Triggers synchronization.
*
* Parameters:
* path - Path relative to the module root.
*/
remove: function (path) {
if (typeof(path) !== 'string') {
return Promise.reject('Argument \'path\' of baseClient.remove must be a string');
}
if (!this.storage.access.checkPathPermission(this.makePath(path), 'rw')) {
console.warn('WARNING: Removing a document to which only read access (\'r\') was claimed');
}
return this.storage.delete(this.makePath(path));
},
cache: function (path, strategy) {
if (typeof(path) !== 'string') {
throw 'Argument \'path\' of baseClient.cache must be a string';
}
if (strategy === false) {
deprecate('caching strategy <false>', '<"FLUSH">');
strategy = 'FLUSH';
} else if (strategy === undefined) {
strategy = 'ALL';
} else if (typeof(strategy) !== 'string') {
deprecate('that caching strategy', '<"ALL">');
strategy = 'ALL';
}
if (strategy !== 'FLUSH' &&
strategy !== 'SEEN' &&
strategy !== 'ALL') {
throw 'Argument \'strategy\' of baseclient.cache must be one of '
+ '["FLUSH", "SEEN", "ALL"]';
}
this.storage.caching.set(this.makePath(path), strategy);
return this;
},
flush: function (path) {
return this.storage.local.flush(path);
},
makePath: function (path) {
return this.base + (path || '');
},
_fireChange: function (event) {
if (RemoteStorage.config.changeEvents[event.origin]) {
['new', 'old', 'lastCommon'].forEach(function (fieldNamePrefix) {
if ((!event[fieldNamePrefix+'ContentType'])
|| (/^application\/(.*)json(.*)/.exec(event[fieldNamePrefix+'ContentType']))) {
if (typeof(event[fieldNamePrefix+'Value']) === 'string') {
try {
event[fieldNamePrefix+'Value'] = JSON.parse(event[fieldNamePrefix+'Value']);
} catch(e) {
}
}
}
});
this._emit('change', event);
}
},
_cleanPath: RemoteStorage.util.cleanPath,
/**
* Method: getItemURL
*
* Retrieve full URL of item
*
* Parameters:
* path - Path relative to the module root.
*/
getItemURL: function (path) {
if (typeof(path) !== 'string') {
throw 'Argument \'path\' of baseClient.getItemURL must be a string';
}
if (this.storage.connected) {
path = this._cleanPath( this.makePath(path) );
return this.storage.remote.href + path;
} else {
return undefined;
}
},
uuid: function () {
return Math.uuid();
}
};
/**
* Method: RS#scope
*
* Returns a new <RS.BaseClient> scoped to the given path.
*
* Parameters:
* path - Root path of new BaseClient.
*
*
* Example:
* (start code)
*
* var foo = remoteStorage.scope('/foo/');
*
* // PUTs data "baz" to path /foo/bar
* foo.storeFile('text/plain', 'bar', 'baz');
*
* var something = foo.scope('something/');
*
* // GETs listing from path /foo/something/bla/
* something.getListing('bla/');
*
* (end code)
*
*/
RS.BaseClient._rs_init = function () {
RS.prototype.scope = function (path) {
if (typeof(path) !== 'string') {
throw 'Argument \'path\' of baseClient.scope must be a string';
}
if (!this.access.checkPathPermission(path, 'r')) {
var escapedPath = path.replace(/(['\\])/g, '\\$1');
console.warn('WARNING: please call remoteStorage.access.claim(\'' + escapedPath + '\', \'r\') (read only) or remoteStorage.access.claim(\'' + escapedPath + '\', \'rw\') (read/write) first');
}
return new RS.BaseClient(this, path);
};
};
/* e.g.:
remoteStorage.defineModule('locations', function (priv, pub) {
return {
exports: {
features: priv.scope('features/').defaultType('feature'),
collections: priv.scope('collections/').defaultType('feature-collection');
}
};
});
*/
// Defined in baseclient/types.js
/**
* Method: declareType
*
* Declare a remoteStorage object type using a JSON schema. See
* <RemoteStorage.BaseClient.Types>
**/
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: src/baseclient/types.js **/
(function(global) {
/**
* Class: RemoteStorage.BaseClient.Types
*
* - Manages and validates types of remoteStorage objects, using JSON-LD and
* JSON Schema
* - Adds schema declaration/validation methods to BaseClient instances.
**/
RemoteStorage.BaseClient.Types = {
// <alias> -> <uri>
uris: {},
// <uri> -> <schema>
schemas: {},
// <uri> -> <alias>
aliases: {},
declare: function(moduleName, alias, uri, schema) {
var fullAlias = moduleName + '/' + alias;
if (schema.extends) {
var extendedAlias;
var parts = schema.extends.split('/');
if (parts.length === 1) {
extendedAlias = moduleName + '/' + parts.shift();
} else {
extendedAlias = parts.join('/');
}
var extendedUri = this.uris[extendedAlias];
if (! extendedUri) {
throw "Type '" + fullAlias + "' tries to extend unknown schema '" + extendedAlias + "'";
}
schema.extends = this.schemas[extendedUri];
}
this.uris[fullAlias] = uri;
this.aliases[uri] = fullAlias;
this.schemas[uri] = schema;
},
resolveAlias: function(alias) {
return this.uris[alias];
},
getSchema: function(uri) {
return this.schemas[uri];
},
inScope: function(moduleName) {
var ml = moduleName.length;
var schemas = {};
for (var alias in this.uris) {
if (alias.substr(0, ml + 1) === moduleName + '/') {
var uri = this.uris[alias];
schemas[uri] = this.schemas[uri];
}
}
return schemas;
}
};
var SchemaNotFound = function(uri) {
var error = new Error("Schema not found: " + uri);
error.name = "SchemaNotFound";
return error;
};
SchemaNotFound.prototype = Error.prototype;
RemoteStorage.BaseClient.Types.SchemaNotFound = SchemaNotFound;
/**
* Class: RemoteStorage.BaseClient
**/
RemoteStorage.BaseClient.prototype.extend({
/**
* Method: declareType
*
* Declare a remoteStorage object type using a JSON schema.
*
* Parameters:
* alias - A type alias/shortname
* uri - (optional) JSON-LD URI of the schema. Automatically generated if none given
* schema - A JSON Schema object describing the object type
*
* Example:
*
* (start code)
* client.declareType('todo-item', {
* "type": "object",
* "properties": {
* "id": {
* "type": "string"
* },
* "title": {
* "type": "string"
* },
* "finished": {
* "type": "boolean"
* "default": false
* },
* "createdAt": {
* "type": "date"
* }
* },
* "required": ["id", "title"]
* })
* (end code)
*
* Visit <http://json-schema.org> for details on how to use JSON Schema.
**/
declareType: function(alias, uri, schema) {
if (! schema) {
schema = uri;
uri = this._defaultTypeURI(alias);
}
RemoteStorage.BaseClient.Types.declare(this.moduleName, alias, uri, schema);
},
/**
* Method: validate
*
* Validate an object against the associated schema.
*
* Parameters:
* object - Object to validate. Must have a @context property.
*
* Returns:
* An object containing information about validation errors
**/
validate: function(object) {
var schema = RemoteStorage.BaseClient.Types.getSchema(object['@context']);
if (schema) {
return tv4.validateResult(object, schema);
} else {
throw new SchemaNotFound(object['@context']);
}
},
_defaultTypeURI: function(alias) {
return 'http://remotestorage.io/spec/modules/' + encodeURIComponent(this.moduleName) + '/' + encodeURIComponent(alias);
},
_attachType: function(object, alias) {
object['@context'] = RemoteStorage.BaseClient.Types.resolveAlias(this.moduleName + '/' + alias) || this._defaultTypeURI(alias);
}
});
// Documented in baseclient.js
Object.defineProperty(RemoteStorage.BaseClient.prototype, 'schemas', {
configurable: true,
get: function() {
return RemoteStorage.BaseClient.Types.inScope(this.moduleName);
}
});
})(typeof(window) !== 'undefined' ? window : global);
/** FILE: src/modules.js **/
(function () {
RemoteStorage.MODULES = {};
/*
* Method: RemoteStorage.defineModule
*
* Method for defining a new remoteStorage data module
*
* Parameters:
* moduleName - Name of the module
* builder - Builder function defining the module
*
* The module builder function should return an object containing another
* object called exports, which will be exported to any <RemoteStorage>
* instance under the module's name. So when defining a locations module,
* like in the example below, it would be accessible via
* `remoteStorage.locations`, which would in turn have a `features` and a
* `collections` property.
*
* The function receives a private and a public client, which are both
* instances of <RemoteStorage.BaseClient>. In the following example, the
* scope of privateClient is `/locations` and the scope of publicClient is
* `/public/locations`.
*
* Example:
* (start code)
* RemoteStorage.defineModule('locations', function (privateClient, publicClient) {
* return {
* exports: {
* features: privateClient.scope('features/').defaultType('feature'),
* collections: privateClient.scope('collections/').defaultType('feature-collection')
* }
* };
* });
* (end code)
*/
RemoteStorage.defineModule = function (moduleName, builder) {
RemoteStorage.MODULES[moduleName] = builder;
Object.defineProperty(RemoteStorage.prototype, moduleName, {
configurable: true,
get: function () {
var instance = this._loadModule(moduleName);
Object.defineProperty(this, moduleName, {
value: instance
});
return instance;
}
});
if (moduleName.indexOf('-') !== -1) {
var camelizedName = moduleName.replace(/\-[a-z]/g, function (s) {
return s[1].toUpperCase();
});
Object.defineProperty(RemoteStorage.prototype, camelizedName, {
get: function () {
return this[moduleName];
}
});
}
};
RemoteStorage.prototype._loadModule = function (moduleName) {
var builder = RemoteStorage.MODULES[moduleName];
if (builder) {
var module = builder(new RemoteStorage.BaseClient(this, '/' + moduleName + '/'),
new RemoteStorage.BaseClient(this, '/public/' + moduleName + '/'));
return module.exports;
} else {
throw "Unknown module: " + moduleName;
}
};
RemoteStorage.prototype.defineModule = function (moduleName) {
console.log("remoteStorage.defineModule is deprecated, use RemoteStorage.defineModule instead!");
RemoteStorage.defineModule.apply(RemoteStorage, arguments);
};
})();
/** FILE: src/debug/inspect.js **/
(function() {
function loadTable(table, storage, paths) {
table.setAttribute('border', '1');
table.style.margin = '8px';
table.style.color = 'white';
table.innerHTML = '';
var thead = document.createElement('thead');
table.appendChild(thead);
var titleRow = document.createElement('tr');
thead.appendChild(titleRow);
['Path', 'Content-Type', 'Revision'].forEach(function(label) {
var th = document.createElement('th');
th.textContent = label;
thead.appendChild(th);
});
var tbody = document.createElement('tbody');
table.appendChild(tbody);
function renderRow(tr, path, contentType, revision) {
[path, contentType, revision].forEach(function(value) {
var td = document.createElement('td');
td.textContent = value || '';
tr.appendChild(td);
});
}
function loadRow(path) {
if (storage.connected === false) { return; }
function processRow(status, body, contentType, revision) {
if (status === 200) {
var tr = document.createElement('tr');
tbody.appendChild(tr);
renderRow(tr, path, contentType, revision);
if (path[path.length - 1] === '/') {
for (var key in body) {
loadRow(path + key);
}
}
}
}
storage.get(path).then(processRow);
}
paths.forEach(loadRow);
}
function renderWrapper(title, table, storage, paths) {
var wrapper = document.createElement('div');
//wrapper.style.display = 'inline-block';
var heading = document.createElement('h2');
heading.textContent = title;
wrapper.appendChild(heading);
var updateButton = document.createElement('button');
updateButton.textContent = "Refresh";
updateButton.onclick = function() { loadTable(table, storage, paths); };
wrapper.appendChild(updateButton);
if (storage.reset) {
var resetButton = document.createElement('button');
resetButton.textContent = "Reset";
resetButton.onclick = function() {
storage.reset(function(newStorage) {
storage = newStorage;
loadTable(table, storage, paths);
});
};
wrapper.appendChild(resetButton);
}
wrapper.appendChild(table);
loadTable(table, storage, paths);
return wrapper;
}
function renderLocalChanges(local) {
var wrapper = document.createElement('div');
//wrapper.style.display = 'inline-block';
var heading = document.createElement('h2');
heading.textContent = "Outgoing changes";
wrapper.appendChild(heading);
var updateButton = document.createElement('button');
updateButton.textContent = "Refresh";
wrapper.appendChild(updateButton);
var list = document.createElement('ul');
list.style.fontFamily = 'courier';
wrapper.appendChild(list);
function updateList() {
list.innerHTML = '';
local.forAllNodes(function(node) {
if (node.local && node.local.body) {
var el = document.createElement('li');
el.textContent = JSON.stringify(node.local);
list.appendChild(el);
}
});
}
updateButton.onclick = updateList;
updateList();
return wrapper;
}
RemoteStorage.prototype.inspect = function() {
var widget = document.createElement('div');
widget.id = 'remotestorage-inspect';
widget.style.position = 'absolute';
widget.style.top = 0;
widget.style.left = 0;
widget.style.background = 'black';
widget.style.color = 'white';
widget.style.border = 'groove 5px #ccc';
var controls = document.createElement('div');
controls.style.position = 'absolute';
controls.style.top = 0;
controls.style.left = 0;
var heading = document.createElement('strong');
heading.textContent = " remotestorage.js inspector ";
controls.appendChild(heading);
var syncButton;
if (this.local) {
syncButton = document.createElement('button');
syncButton.textContent = "Synchronize";
controls.appendChild(syncButton);
}
var closeButton = document.createElement('button');
closeButton.textContent = "Close";
closeButton.onclick = function() {
document.body.removeChild(widget);
};
controls.appendChild(closeButton);
widget.appendChild(controls);
var remoteRootPaths = [];
for (var path in this.caching._rootPaths) {
if (this.caching._rootPaths.hasOwnProperty(path)) {
remoteRootPaths.push(path);
}
}
var remoteTable = document.createElement('table');
var localTable = document.createElement('table');
widget.appendChild(renderWrapper("Remote", remoteTable, this.remote, remoteRootPaths));
if (this.local) {
widget.appendChild(renderWrapper("Local", localTable, this.local, ['/']));
widget.appendChild(renderLocalChanges(this.local));
syncButton.onclick = function() {
this.log('sync clicked');
this.sync.sync().then(function() {
this.log('SYNC FINISHED');
loadTable(localTable, this.local, ['/']);
}.bind(this), function(err) {
console.error("SYNC FAILED", err, err.stack);
});
}.bind(this);
}
document.body.appendChild(widget);
};
})();
/** FILE: src/googledrive.js **/
(function (global) {
/**
* Class: RemoteStorage.GoogleDrive
*
* WORK IN PROGRESS, NOT RECOMMENDED FOR PRODUCTION USE
*
* To use this backend, you need to specify the app's client ID like so:
*
* (start code)
*
* remoteStorage.setApiKeys('googledrive', {
* clientId: 'your-client-id'
* });
*
* (end code)
*
* An client ID can be obtained by registering your app in the Google
* Developers Console: https://developers.google.com/drive/web/auth/web-client
*
* Docs: https://developers.google.com/drive/web/auth/web-client#create_a_client_id_and_client_secret
**/
var RS = RemoteStorage;
var BASE_URL = 'https://www.googleapis.com';
var AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';
var AUTH_SCOPE = 'https://www.googleapis.com/auth/drive';
var GD_DIR_MIME_TYPE = 'application/vnd.google-apps.folder';
var RS_DIR_MIME_TYPE = 'application/json; charset=UTF-8';
function buildQueryString(params) {
return Object.keys(params).map(function (key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
}
function fileNameFromMeta(meta) {
return encodeURIComponent(meta.title) + (meta.mimeType === GD_DIR_MIME_TYPE ? '/' : '');
}
function metaTitleFromFileName(filename) {
if (filename.substr(-1) === '/') {
filename = filename.substr(0, filename.length - 1);
}
return decodeURIComponent(filename);
}
function parentPath(path) {
return path.replace(/[^\/]+\/?$/, '');
}
function baseName(path) {
var parts = path.split('/');
if (path.substr(-1) === '/') {
return parts[parts.length-2]+'/';
} else {
return parts[parts.length-1];
}
}
var Cache = function (maxAge) {
this.maxAge = maxAge;
this._items = {};
};
Cache.prototype = {
get: function (key) {
var item = this._items[key];
var now = new Date().getTime();
return (item && item.t >= (now - this.maxAge)) ? item.v : undefined;
},
set: function (key, value) {
this._items[key] = {
v: value,
t: new Date().getTime()
};
}
};
RS.GoogleDrive = function (remoteStorage, clientId) {
RS.eventHandling(this, 'change', 'connected', 'wire-busy', 'wire-done', 'not-connected');
this.rs = remoteStorage;
this.clientId = clientId;
this._fileIdCache = new Cache(60 * 5); // ids expire after 5 minutes (is this a good idea?)
};
RS.GoogleDrive.prototype = {
connected: false,
online: true,
configure: function (settings) { // Settings parameter compatible with WireClient
if (settings.token) {
localStorage['remotestorage:googledrive:token'] = settings.token;
this.token = settings.token;
this.connected = true;
this._emit('connected');
} else {
this.connected = false;
delete this.token;
delete localStorage['remotestorage:googledrive:token'];
}
},
connect: function () {
this.rs.setBackend('googledrive');
RS.Authorize(this.rs, AUTH_URL, AUTH_SCOPE, String(RS.Authorize.getLocation()), this.clientId);
},
stopWaitingForToken: function () {
if (!this.connected) {
this._emit('not-connected');
}
},
get: function (path, options) {
if (path.substr(-1) === '/') {
return this._getFolder(path, options);
} else {
return this._getFile(path, options);
}
},
put: function (path, body, contentType, options) {
var self = this;
function putDone(response) {
if (response.status >= 200 && response.status < 300) {
var meta = JSON.parse(response.responseText);
var etagWithoutQuotes = meta.etag.substring(1, meta.etag.length-1);
return Promise.resolve({statusCode: 200, contentType: meta.mimeType, revision: etagWithoutQuotes});
} else if (response.status === 412) {
return Promise.resolve({statusCode: 412, revision: 'conflict'});
} else {
return Promise.reject("PUT failed with status " + response.status + " (" + response.responseText + ")");
}
}
return self._getFileId(path).then(function (id) {
if (id) {
if (options && (options.ifNoneMatch === '*')) {
return putDone({ status: 412 });
}
return self._updateFile(id, path, body, contentType, options).then(putDone);
} else {
return self._createFile(path, body, contentType, options).then(putDone);
}
});
},
'delete': function (path, options) {
var self = this;
return self._getFileId(path).then(function (id) {
if (!id) {
// File doesn't exist. Ignore.
return Promise.resolve({statusCode: 200});
}
return self._getMeta(id).then(function (meta) {
var etagWithoutQuotes;
if ((typeof meta === 'object') && (typeof meta.etag === 'string')) {
etagWithoutQuotes = meta.etag.substring(1, meta.etag.length-1);
}
if (options && options.ifMatch && (options.ifMatch !== etagWithoutQuotes)) {
return {statusCode: 412, revision: etagWithoutQuotes};
}
return self._request('DELETE', BASE_URL + '/drive/v2/files/' + id, {}).then(function (response) {
if (response.status === 200 || response.status === 204) {
return {statusCode: 200};
} else {
return Promise.reject("Delete failed: " + response.status + " (" + response.responseText + ")");
}
});
});
});
},
_updateFile: function (id, path, body, contentType, options) {
var self = this;
var metadata = {
mimeType: contentType
};
var headers = {
'Content-Type': 'application/json; charset=UTF-8'
};
if (options && options.ifMatch) {
headers['If-Match'] = '"' + options.ifMatch + '"';
}
return self._request('PUT', BASE_URL + '/upload/drive/v2/files/' + id + '?uploadType=resumable', {
body: JSON.stringify(metadata),
headers: headers
}).then(function (response) {
if (response.status === 412) {
return (response);
} else {
return self._request('PUT', response.getResponseHeader('Location'), {
body: contentType.match(/^application\/json/) ? JSON.stringify(body) : body
});
}
});
},
_createFile: function (path, body, contentType, options) {
var self = this;
return self._getParentId(path).then(function (parentId) {
var fileName = baseName(path);
var metadata = {
title: metaTitleFromFileName(fileName),
mimeType: contentType,
parents: [{
kind: "drive#fileLink",
id: parentId
}]
};
return self._request('POST', BASE_URL + '/upload/drive/v2/files?uploadType=resumable', {
body: JSON.stringify(metadata),
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
}).then(function (response) {
return self._request('POST', response.getResponseHeader('Location'), {
body: contentType.match(/^application\/json/) ? JSON.stringify(body) : body
});
});
});
},
_getFile: function (path, options) {
var self = this;
return self._getFileId(path).then(function (id) {
return self._getMeta(id).then(function (meta) {
var etagWithoutQuotes;
if (typeof(meta) === 'object' && typeof(meta.etag) === 'string') {
etagWithoutQuotes = meta.etag.substring(1, meta.etag.length-1);
}
if (options && options.ifNoneMatch && (etagWithoutQuotes === options.ifNoneMatch)) {
return Promise.resolve({statusCode: 304});
}
var options2 = {};
if (!meta.downloadUrl) {
if (meta.exportLinks && meta.exportLinks['text/html']) {
// Documents that were generated inside GoogleDocs have no
// downloadUrl, but you can export them to text/html instead:
meta.mimeType += ';export=text/html';
meta.downloadUrl = meta.exportLinks['text/html'];
} else {
// empty file
return Promise.resolve({statusCode: 200, body: '', contentType: meta.mimeType, revision: etagWithoutQuotes});
}
}
if (meta.mimeType.match(/charset=binary/)) {
options2.responseType = 'blob';
}
return self._request('GET', meta.downloadUrl, options2).then(function (response) {
var body = response.response;
if (meta.mimeType.match(/^application\/json/)) {
try {
body = JSON.parse(body);
} catch(e) {}
}
return Promise.resolve({statusCode: 200, body: body, contentType: meta.mimeType, revision: etagWithoutQuotes});
});
});
});
},
_getFolder: function (path, options) {
var self = this;
return self._getFileId(path).then(function (id) {
var query, fields, data, i, etagWithoutQuotes, itemsMap;
if (! id) {
return Promise.resolve({statusCode: 404});
}
query = '\'' + id + '\' in parents';
fields = 'items(downloadUrl,etag,fileSize,id,mimeType,title)';
return self._request('GET', BASE_URL + '/drive/v2/files?'
+ 'q=' + encodeURIComponent(query)
+ '&fields=' + encodeURIComponent(fields)
+ '&maxResults=1000',
{})
.then(function (response) {
if (response.status !== 200) {
return Promise.reject('request failed or something: ' + response.status);
}
try {
data = JSON.parse(response.responseText);
} catch(e) {
return Promise.reject('non-JSON response from GoogleDrive');
}
itemsMap = {};
for (var i = 0, len = data.items.length; i < len; i++) {
etagWithoutQuotes = data.items[i].etag.substring(1, data.items[i].etag.length-1);
if (data.items[i].mimeType === GD_DIR_MIME_TYPE) {
self._fileIdCache.set(path + data.items[i].title + '/', data.items[i].id);
itemsMap[data.items[i].title + '/'] = {
ETag: etagWithoutQuotes
};
} else {
self._fileIdCache.set(path + data.items[i].title, data.items[i].id);
itemsMap[data.items[i].title] = {
ETag: etagWithoutQuotes,
'Content-Type': data.items[i].mimeType,
'Content-Length': data.items[i].fileSize
};
}
}
// FIXME: add revision of folder!
return Promise.resolve({statusCode: 200, body: itemsMap, contentType: RS_DIR_MIME_TYPE, revision: undefined});
});
});
},
_getParentId: function (path) {
var foldername = parentPath(path);
var self = this;
return self._getFileId(foldername).then(function (parentId) {
if (parentId) {
return Promise.resolve(parentId);
} else {
return self._createFolder(foldername);
}
});
},
_createFolder: function (path) {
var self = this;
return self._getParentId(path).then(function (parentId) {
return self._request('POST', BASE_URL + '/drive/v2/files', {
body: JSON.stringify({
title: metaTitleFromFileName(baseName(path)),
mimeType: GD_DIR_MIME_TYPE,
parents: [{
id: parentId
}]
}),
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
}).then(function (response) {
var meta = JSON.parse(response.responseText);
return Promise.resolve(meta.id);
});
});
},
_getFileId: function (path) {
var self = this;
var id;
if (path === '/') {
// "root" is a special alias for the fileId of the root folder
return Promise.resolve('root');
} else if ((id = this._fileIdCache.get(path))) {
// id is cached.
return Promise.resolve(id);
}
// id is not cached (or file doesn't exist).
// load parent folder listing to propagate / update id cache.
return self._getFolder(parentPath(path)).then(function () {
id = self._fileIdCache.get(path);
if (!id) {
if (path.substr(-1) === '/') {
return self._createFolder(path).then(function () {
return self._getFileId(path);
});
} else {
return Promise.resolve();
}
return;
}
return Promise.resolve(id);
});
},
_getMeta: function (id) {
return this._request('GET', BASE_URL + '/drive/v2/files/' + id, {}).then(function (response) {
if (response.status === 200) {
return Promise.resolve(JSON.parse(response.responseText));
} else {
return Promise.reject("request (getting metadata for " + id + ") failed with status: " + response.status);
}
});
},
_request: function (method, url, options) {
var self = this;
if (! options.headers) { options.headers = {}; }
options.headers['Authorization'] = 'Bearer ' + self.token;
return RS.WireClient.request(method, url, options).then(function (xhr) {
// google tokens expire from time to time...
if (xhr && xhr.status === 401) {
self.connect();
return;
}
return xhr;
});
}
};
RS.GoogleDrive._rs_init = function (remoteStorage) {
var config = remoteStorage.apiKeys.googledrive;
if (config) {
remoteStorage.googledrive = new RS.GoogleDrive(remoteStorage, config.clientId);
if (remoteStorage.backend === 'googledrive') {
remoteStorage._origRemote = remoteStorage.remote;
remoteStorage.remote = remoteStorage.googledrive;
}
}
};
RS.GoogleDrive._rs_supported = function (rs) {
return true;
};
RS.GoogleDrive._rs_cleanup = function (remoteStorage) {
remoteStorage.setBackend(undefined);
if (remoteStorage._origRemote) {
remoteStorage.remote = remoteStorage._origRemote;
delete remoteStorage._origRemote;
}
};
})(this);
/** FILE: src/dropbox.js **/
(function (global) {
var RS = RemoteStorage;
/**
* File: Dropbox
*
* WORK IN PROGRESS, NOT RECOMMENDED FOR PRODUCTION USE
*
* Dropbox backend for RemoteStorage.js
* This file exposes a get/put/delete interface which is compatible with
* <RemoteStorage.WireClient>.
*
* When remoteStorage.backend is set to 'dropbox', this backend will
* initialize and replace remoteStorage.remote with remoteStorage.dropbox.
*
* In order to ensure compatibility with the public folder, <BaseClient.getItemURL>
* gets hijacked to return the Dropbox public share URL.
*
* To use this backend, you need to specify the Dropbox app key like so:
*
* (start code)
*
* remoteStorage.setApiKeys('dropbox', {
* appKey: 'your-app-key'
* });
*
* (end code)
*
* An app key can be obtained by registering your app at https://www.dropbox.com/developers/apps
*
* Known issues:
*
* - Storing files larger than 150MB is not yet supported
* - Listing and deleting folders with more than 10'000 files will cause problems
* - Content-Type is not fully supported due to limitations of the Dropbox API
* - Dropbox preserves cases but is not case-sensitive
* - getItemURL is asynchronous which means getIetmURL returns useful values
* after the syncCycle
*/
var hasLocalStorage;
var AUTH_URL = 'https://www.dropbox.com/1/oauth2/authorize';
var SETTINGS_KEY = 'remotestorage:dropbox';
var PATH_PREFIX = '/remotestorage';
/**
* Function: getDropboxPath(path)
*
* Map a local path to a path in DropBox.
*/
var getDropboxPath = function (path) {
return RS.WireClient.cleanPath(PATH_PREFIX + '/' + path);
};
var encodeQuery = function (obj) {
var pairs = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
}
return pairs.join('&');
};
/**
* class: LowerCaseCache
*
* A cache which automatically converts all keys to lower case and can
* propagate changes up to parent folders.
*
* By default the set and delete methods are aliased to justSet and justDelete.
*
* Parameters:
*
* defaultValue - the value that is returned for all keys that don't exist
* in the cache
*/
function LowerCaseCache(defaultValue){
this.defaultValue = defaultValue;
this._storage = { };
this.set = this.justSet;
this.delete = this.justDelete;
}
LowerCaseCache.prototype = {
/**
* Method: get
*
* Get a value from the cache or defaultValue, if the key is not in the
* cache.
*/
get : function (key) {
key = key.toLowerCase();
var stored = this._storage[key];
if (typeof stored === 'undefined'){
stored = this.defaultValue;
this._storage[key] = stored;
}
return stored;
},
/**
* Method: propagateSet
*
* Set a value and also update the parent folders with that value.
*/
propagateSet : function (key, value) {
key = key.toLowerCase();
if (this._storage[key] === value) {
return value;
}
this._propagate(key, value);
this._storage[key] = value;
return value;
},
/**
* Method: propagateDelete
*
* Delete a value and propagate the changes to the parent folders.
*/
propagateDelete : function (key) {
key = key.toLowerCase();
this._propagate(key, this._storage[key]);
return delete this._storage[key];
},
_activatePropagation: function (){
this.set = this.propagateSet;
this.delete = this.propagateDelete;
return true;
},
/**
* Method: justSet
*
* Set a value without propagating.
*/
justSet : function (key, value) {
key = key.toLowerCase();
this._storage[key] = value;
return value;
},
/**
* Method: justDelete
*
* Delete a value without propagating.
*/
justDelete : function (key, value) {
key = key.toLowerCase();
return delete this._storage[key];
},
_propagate: function (key, rev){
var folders = key.split('/').slice(0,-1);
var path = '';
for (var i = 0, len = folders.length; i < len; i++){
path += folders[i]+'/';
if (!rev) {
rev = this._storage[path]+1;
}
this._storage[path] = rev;
}
}
};
var onErrorCb;
/**
* Class: RemoteStorage.Dropbox
*/
RS.Dropbox = function (rs) {
this.rs = rs;
this.connected = false;
this.rs = rs;
var self = this;
onErrorCb = function (error){
if (error instanceof RemoteStorage.Unauthorized) {
// Delete all the settings - see the documentation of wireclient.configure
self.configure({
userAddress: null,
href: null,
storageApi: null,
token: null,
options: null
});
}
};
RS.eventHandling(this, 'change', 'connected', 'wire-busy', 'wire-done', 'not-connected');
rs.on('error', onErrorCb);
this.clientId = rs.apiKeys.dropbox.appKey;
this._revCache = new LowerCaseCache('rev');
this._itemRefs = {};
this._metadataCache = {};
if (hasLocalStorage){
var settings;
try {
settings = JSON.parse(localStorage[SETTINGS_KEY]);
} catch(e){}
if (settings) {
this.configure(settings);
}
try {
this._itemRefs = JSON.parse(localStorage[ SETTINGS_KEY+':shares' ]);
} catch(e) { }
}
if (this.connected) {
setTimeout(this._emit.bind(this), 0, 'connected');
}
};
RS.Dropbox.prototype = {
online: true,
/**
* Method: connect
*
* Set the backed to 'dropbox' and start the authentication flow in order
* to obtain an API token from Dropbox.
*/
connect: function () {
// TODO handling when token is already present
this.rs.setBackend('dropbox');
if (this.token){
hookIt(this.rs);
} else {
RS.Authorize(this.rs, AUTH_URL, '', String(RS.Authorize.getLocation()), this.clientId);
}
},
/**
* Method : configure(settings)
* Accepts its parameters according to the <RemoteStorage.WireClient>.
* Sets the connected flag
**/
configure: function (settings) {
// We only update this.userAddress if settings.userAddress is set to a string or to null:
if (typeof settings.userAddress !== 'undefined') { this.userAddress = settings.userAddress; }
// Same for this.token. If only one of these two is set, we leave the other one at its existing value:
if (typeof settings.token !== 'undefined') { this.token = settings.token; }
if (this.token) {
this.connected = true;
if ( !this.userAddress ){
this.info().then(function (info){
this.userAddress = info.display_name;
this.rs.widget.view.setUserAddress(this.userAddress);
this._emit('connected');
}.bind(this));
}
} else {
this.connected = false;
}
if (hasLocalStorage){
localStorage[SETTINGS_KEY] = JSON.stringify({
userAddress: this.userAddress,
token: this.token
});
}
},
/**
* Method: stopWaitingForToken
*
* Stop waiting for the token and emit not-connected
*/
stopWaitingForToken: function () {
if (!this.connected) {
this._emit('not-connected');
}
},
/**
* Method: _getFolder
*
* Get all items in a folder.
*
* Parameters:
*
* path - path of the folder to get, with leading slash
* options - not used
*
* Returns:
*
* statusCode - HTTP status code
* body - array of the items found
* contentType - 'application/json; charset=UTF-8'
* revision - revision of the folder
*/
_getFolder: function (path, options) {
// FIXME simplify promise handling
var url = 'https://api.dropbox.com/1/metadata/auto' + getDropboxPath(path);
var revCache = this._revCache;
var self = this;
return this._request('GET', url, {}).then(function (resp) {
var status = resp.status;
if (status === 304) {
return Promise.resolve({statusCode: status});
}
var listing, body, mime, rev;
try{
body = JSON.parse(resp.responseText);
} catch (e) {
return Promise.reject(e);
}
rev = self._revCache.get(path);
mime = 'application/json; charset=UTF-8';
if (body.contents) {
listing = body.contents.reduce(function (m, item) {
var itemName = item.path.split('/').slice(-1)[0] + ( item.is_dir ? '/' : '' );
if (item.is_dir){
m[itemName] = { ETag: revCache.get(path+itemName) };
} else {
m[itemName] = { ETag: item.rev };
}
return m;
}, {});
}
return Promise.resolve({statusCode: status, body: listing, contentType: mime, revision: rev});
});
},
/**
* Method: get
*
* Compatible with <RemoteStorage.WireClient.get>
*
* Checks for the path in _revCache and decides based on that if file has
* changed. Calls _getFolder is the path points to a folder.
*
* Calls <RemoteStorage.Dropbox.share> afterwards to fill _itemRefs.
*/
get: function (path, options) {
if (! this.connected) { return Promise.reject("not connected (path: " + path + ")"); }
var url = 'https://api-content.dropbox.com/1/files/auto' + getDropboxPath(path);
var self = this;
var savedRev = this._revCache.get(path);
if (savedRev === null) {
// file was deleted server side
return Promise.resolve({statusCode: 404});
}
if (options && options.ifNoneMatch &&
savedRev && (savedRev === options.ifNoneMatch)) {
// nothing changed.
return Promise.resolve({statusCode: 304});
}
//use _getFolder for folders
if (path.substr(-1) === '/') { return this._getFolder(path, options); }
return this._request('GET', url, {}).then(function (resp) {
var status = resp.status;
var meta, body, mime, rev;
if (status !== 200) {
return Promise.resolve({statusCode: status});
}
body = resp.responseText;
try {
meta = JSON.parse( resp.getResponseHeader('x-dropbox-metadata') );
} catch(e) {
return Promise.reject(e);
}
mime = meta.mime_type; //resp.getResponseHeader('Content-Type');
rev = meta.rev;
self._revCache.set(path, rev);
self._shareIfNeeded(path); // The shared link expires every 4 hours
// handling binary
if (!resp.getResponseHeader('Content-Type') ||
resp.getResponseHeader('Content-Type').match(/charset=binary/)) {
var pending = Promise.defer();
RS.WireClient.readBinaryData(resp.response, mime, function (result) {
pending.resolve({
statusCode: status,
body: result,
contentType: mime,
revision: rev
});
});
return pending.promise;
}
// handling json (always try)
if (mime && mime.search('application/json') >= 0 || true) {
try {
body = JSON.parse(body);
mime = 'application/json; charset=UTF-8';
} catch(e) {
//Failed parsing Json, assume it is something else then
}
}
return Promise.resolve({statusCode: status, body: body, contentType: mime, revision: rev});
});
},
/**
* Method: put
*
* Compatible with <RemoteStorage.WireClient>
*
* Checks for the path in _revCache and decides based on that if file has
* changed.
*
* Calls <RemoteStorage.Dropbox.share> afterwards to fill _itemRefs.
*/
put: function (path, body, contentType, options) {
var self = this;
if (!this.connected) {
throw new Error("not connected (path: " + path + ")");
}
//check if file has changed and return 412
var savedRev = this._revCache.get(path);
if (options && options.ifMatch &&
savedRev && (savedRev !== options.ifMatch)) {
return Promise.resolve({statusCode: 412, revision: savedRev});
}
if (options && (options.ifNoneMatch === '*') &&
savedRev && (savedRev !== 'rev')) {
return Promise.resolve({statusCode: 412, revision: savedRev});
}
if ((!contentType.match(/charset=/)) &&
(body instanceof ArrayBuffer || RS.WireClient.isArrayBufferView(body))) {
contentType += '; charset=binary';
}
if (body.length > 150 * 1024 * 1024) {
//https://www.dropbox.com/developers/core/docs#chunked-upload
return Promise.reject(new Error("Cannot upload file larger than 150MB"));
}
var result;
var needsMetadata = options && (options.ifMatch || (options.ifNoneMatch === '*'));
var uploadParams = {
body: body,
contentType: contentType,
path: path
};
if (needsMetadata) {
result = this._getMetadata(path).then(function (metadata) {
if (options && (options.ifNoneMatch === '*') && metadata) {
// if !!metadata === true, the file exists
return Promise.resolve({
statusCode: 412,
revision: metadata.rev
});
}
if (options && options.ifMatch && metadata && (metadata.rev !== options.ifMatch)) {
return Promise.resolve({
statusCode: 412,
revision: metadata.rev
});
}
return self._uploadSimple(uploadParams);
});
} else {
result = self._uploadSimple(uploadParams);
}
return result.then(function (ret) {
self._shareIfNeeded(path);
return ret;
});
},
/**
* Method: delete
*
* Compatible with <RemoteStorage.WireClient.delete>
*
* Checks for the path in _revCache and decides based on that if file has
* changed.
*
* Calls <RemoteStorage.Dropbox.share> afterwards to fill _itemRefs.
*/
'delete': function (path, options) {
var self = this;
if (!this.connected) {
throw new Error("not connected (path: " + path + ")");
}
//check if file has changed and return 412
var savedRev = this._revCache.get(path);
if (options && options.ifMatch && savedRev && (options.ifMatch !== savedRev)) {
return Promise.resolve({ statusCode: 412, revision: savedRev });
}
if (options && options.ifMatch) {
return this._getMetadata(path).then(function (metadata) {
if (options && options.ifMatch && metadata && (metadata.rev !== options.ifMatch)) {
return Promise.resolve({
statusCode: 412,
revision: metadata.rev
});
}
return self._deleteSimple(path);
});
}
return self._deleteSimple(path);
},
/**
* Method: _shareIfNeeded
*
* Calls share, if the provided path resides in a public folder.
*/
_shareIfNeeded: function (path) {
if (path.match(/^\/public\/.*[^\/]$/) && this._itemRefs[path] === undefined) {
this.share(path);
}
},
/**
* Method: share
*
* Gets a publicly-accessible URL for the path from Dropbox and stores it
* in _itemRefs.
*
* Returns:
*
* A promise for the URL
*/
share: function (path) {
var self = this;
var url = 'https://api.dropbox.com/1/media/auto' + getDropboxPath(path);
return this._request('POST', url, {}).then(function (response) {
if (response.status !== 200) {
return Promise.reject(new Error('Invalid Dropbox API response status when sharing "' + path + '":' + response.status));
}
try {
response = JSON.parse(response.responseText);
} catch (e) {
return Promise.reject(new Error('Invalid Dropbox API response when sharing "' + path + '": ' + response.responseText));
}
self._itemRefs[path] = response.url;
if (hasLocalStorage) {
localStorage[SETTINGS_KEY + ':shares'] = JSON.stringify(self._itemRefs);
}
return Promise.resolve(url);
}, function (error) {
err.message = 'Sharing dropbox file or folder ("' + path + '") failed.' + err.message;
return Promise.reject(error);
});
},
/**
* Method: info
*
* Fetches the user's info from dropbox and returns a promise for it.
*
* Returns:
*
* A promise to the user's info
*/
info: function () {
var url = 'https://api.dropbox.com/1/account/info';
// requesting user info(mainly for userAdress)
return this._request('GET', url, {}).then(function (resp){
try {
var info = JSON.parse(resp.responseText);
return Promise.resolve(info);
} catch (e) {
return Promise.reject(e);
}
});
},
/**
* Method: _request
*
* Make a HTTP request.
*
* Options:
*
* headers - an object containing the request headers
*
* Parameters:
*
* method - the method to use
* url - the URL to make the request to
* options - see above
*/
_request: function (method, url, options) {
var self = this;
if (! options.headers) { options.headers = {}; }
options.headers['Authorization'] = 'Bearer ' + this.token;
return RS.WireClient.request.call(this, method, url, options).then(function (xhr) {
//503 means retry this later
if (xhr && xhr.status === 503) {
return global.setTimeout(self._request(method, url, options), 3210);
} else {
return Promise.resolve(xhr);
}
});
},
/**
* Method: fetchDelta
*
* Fetches the revision of all the files from dropbox API and puts them
* into _revCache. These values can then be used to determine if something
* has changed.
*/
fetchDelta: function () {
// TODO: Handle `has_more`
var args = Array.prototype.slice.call(arguments);
var self = this;
var body = { path_prefix: PATH_PREFIX };
if (self._deltaCursor) {
body.cursor = self._deltaCursor;
}
return self._request('POST', 'https://api.dropbox.com/1/delta', {
body: encodeQuery(body),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function (response) {
// break if status != 200
if (response.status !== 200 ) {
if (response.status === 400) {
self.rs._emit('error', new RemoteStorage.Unauthorized());
return Promise.resolve(args);
} else {
return Promise.reject("dropbox.fetchDelta returned "+response.status+response.responseText);
}
return;
}
var delta;
try {
delta = JSON.parse(response.responseText);
} catch(error) {
RS.log('fetchDeltas can not parse response',error);
return Promise.reject("can not parse response of fetchDelta : "+error.message);
}
// break if no entries found
if (!delta.entries) {
return Promise.reject('dropbox.fetchDeltas failed, no entries found');
}
// Dropbox sends the complete state
if (delta.reset) {
self._revCache = new LowerCaseCache('rev');
}
//saving the cursor for requesting further deltas in relation to the cursor position
if (delta.cursor) {
self._deltaCursor = delta.cursor;
}
//updating revCache
delta.entries.forEach(function (entry) {
var path = entry[0].substr(PATH_PREFIX.length);
var rev;
if (!entry[1]){
rev = null;
} else {
if (entry[1].is_dir) {
return;
}
rev = entry[1].rev;
}
self._revCache.set(path, rev);
});
return Promise.resolve(args);
}, function (err) {
this.rs.log('fetchDeltas', err);
this.rs._emit('error', new RemoteStorage.SyncError('fetchDeltas failed.' + err));
promise.reject(err);
}).then(function () {
if (self._revCache) {
var args = Array.prototype.slice.call(arguments);
self._revCache._activatePropagation();
return Promise.resolve(args);
}
});
},
/**
* Method: _getMetadata
*
* Gets metadata for a path (can point to either a file or a folder).
*
* Options:
*
* list - if path points to a folder, specifies whether to list the
* metadata of the folder's children. False by default.
*
* Parameters:
*
* path - the path to get metadata for
* options - see above
*
* Returns:
*
* A promise for the metadata
*/
_getMetadata: function (path, options) {
var self = this;
var cached = this._metadataCache[path];
var url = 'https://api.dropbox.com/1/metadata/auto' + getDropboxPath(path);
url += '?list=' + ((options && options.list) ? 'true' : 'false');
if (cached && cached.hash) {
url += '&hash=' + encodeURIComponent(cached.hash);
}
return this._request('GET', url, {}).then(function (resp) {
if (resp.status === 304) {
return Promise.resolve(cached);
} else if (resp.status === 200) {
var response = JSON.parse(resp.responseText);
self._metadataCache[path] = response;
return Promise.resolve(response);
} else {
// The file doesn't exist
return Promise.resolve();
}
});
},
/**
* Method: _uploadSimple
*
* Upload a simple file (the size is no more than 150MB).
*
* Parameters:
*
* ifMatch - same as for get
* path - path of the file
* body - contents of the file to upload
* contentType - mime type of the file
*
* Returns:
*
* statusCode - HTTP status code
* revision - revision of the newly-created file, if any
*/
_uploadSimple: function (params) {
var self = this;
var url = 'https://api-content.dropbox.com/1/files_put/auto' + getDropboxPath(params.path) + '?';
if (params && params.ifMatch) {
url += "parent_rev=" + encodeURIComponent(params.ifMatch);
}
return self._request('PUT', url, {
body: params.body,
headers: {
'Content-Type': params.contentType
}
}).then(function (resp) {
if (resp.status !== 200) {
return Promise.resolve({ statusCode: resp.status });
}
var response;
try {
response = JSON.parse(resp.responseText);
} catch (e) {
return Promise.reject(e);
}
// Conflict happened. Delete the copy created by dropbox
if (response.path !== getDropboxPath(params.path)) {
var deleteUrl = 'https://api.dropbox.com/1/fileops/delete?root=auto&path=' + encodeURIComponent(response.path);
self._request('POST', deleteUrl, {});
return self._getMetadata(params.path).then(function (metadata) {
return Promise.resolve({
statusCode: 412,
revision: metadata.rev
});
});
}
self._revCache.propagateSet(params.path, response.rev);
return Promise.resolve({ statusCode: resp.status });
});
},
/**
* Method: _deleteSimple
*
* Deletes a file or a folder. If the folder contains more than 10'000 items
* (recursively) then the operation may not complete successfully. If that
* is the case, an Error gets thrown.
*
* Parameters:
*
* path - the path to delete
*
* Returns:
*
* statusCode - HTTP status code
*/
_deleteSimple: function (path) {
var self = this;
var url = 'https://api.dropbox.com/1/fileops/delete?root=auto&path=' + encodeURIComponent(getDropboxPath(path));
return self._request('POST', url, {}).then(function (resp) {
if (resp.status === 406) {
// Too many files would be involved in the operation for it to
// complete successfully.
// TODO: Handle this somehow
return Promise.reject(new Error("Cannot delete '" + path + "': too many files involved"));
}
if (resp.status === 200 || resp.status === 404) {
self._revCache.delete(path);
delete self._itemRefs[path];
}
return Promise.resolve({ statusCode: resp.status });
});
}
};
//hooking and unhooking the sync
function hookSync(rs) {
if (rs._dropboxOrigSync) { return; } // already hooked
rs._dropboxOrigSync = rs.sync.sync.bind(rs.sync);
rs.sync.sync = function () {
return this.dropbox.fetchDelta.apply(this.dropbox, arguments).
then(rs._dropboxOrigSync, function (err) {
rs._emit('error', new RemoteStorage.SyncError(err));
});
}.bind(rs);
}
function unHookSync(rs) {
if (! rs._dropboxOrigSync) { return; } // not hooked
rs.sync.sync = rs._dropboxOrigSync;
delete rs._dropboxOrigSync;
}
// hooking and unhooking getItemURL
function hookGetItemURL(rs) {
if (rs._origBaseClientGetItemURL) { return; }
rs._origBaseClientGetItemURL = RS.BaseClient.prototype.getItemURL;
RS.BaseClient.prototype.getItemURL = function (path){
var ret = rs.dropbox._itemRefs[path];
return ret ? ret : '';
};
}
function unHookGetItemURL(rs){
if (! rs._origBaseClientGetItemURL) { return; }
RS.BaseClient.prototype.getItemURL = rs._origBaseClientGetItemURL;
delete rs._origBaseClientGetItemURL;
}
function hookRemote(rs){
if (rs._origRemote) { return; }
rs._origRemote = rs.remote;
rs.remote = rs.dropbox;
}
function unHookRemote(rs){
if (rs._origRemote) {
rs.remote = rs._origRemote;
delete rs._origRemote;
}
}
function hookIt(rs){
hookRemote(rs);
if (rs.sync) {
hookSync(rs);
} else {
// when sync is not available yet, we wait for the remote to be connected,
// at which point sync should be available as well
rs.on('connected', function() {
if (rs.sync) {
hookSync(rs);
}
});
}
hookGetItemURL(rs);
}
function unHookIt(rs){
unHookRemote(rs);
unHookSync(rs);
unHookGetItemURL(rs);
}
RS.Dropbox._rs_init = function (rs) {
hasLocalStorage = RemoteStorage.util.localStorageAvailable();
if ( rs.apiKeys.dropbox ) {
rs.dropbox = new RS.Dropbox(rs);
}
if (rs.backend === 'dropbox') {
hookIt(rs);
}
};
RS.Dropbox._rs_supported = function () {
return true;
};
RS.Dropbox._rs_cleanup = function (rs) {
unHookIt(rs);
if (hasLocalStorage){
delete localStorage[SETTINGS_KEY];
}
rs.removeEventListener('error', onErrorCb);
rs.setBackend(undefined);
};
})(this);
remoteStorage = new RemoteStorage(); |
ajax/libs/react-router-bootstrap/0.21.0/ReactRouterBootstrap.js | holtkamp/cdnjs | (function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["ReactRouterBootstrap"] = factory(require("react"));
else
root["ReactRouterBootstrap"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_2__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _IndexLinkContainer2 = __webpack_require__(1);
var _IndexLinkContainer3 = _interopRequireDefault(_IndexLinkContainer2);
exports.IndexLinkContainer = _IndexLinkContainer3['default'];
var _LinkContainer2 = __webpack_require__(3);
var _LinkContainer3 = _interopRequireDefault(_LinkContainer2);
exports.LinkContainer = _LinkContainer3['default'];
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _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; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _LinkContainer = __webpack_require__(3);
var _LinkContainer2 = _interopRequireDefault(_LinkContainer);
var IndexLinkContainer = (function (_React$Component) {
_inherits(IndexLinkContainer, _React$Component);
function IndexLinkContainer() {
_classCallCheck(this, IndexLinkContainer);
_get(Object.getPrototypeOf(IndexLinkContainer.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(IndexLinkContainer, [{
key: 'render',
value: function render() {
return _react2['default'].createElement(_LinkContainer2['default'], _extends({}, this.props, { onlyActiveOnIndex: true }));
}
}]);
return IndexLinkContainer;
})(_react2['default'].Component);
exports['default'] = IndexLinkContainer;
module.exports = exports['default'];
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_2__;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
// This is largely taken from rrtr/lib/Link.
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
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 = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _rrtrLibLink = __webpack_require__(4);
var _rrtrLibLink2 = _interopRequireDefault(_rrtrLibLink);
var LinkContainer = (function (_React$Component) {
_inherits(LinkContainer, _React$Component);
function LinkContainer(props, context) {
_classCallCheck(this, LinkContainer);
_get(Object.getPrototypeOf(LinkContainer.prototype), 'constructor', this).call(this, props, context);
this.onClick = this.onClick.bind(this);
}
_createClass(LinkContainer, [{
key: 'onClick',
value: function onClick(event) {
if (this.props.disabled) {
event.preventDefault();
return;
}
if (this.props.children.props.onClick) {
this.props.children.props.onClick(event);
}
_rrtrLibLink2['default'].prototype.handleClick.call(this, event);
}
}, {
key: 'render',
value: function render() {
var router = this.context.router;
var _props = this.props;
var onlyActiveOnIndex = _props.onlyActiveOnIndex;
var to = _props.to;
var children = _props.children;
var props = _objectWithoutProperties(_props, ['onlyActiveOnIndex', 'to', 'children']);
props.onClick = this.onClick;
// Ignore if rendered outside Router context; simplifies unit testing.
if (router) {
props.href = router.createHref(to);
if (props.active == null) {
props.active = router.isActive(to, onlyActiveOnIndex);
}
}
return _react2['default'].cloneElement(_react2['default'].Children.only(children), props);
}
}]);
return LinkContainer;
})(_react2['default'].Component);
exports['default'] = LinkContainer;
LinkContainer.propTypes = {
onlyActiveOnIndex: _react2['default'].PropTypes.bool.isRequired,
to: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.object]).isRequired,
onClick: _react2['default'].PropTypes.func,
active: _react2['default'].PropTypes.bool,
disabled: _react2['default'].PropTypes.bool.isRequired,
children: _react2['default'].PropTypes.node.isRequired
};
LinkContainer.contextTypes = {
router: _react2['default'].PropTypes.object
};
LinkContainer.defaultProps = {
onlyActiveOnIndex: false,
disabled: false
};
module.exports = exports['default'];
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _routerWarning = __webpack_require__(5);
var _routerWarning2 = _interopRequireDefault(_routerWarning);
var _React$PropTypes = _react2['default'].PropTypes;
var bool = _React$PropTypes.bool;
var object = _React$PropTypes.object;
var string = _React$PropTypes.string;
var func = _React$PropTypes.func;
var oneOfType = _React$PropTypes.oneOfType;
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
// TODO: De-duplicate against hasAnyProperties in createTransitionManager.
function isEmptyObject(object) {
for (var p in object) {
if (Object.prototype.hasOwnProperty.call(object, p)) return false;
}return true;
}
function createLocationDescriptor(to, _ref) {
var query = _ref.query;
var hash = _ref.hash;
var state = _ref.state;
if (query || hash || state) {
return { pathname: to, query: query, hash: hash, state: state };
}
return to;
}
/**
* A <Link> is used to create an <a> element that links to a route.
* When that route is active, the link gets the value of its
* activeClassName prop.
*
* For example, assuming you have the following route:
*
* <Route path="/posts/:postID" component={Post} />
*
* You could use the following component to link to that route:
*
* <Link to={`/posts/${post.id}`} />
*
* Links may pass along location state and/or query string parameters
* in the state/query props, respectively.
*
* <Link ... query={{ show: true }} state={{ the: 'state' }} />
*/
var Link = _react2['default'].createClass({
displayName: 'Link',
contextTypes: {
router: object
},
propTypes: {
to: oneOfType([string, object]).isRequired,
query: object,
hash: string,
state: object,
activeStyle: object,
activeClassName: string,
onlyActiveOnIndex: bool.isRequired,
onClick: func
},
getDefaultProps: function getDefaultProps() {
return {
onlyActiveOnIndex: false,
className: '',
style: {}
};
},
handleClick: function handleClick(event) {
var allowTransition = true;
if (this.props.onClick) this.props.onClick(event);
if (isModifiedEvent(event) || !isLeftClickEvent(event)) return;
if (event.defaultPrevented === true) allowTransition = false;
// If target prop is set (e.g. to "_blank") let browser handle link.
/* istanbul ignore if: untestable with Karma */
if (this.props.target) {
if (!allowTransition) event.preventDefault();
return;
}
event.preventDefault();
if (allowTransition) {
var _props = this.props;
var to = _props.to;
var query = _props.query;
var hash = _props.hash;
var state = _props.state;
var _location = createLocationDescriptor(to, { query: query, hash: hash, state: state });
this.context.router.push(_location);
}
},
render: function render() {
var _props2 = this.props;
var to = _props2.to;
var query = _props2.query;
var hash = _props2.hash;
var state = _props2.state;
var activeClassName = _props2.activeClassName;
var activeStyle = _props2.activeStyle;
var onlyActiveOnIndex = _props2.onlyActiveOnIndex;
var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']);
true ? _routerWarning2['default'](!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : undefined;
// Ignore if rendered outside the context of router, simplifies unit testing.
var router = this.context.router;
if (router) {
var _location2 = createLocationDescriptor(to, { query: query, hash: hash, state: state });
props.href = router.createHref(_location2);
if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) {
if (router.isActive(_location2, onlyActiveOnIndex)) {
if (activeClassName) props.className += props.className === '' ? activeClassName : ' ' + activeClassName;
if (activeStyle) props.style = _extends({}, props.style, activeStyle);
}
}
}
return _react2['default'].createElement('a', _extends({}, props, { onClick: this.handleClick }));
}
});
exports['default'] = Link;
module.exports = exports['default'];
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = routerWarning;
exports._resetWarned = _resetWarned;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _warning = __webpack_require__(6);
var _warning2 = _interopRequireDefault(_warning);
var warned = {};
function routerWarning(falseToWarn, message) {
// Only issue deprecation warnings once.
if (message.indexOf('deprecated') !== -1) {
if (warned[message]) {
return;
}
warned[message] = true;
}
message = '[react-router] ' + message;
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
true ? _warning2['default'].apply(undefined, [falseToWarn, message].concat(args)) : undefined;
}
function _resetWarned() {
warned = {};
}
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
/**
* 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 = function() {};
if (true) {
warning = function(condition, format, args) {
var len = arguments.length;
args = new Array(len > 2 ? len - 2 : 0);
for (var key = 2; key < len; key++) {
args[key - 2] = arguments[key];
}
if (format === undefined) {
throw new Error(
'`warning(condition, format, ...args)` requires a warning ' +
'message argument'
);
}
if (format.length < 10 || (/^[s\W]*$/).test(format)) {
throw new Error(
'The warning format should be able to uniquely identify this ' +
'warning. Please, use a more descriptive format than: ' + format
);
}
if (!condition) {
var argIndex = 0;
var message = 'Warning: ' +
format.replace(/%s/g, function() {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch(x) {}
}
};
}
module.exports = warning;
/***/ }
/******/ ])
});
; |
src/svg-icons/action/account-balance-wallet.js | xmityaz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAccountBalanceWallet = (props) => (
<SvgIcon {...props}>
<path d="M21 18v1c0 1.1-.9 2-2 2H5c-1.11 0-2-.9-2-2V5c0-1.1.89-2 2-2h14c1.1 0 2 .9 2 2v1h-9c-1.11 0-2 .9-2 2v8c0 1.1.89 2 2 2h9zm-9-2h10V8H12v8zm4-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>
);
ActionAccountBalanceWallet = pure(ActionAccountBalanceWallet);
ActionAccountBalanceWallet.displayName = 'ActionAccountBalanceWallet';
ActionAccountBalanceWallet.muiName = 'SvgIcon';
export default ActionAccountBalanceWallet;
|
ajax/libs/backbone.radio/0.4.1/backbone.radio.min.js | menuka94/cdnjs | // Backbone.Radio v0.4.0
!function(a,b){if("function"==typeof define&&define.amd)define(["backbone","underscore"],function(a,c){return b(a,c)});else if("undefined"!=typeof exports){var c=require("backbone"),d=require("underscore");module.exports=b(c,d)}else b(a.Backbone,a._)}(this,function(a,b){"use strict";function c(a){return h[a]||(h[a]=b.partial(f.log,a))}function d(a){return b.isFunction(a)?a:b.constant(a)}var e=a.Radio,f=a.Radio={};f.VERSION="0.4.0",f.noConflict=function(){return a.Radio=e,this};var g=Array.prototype.slice;b.extend(f,{_channels:{},DEBUG:!1,channel:function(a){if(!a)throw new Error("You must provide a name for the channel.");return f._getChannel(a)},_getChannel:function(a){var b=f._channels[a];return b||(b=new f.Channel(a),f._channels[a]=b),b}});var h={};b.extend(f,{log:function(a,b){var c=g.call(arguments,2);console.log("["+a+'] "'+b+'"',c)},tuneIn:function(a){var b=f.channel(a);return b._tunedIn=!0,b.on("all",c(a)),this},tuneOut:function(a){var b=f.channel(a);return b._tunedIn=!1,b.off("all",c(a)),delete h[a],this}}),f.Commands={command:function(a){var b=g.call(arguments,1),c=this._channelName;if(c&&this._tunedIn&&f.log.apply(this,[c,a].concat(b)),this._commands&&this._commands[a]){var d=this._commands[a];d.callback.apply(d.context,b)}else if(f.DEBUG){var e=c?" on the "+c+" channel":"";console.warn("An unhandled event was fired"+e+': "'+a+'"')}return this},react:function(a,b,c){return this._commands||(this._commands={}),this._commands[a]={callback:b,context:c||this},this},reactOnce:function(a,c,d){var e=this,f=b.once(function(){return e.stopReacting(a),c.apply(this,arguments)});return this.react(a,f,d)},stopReacting:function(a){var b=this._commands;if(a){if(b&&b[a])delete b[a];else if(f.DEBUG){var c=this._channelName,d=c?" on the "+c+" channel.":"";console.warn('Attempted to remove the unregistered command "'+a+'"'+d)}}else delete this._commands;return this}},f.Requests={request:function(a){var b=g.call(arguments,1),c=this._channelName;if(c&&this._tunedIn&&f.log.apply(this,[c,a].concat(b)),this._requests&&this._requests[a]){var d=this._requests[a];return d.callback.apply(d.context,b)}if(f.DEBUG){var e=c?" on the "+c+" channel":"";console.warn("An unhandled event was fired"+e+': "'+a+'"')}},reply:function(a,b,c){return this._requests||(this._requests={}),this._requests[a]={callback:d(b),context:c||this},this},replyOnce:function(a,c,e){var f=this,g=b.once(function(){return f.stopReplying(a),d(c).apply(this,arguments)});return this.reply(a,g,e)},stopReplying:function(a){var b=this._requests;if(a){if(b&&b[a])delete b[a];else if(f.DEBUG){var c=this._channelName,d=c?" on the "+c+" channel.":"";console.warn('Attempted to remove the unregistered request "'+a+'"'+d)}}else delete this._requests;return this}},f.Channel=function(c){this._channelName=c,b.extend(this,a.Events,f.Commands,f.Requests)},b.extend(f.Channel.prototype,{reset:function(){return this.off(),this.stopListening(),this.stopReacting(),this.stopReplying(),this},connectEvents:function(a,b){return this._connect("on",a,b)},connectCommands:function(a,b){return this._connect("react",a,b)},connectRequests:function(a,b){return this._connect("reply",a,b)},_connect:function(a,c,d){return c?(b.each(c,function(b,c){this[a](c,b,d||this)},this),this):void 0}});var i,j,k=[a.Events,f.Commands,f.Requests];return b.each(k,function(a){b.each(a,function(a,b){f[b]=function(a){return j=g.call(arguments,2),i=this.channel(a),i[b].apply(i,j)}})}),f});
//# sourceMappingURL=backbone.radio.min.map |
app/containers/Upload/index.js | mhoffman/CatAppBrowser | /*
*
* Upload
*
*/
import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import Script from 'react-load-script';
import { connect } from 'react-redux';
import FileDrop from 'react-file-drop';
import GeometryCanvasWithOptions from 'components/GeometryCanvasWithOptions';
import { withStyles } from 'material-ui/styles';
import Paper from 'material-ui/Paper';
import Popover from 'material-ui/Popover';
import Button from 'material-ui/Button';
import TextField from 'material-ui/TextField';
import Grid from 'material-ui/Grid';
import {
MdRefresh,
MdThumbUp,
MdChevronRight,
MdPublic,
MdDelete,
MdWarning,
} from 'react-icons/lib/md';
import Modal from 'material-ui/Modal';
import { CircularProgress } from 'material-ui/Progress';
import IFrame from 'react-iframe';
import ReactGA from 'react-ga';
import { createStructuredSelector } from 'reselect';
import axios from 'axios';
/* import { apiRoot, uploadGraphqlRoot } from 'utils/constants'; */
/* import { apiRoot } from 'utils/constants'; */
import * as snackbarActions from 'containers/AppSnackBar/actions';
import PublicationView from 'components/PublicationView';
import { prettyPrintReference } from 'utils/functions';
import { apiRoot } from 'utils/constants';
import { styles } from './styles';
import makeSelectUpload from './selectors';
/* const apiRoot = 'https://catappdatabase2-pr-63.herokuapp.com'; */
/* const apiRoot = 'http://localhost:5000'; */
const backendRoot = `${apiRoot}/apps/upload`;
const url = `${backendRoot}/upload_dataset/`;
const userInfoUrl = `${backendRoot}/user_info`;
const logoutUrl = `${backendRoot}/logout`;
const releaseUrl = `${backendRoot}/release`;
const endorseUrl = `${backendRoot}/endorse`;
const deleteUrl = `${backendRoot}/delete`;
/* const fileDropUrl = `${apiRoot}/apps/catKitDemo/convert_atoms`; */
const fileDropUrl = `${apiRoot}/apps/bulkEnumerator/get_wyckoff_from_structure`;
// TODO: COMMENT OUT IN PRODUCTION
/* const uploadGraphqlRoot = 'http://localhost:5000/apps/upload/graphql'; */
const uploadGraphqlRoot = `${apiRoot}/apps/upload/graphql`;
const showUploadForm = false;
export class Upload extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props);
this.state = {
uploadError: '',
loginModalOpen: false,
loginUrl: '',
userInfo: {},
datasets: [],
pubId: '',
showHelp: true,
pubEntries: {},
popoverAnchorElement: null,
deleting: false,
molecules: [],
reactions: [{}],
};
this.logout = this.logout.bind(this);
this.fetchUserInfo = this.fetchUserInfo.bind(this);
this.getDatasets = this.getDatasets.bind(this);
this.handleFileDrop = this.handleFileDrop.bind(this);
this.handleSocialLogin = this.handleSocialLogin.bind(this);
this.handleSocialLoginFailure = this.handleSocialLoginFailure.bind(this);
this.handleRelease = this.handleRelease.bind(this);
this.handleEndorse = this.handleEndorse.bind(this);
this.handleDelete = this.handleDelete.bind(this);
this.handlePopoverOpen = this.handlePopoverOpen.bind(this);
this.handlePopoverClose = this.handlePopoverClose.bind(this);
this.handleDrop = this.handleDrop.bind(this);
this.login = this.login.bind(this);
this.removeMolecule = this.removeMolecule.bind(this);
this.setDataset = this.setDataset.bind(this);
this.toggleHelp = this.toggleHelp.bind(this);
this.windowLogin = this.windowLogin.bind(this);
this.moleculeInput = null;
this.reactantInput = null;
this.productInput = null;
}
componentDidMount() {
if (_.get(this.props, 'location.query.login') === 'success') {
this.fetchUserInfo();
this.getDatasets();
}
}
componentWillReceiveProps(nextProps) {
if (_.get(nextProps, 'location.query.login') === 'success') {
this.fetchUserInfo();
this.getDatasets();
}
}
getDatasets() {
const datasetQuery = `{publications { totalCount edges { node {
title authors doi pubId journal volume pages year
} } }}`;
axios.default.withCredentials = true;
axios.post(uploadGraphqlRoot, {}, {
method: 'POST',
data: {
query: datasetQuery,
},
withCredentials: true,
}).then((response) => {
this.setState({
datasets: response.data.data.publications.edges.map(
(edge) => edge.node
),
});
});
const pubEntryQuery = `{reactions(username:"~", distinct: true) {
edges { node { pubId username } } }}`;
axios({
url: uploadGraphqlRoot,
method: 'POST',
data: {
query: pubEntryQuery,
},
withCredentials: true,
}).then((response) => {
const pubEntries = _.groupBy(response.data.data.reactions.edges.map((x) => x.node),
'pubId');
this.setState({
pubEntries,
});
});
}
setDataset(dataset) {
this.setState({
pubId: dataset.pubId,
});
}
removeMolecule(i) {
let molecules = this.state;
molecules = molecules.filter((elem, x) => x !== i);
this.setState({
molecules,
});
}
handleDrop(field) {
return (files, event) => {
/* console.log(event.toElement.innerText) */
const formData = new FormData();
formData.append('file', files[0]);
formData.append('field', field);
formData.append('event', JSON.stringify(event));
axios.post(fileDropUrl, formData,
{
headers:
{
'content-type': 'multipart/form-data',
},
}).then((response) => {
let { molecules } = this.state;
molecules = _.concat(molecules, [response.data.cif]);
this.setState({
molecules,
});
});
};
}
handlePopoverOpen(event) {
this.setState({
popoverAnchorElement: event.currentTarget,
});
}
handlePopoverClose() {
this.setState({
popoverAnchorElement: null,
});
}
handleEndorse(dataset) {
ReactGA.event({
category: 'Endorse',
action: 'Endorse a Dataset',
label: ` endorse ${dataset.pubId}`,
});
const correspondentQuery = `{reactions(first: 1, pubId: "${dataset.pubId}") {
edges {
node {
id
username
}
}
}}`;
axios.post(uploadGraphqlRoot, {}, {
method: 'POST',
data: {
query: correspondentQuery,
},
withCredentials: true,
}).then((response) => {
axios.post(endorseUrl, {
dataset,
userInfo: this.state.userInfo,
corresponding_email: response.data.data.reactions.edges[0].node.username,
}).then((messageResponse) => {
this.props.openSnackbar(messageResponse.data.message);
});
});
}
handleRelease(dataset) {
ReactGA.event({
category: 'Upload',
action: 'upload a dataset',
label: ` uploaded ${dataset.pubId}`,
});
const correspondentQuery = `{reactions(first: 1, pubId: "${dataset.pubId}") {
edges {
node {
id
username
}
}
}}`;
axios.post(uploadGraphqlRoot, {}, {
method: 'POST',
data: {
query: correspondentQuery,
},
withCredentials: true,
}).then((response) => {
axios.post(releaseUrl, {
dataset,
userInfo: this.state.userInfo,
corresponding_email: response.data.data.reactions.edges[0].node.username,
}).then((messageResponse) => {
this.props.openSnackbar(messageResponse.data.message);
});
});
}
handleDelete(dataset) {
// TODO: Implement confirmation dialogue
const correspondentQuery = `{reactions(first: 1, pubId: "${dataset.pubId}") {
edges {
node {
id
username
}
}
}}`;
this.setState({
deleting: true,
});
axios.post(uploadGraphqlRoot, {}, {
method: 'POST',
data: {
query: correspondentQuery,
},
withCredentials: true,
}).then((response) => {
axios.post(deleteUrl, {
dataset,
userInfo: this.state.userInfo,
corresponding_email: response.data.data.reactions.edges[0].node.username,
}).then((messageResponse) => {
this.props.openSnackbar(messageResponse.data.message);
this.getDatasets();
this.setState({
deleting: false,
});
});
});
}
handleSocialLogin() {
}
handleSocialLoginFailure() {
}
fetchUserInfo() {
axios.get(userInfoUrl, {
data: {},
withCredentials: true,
}).then((response) => {
this.setState({
userInfo: response.data,
});
});
}
login() {
const uploadUrl = `${apiRoot}/apps/upload/submit`;
axios.get(uploadUrl).then((response) => {
this.setState({
loginModalOpen: true,
loginUrl: response.data.location,
});
});
}
logout() {
axios(logoutUrl, {
method: 'post',
data: {},
withCredentials: true,
}).then(() => {
this.setState({
userInfo: {},
datasets: [],
pubId: '',
});
});
}
windowLogin(provider = 'slack') {
const uploadUrl = `${apiRoot}/apps/upload/`;
ReactGA.event({
category: 'Login',
action: 'User Login',
label: ` login with ${provider}`,
});
axios(uploadUrl, {
method: 'get',
params: {
provider,
},
mode: 'no-cors',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
withCredentials: true,
credentials: 'same-origin',
}).then((response) => {
window.open(response.data.location);
window.focus();
window.close();
});
}
handleClose() {
this.setState({
loginModalOpen: false,
});
}
handleFileDrop(files) {
const formData = new FormData();
formData.append('file', files[0]);
axios.post(url, formData, { headers: { 'content-type': 'multipart/form-data' } }).then((response) => response);
}
toggleHelp() {
this.setState({
showHelp: !this.state.showHelp,
});
}
render() {
return (
<div>
<Script url="https://code.jquery.com/jquery-3.2.1.min.js" />
<Script url="/static/ChemDoodleWeb.js" />
<Modal
aria-labelledby="simple-modal-title"
aria-describedby="simple-modal-description"
open={this.state.loginModalOpen}
onClose={() => { this.handleClose(); }}
style={{
backgroundColor: 'white',
}}
>
<IFrame
url={this.state.loginUrl}
width="95vw"
height="95vh"
position="relative"
top="50px"
display="initial"
/>
</Modal>
<Grid container direction="row" justify="space-between">
<Grid item>
<h2>
Upload Datasets
{!_.isEmpty(this.state.userInfo)
? `\u00A0\u00A0(${this.state.userInfo.email})`
: null}
</h2>
</Grid>
<Grid item>
{_.isEmpty(this.state.userInfo) ? null
: (
<img
src={this.state.userInfo.picture}
height="72"
width="72"
alt="Portrait"
/>
)
}
</Grid>
</Grid>
<Paper className={this.props.classes.paper}>
{!_.isEmpty(this.state.userInfo) ? null
: (
<Grid container direction="row" justify="flex-end">
<Grid item>
<Button
raised
onClick={() => { this.toggleHelp(); }}
>
{this.state.showHelp ? 'Hide Help' : 'Show Help' }
</Button>
</Grid>
<Grid item>
<Button
raised
color="primary"
onClick={(event) => {
this.handlePopoverOpen(event);
}}
>
Login
</Button>
<Popover
open={Boolean(this.state.popoverAnchorElement)}
anchorEl={this.state.popoverAnchorElement}
onClose={this.handlePopoverClose}
origin={{
vertical: 'bottom',
horizontal: 'left',
}}
transformOrigin={{
vertical: 'bottom',
horizontal: 'right',
}}
>
<div
className={this.props.classes.loginPopover}
>
<Button
onClick={() => this.windowLogin('google')}
>
{' '}
Google
{' '}
</Button>
<Button
onClick={() => this.windowLogin('slack')}
>
{' '}
Slack
{' '}
</Button>
</div>
</Popover>
</Grid>
</Grid>
)
}
{_.isEmpty(this.state.userInfo) ? null
: (
<Grid container direction="row" justify="space-between">
<Grid item>
<Button
raised
onClick={() => { this.toggleHelp(); }}
>
{this.state.showHelp ? 'Hide Help' : 'Show Help' }
</Button>
</Grid>
<Grid item>
<Button
onClick={() => this.logout()}
>
Logout
</Button>
</Grid>
</Grid>
)
}
{_.isEmpty(this.state.uploadError) ? null
: <div className={this.props.classes.error}>{this.state.uploadError}</div>
}
</Paper>
{!this.state.showHelp ? null
: (
<Paper className={this.props.classes.paper}>
<div style={{ width: '62%', textAlign: 'justify', lineHeight: '24px' }}>
<MdWarning />
{' '}
Disclaimer: data submitted to the preview section can be seen by all registered users
of catalysis-hub.org.
<h3>Why should I submit calculations of reaction energies?</h3>
<ul>
<li>
Create an easy-to-use interactive supplementary information for your
{' '}
<a href="/publications">publication</a>
{' '}
with its own URL.
</li>
<li>
Get your own
{' '}
<a href="/profile">profile page</a>
</li>
<li>
Accelerate transfer of your theoretical insight to experimentalists in the field.
</li>
<li>
Support
{' '}
<a href="/catLearn">ongoing machine-learning efforts</a>
in the community by providing first-principles based training data.
</li>
<li>
Get your dataset referenced in
{' '}
<a target="_blank" href="https://toolbox.google.com/datasetsearch/search?query=catalysis%20hub&docid=NNswoG6o3ztB5JwUAAAAAA%3D%3D">{'Google\'s Dataset Search'}</a>
.
</li>
</ul>
<h3>How to submit with the CatHub terminal client</h3>
<div>
Check
{' '}
<a target="_blank" href="http://docs.catalysis-hub.org/en/latest/tutorials/upload.html#suncat-group-members">docs.catalysis-hub.org</a>
{' '}
for a detailed guide on how to upload data. Below a short guide is provided. If you have problems, please contact Kirsten Winther (
{'[email protected]'}
) or use the
{' '}
<a href="https://gitter.im/catalysis-hub-org/Lobby#"> Chat room </a>
{' '}
for assistance.
</div>
<ol>
<li>
Install CatHub:
<pre style={{ margin: '8px' }}>pip install cathub --upgrade --user </pre>
</li>
<li>
For an overview of commands, run in your terminal:
<pre style={{ margin: '8px' }}>cathub --help </pre>
<pre style={{ margin: '8px' }}>cathub make_folders --help </pre>
<pre style={{ margin: '8px' }}>cathub organize --help </pre>
</li>
<li>
Organize your DFT output files into a folder tree. Choose one of two options:
<ul>
<li>
For automated organization of folders and files (adsorption energies only):
<pre style={{ margin: '8px' }}>
{' '}
cathub organize
{'<foldername>'}
{' '}
-a
{'<adsorbate1,adsorbate2>'}
{' '}
</pre>
<pre style={{ margin: '8px' }}>
{' '}
-c
{'<dft-code>'}
{' '}
-x
{'<xc-functional>'}
{' '}
-f
{'<facet>'}
{' '}
</pre>
</li>
<li>
For more complicated reactions, create an empty folder tree and dump the files yourself:
<pre style={{ margin: '8px' }}>
{' '}
cathub make_folders
{'<template>'}
</pre>
</li>
</ul>
</li>
<li>
Turn organized folder into a database file (SQLite3 format):
<pre>
cathub folder2db
{' '}
{'<organized folder>'}
</pre>
</li>
<li>
Upload the database file to the server:
<pre>
cathub db2server
{'<NameTitlewordYear>'}
.db
</pre>
</li>
<li>
Go to www.catalysis-hub.org/upload and login with the email you provided together with your files.
</li>
<li>
Click on
{' '}
{'"Fetch Data Sets"'}
{' '}
to see your uploaded dataset.
</li>
<li>
Check that the data looks right. Click on
{' '}
{'"Release"'}
, and the dataset will be made available to the public as soon as possible.
</li>
</ol>
</div>
</Paper>
)
}
{!showUploadForm ? null
: (
<Paper className={this.props.classes.paper}>
<h1>Manual Upload</h1>
<TextField
className={this.props.classes.textField}
id="title"
label="Title *"
InputLabelProps={{
shrink: true,
}}
placeholder="Highly Efficient Catalyst from Non-Toxic Earth Abundant Materials for XY"
fullWidth
margin="normal"
/>
<TextField
className={this.props.classes.textField}
id="authors"
label="Authors *"
InputLabelProps={{
shrink: true,
}}
placeholder="A Einstein"
fullWidth
margin="normal"
/>
<TextField
className={this.props.classes.textField}
label="Volume"
InputLabelProps={{
shrink: true,
}}
placeholder="8"
margin="normal"
/>
<TextField
className={this.props.classes.textField}
label="Number"
InputLabelProps={{
shrink: true,
}}
placeholder="13"
margin="normal"
/>
<TextField
className={this.props.classes.textField}
label="Pages"
InputLabelProps={{
shrink: true,
}}
placeholder="2140-2267"
margin="normal"
/>
<TextField
className={this.props.classes.textField}
label="Year *"
InputLabelProps={{
shrink: true,
}}
placeholder="2018"
margin="normal"
/>
<TextField
className={this.props.classes.textField}
label="Publisher"
InputLabelProps={{
shrink: true,
}}
placeholder="Wiley"
margin="normal"
/>
<TextField
className={this.props.classes.textField}
label="DOI"
InputLabelProps={{
shrink: true,
}}
placeholder="10.1002/cssc.201500322"
margin="normal"
/>
<TextField
className={this.props.classes.textField}
label="DFT Code"
InputLabelProps={{
shrink: true,
}}
placeholder="Quantum Espresso"
margin="normal"
/>
<TextField
className={this.props.classes.textField}
label="DFT Functional(s)"
InputLabelProps={{
shrink: true,
}}
placeholder="BEEF-vdW"
margin="normal"
/>
<h2>Gas Phase Molecules</h2>
<div>
<input
accept="text/*"
id="molecule-upload-button"
ref={(el) => { this.moleculeInput = el; }}
type="file"
className={this.props.classes.input}
multiple
/>
<label
htmlFor="molecule-upload-button"
>
<Button
raised
type="file"
className={this.props.classes.button}
component="span"
>
+ Molecule
{/* frame={this.moleculeInput} */}
<FileDrop
onDrop={this.handleDrop('molecule')}
dropEffect="copy"
>
(Drop)
</FileDrop>
</Button>
</label>
</div>
<div>
<Grid container direction="row" justify="flex-start">
{this.state.molecules.map((molecule, i) => (
<Grid
item
key={`ml_${i}`}
>
<Grid container direction="column" justify="flex-start">
<Grid item>
<GeometryCanvasWithOptions
key={`mc_${i}`}
cifdata={molecule}
unique_id={`molecule_${i}`}
id={`molecule_${i}`}
height={400}
width={400}
showButtons={false}
x={1}
y={1}
z={2}
/>
</Grid>
<Grid>
<Grid container direction="row" justify="flex-start">
<Grid item>
<Button
onClick={() => { this.removeMolecule(i); }}
raised
>
<MdDelete />
{' '}
Remove
</Button>
</Grid>
</Grid>
</Grid>
</Grid>
</Grid>
))}
</Grid>
</div>
<h2>Reactions</h2>
<Grid container direction="column" justify="flex-start">
{this.state.reactions.map((reaction, i) => (
<Grid item key={`reaction_${i}`}>
<h3>
Reaction
{i + 1}
</h3>
</Grid>
))}
</Grid>
<div>
<input
accept="text/*"
ref={(el) => { this.reactantInput = el; }}
id="reactants-upload-button"
type="file"
className={this.props.classes.input}
multiple
/>
<label
htmlFor="reactants-upload-button"
>
<Button
raised
component="span"
className={this.props.classes.button}
>
+ Reactant
{/* frame={this.reactantInput} */}
<FileDrop
onDrop={this.handleDrop('molecule')}
dropEffect="copy"
>
(Drop)
</FileDrop>
</Button>
</label>
<input
accept="text/*"
id="products-upload-button"
type="file"
className={this.props.classes.input}
ref={(el) => { this.productInput = el; }}
multiple
/>
<label
htmlFor="products-upload-button"
>
<Button
raised
component="span"
className={this.props.classes.button}
>
+ Product
{/* frame={this.productInput} */}
<FileDrop
onDrop={this.handleDrop('molecule')}
dropEffect="copy"
>
(Drop)
</FileDrop>
</Button>
</label>
</div>
</Paper>
)
}
{_.isEmpty(this.state.userInfo) ? null
: (
<Paper className={this.props.classes.paper}>
<Grid container justify="space-between" direction="row">
<Grid item>
<h1>Data Sets</h1>
</Grid>
<Grid item>
<Button
raised
color="primary"
onClick={() => { this.getDatasets(); }}
>
<MdRefresh />
{' '}
Fetch Data Sets
</Button>
</Grid>
</Grid>
{_.isEmpty(this.state.datasets) ? null
: this.state.datasets.map((dataset, i) => (
<Paper key={`ds_${i}`} className={this.props.classes.paper}>
{prettyPrintReference(dataset)}
{(this.state.userInfo.email !== _.get(this.state.pubEntries,
`${dataset.pubId}.0.username`, '') && _.get(this.state.pubEntries,
`${dataset.pubId}.0.username`, '') !== 'anonymous')
? (
<div>
<Button
raised
onClick={() => {
this.handleEndorse(dataset);
}}
>
Endorse
{' '}
{'\u00A0\u00A0'}
{' '}
<MdThumbUp />
</Button>
{' '}
{'\u00A0\u00A0'}
</div>
)
: (
<div>
<Button
raised
onClick={() => {
this.handleRelease(dataset);
}}
>
Release
{' '}
{'\u00A0\u00A0'}
{' '}
<MdPublic />
</Button>
{'\u00A0\u00A0\u00A0'}
<div>
{JSON.stringify(this.state.userInfo)}
</div>
<div>
{_.get(this.state.pubEntries, `${dataset.pubId}.0.username`, '')}
</div>
<Button
raised
onClick={() => {
this.handleDelete(dataset);
}}
>
Delete
{' '}
{'\u00A0\u00A0'}
{' '}
<MdDelete />
{ this.state.deleting ? <CircularProgress size={16} /> : null }
</Button>
{'\u00A0\u00A0\u00A0'}
<Button
raised
onClick={() => { this.setDataset(dataset); }}
>
{' '}
Details
<MdChevronRight />
</Button>
</div>
)
}
</Paper>
))
}
</Paper>
)
}
{_.isEmpty(this.state.pubId) ? null
: (
<Paper>
<PublicationView
preview
pubId={this.state.pubId}
graphqlRoot={uploadGraphqlRoot}
privilegedAccess
/>
</Paper>
)
}
</div>
);
}
}
Upload.propTypes = {
classes: PropTypes.object,
openSnackbar: PropTypes.func,
};
const mapStateToProps = createStructuredSelector({
Upload: makeSelectUpload(),
});
const mapDispatchToProps = (dispatch) => ({
openSnackbar: (message) => {
dispatch(snackbarActions.open(message));
},
});
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles, { withTheme: true })(Upload));
|
ajax/libs/yui/3.14.1/datatable-body/datatable-body-coverage.js | stefanocudini/cdnjs | if (typeof __coverage__ === 'undefined') { __coverage__ = {}; }
if (!__coverage__['build/datatable-body/datatable-body.js']) {
__coverage__['build/datatable-body/datatable-body.js'] = {"path":"build/datatable-body/datatable-body.js","s":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0,"80":0,"81":0,"82":0,"83":0,"84":0,"85":0,"86":0,"87":0,"88":0,"89":0,"90":0,"91":0,"92":0,"93":0,"94":0,"95":0,"96":0,"97":0,"98":0,"99":0,"100":0,"101":0,"102":0,"103":0,"104":0,"105":0,"106":0,"107":0,"108":0,"109":0,"110":0,"111":0,"112":0,"113":0,"114":0,"115":0,"116":0,"117":0,"118":0,"119":0,"120":0,"121":0,"122":0,"123":0,"124":0,"125":0,"126":0,"127":0,"128":0,"129":0,"130":0,"131":0,"132":0,"133":0,"134":0,"135":0,"136":0,"137":0,"138":0,"139":0,"140":0,"141":0,"142":0,"143":0,"144":0,"145":0,"146":0,"147":0,"148":0,"149":0,"150":0,"151":0,"152":0,"153":0,"154":0,"155":0,"156":0,"157":0,"158":0,"159":0,"160":0,"161":0,"162":0,"163":0,"164":0,"165":0,"166":0,"167":0,"168":0,"169":0,"170":0,"171":0,"172":0,"173":0,"174":0,"175":0,"176":0,"177":0,"178":0,"179":0,"180":0,"181":0,"182":0,"183":0,"184":0,"185":0,"186":0,"187":0,"188":0,"189":0,"190":0,"191":0,"192":0,"193":0,"194":0,"195":0,"196":0,"197":0,"198":0,"199":0,"200":0,"201":0,"202":0,"203":0,"204":0,"205":0,"206":0,"207":0,"208":0,"209":0,"210":0,"211":0,"212":0,"213":0,"214":0,"215":0,"216":0,"217":0,"218":0,"219":0,"220":0,"221":0,"222":0,"223":0,"224":0,"225":0,"226":0,"227":0,"228":0,"229":0,"230":0,"231":0,"232":0,"233":0,"234":0,"235":0},"b":{"1":[0,0],"2":[0,0],"3":[0,0],"4":[0,0],"5":[0,0],"6":[0,0],"7":[0,0],"8":[0,0],"9":[0,0,0,0],"10":[0,0],"11":[0,0],"12":[0,0],"13":[0,0],"14":[0,0],"15":[0,0],"16":[0,0],"17":[0,0],"18":[0,0],"19":[0,0],"20":[0,0],"21":[0,0],"22":[0,0],"23":[0,0],"24":[0,0],"25":[0,0],"26":[0,0],"27":[0,0],"28":[0,0],"29":[0,0],"30":[0,0],"31":[0,0],"32":[0,0],"33":[0,0],"34":[0,0],"35":[0,0],"36":[0,0],"37":[0,0],"38":[0,0],"39":[0,0],"40":[0,0],"41":[0,0,0],"42":[0,0],"43":[0,0,0],"44":[0,0],"45":[0,0],"46":[0,0],"47":[0,0],"48":[0,0],"49":[0,0],"50":[0,0],"51":[0,0],"52":[0,0],"53":[0,0,0,0],"54":[0,0],"55":[0,0],"56":[0,0],"57":[0,0],"58":[0,0,0,0],"59":[0,0],"60":[0,0],"61":[0,0],"62":[0,0],"63":[0,0],"64":[0,0],"65":[0,0],"66":[0,0],"67":[0,0],"68":[0,0],"69":[0,0],"70":[0,0],"71":[0,0],"72":[0,0],"73":[0,0],"74":[0,0],"75":[0,0],"76":[0,0],"77":[0,0],"78":[0,0],"79":[0,0],"80":[0,0],"81":[0,0],"82":[0,0],"83":[0,0,0],"84":[0,0],"85":[0,0],"86":[0,0],"87":[0,0],"88":[0,0],"89":[0,0],"90":[0,0],"91":[0,0],"92":[0,0],"93":[0,0],"94":[0,0],"95":[0,0],"96":[0,0],"97":[0,0],"98":[0,0],"99":[0,0],"100":[0,0],"101":[0,0],"102":[0,0]},"f":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0},"fnMap":{"1":{"name":"(anonymous_1)","line":1,"loc":{"start":{"line":1,"column":26},"end":{"line":1,"column":45}}},"2":{"name":"(anonymous_2)","line":214,"loc":{"start":{"line":214,"column":13},"end":{"line":214,"column":36}}},"3":{"name":"(anonymous_3)","line":267,"loc":{"start":{"line":267,"column":18},"end":{"line":267,"column":30}}},"4":{"name":"(anonymous_4)","line":292,"loc":{"start":{"line":292,"column":15},"end":{"line":292,"column":31}}},"5":{"name":"(anonymous_5)","line":304,"loc":{"start":{"line":304,"column":36},"end":{"line":304,"column":52}}},"6":{"name":"(anonymous_6)","line":326,"loc":{"start":{"line":326,"column":12},"end":{"line":326,"column":26}}},"7":{"name":"(anonymous_7)","line":433,"loc":{"start":{"line":433,"column":12},"end":{"line":433,"column":24}}},"8":{"name":"(anonymous_8)","line":469,"loc":{"start":{"line":469,"column":16},"end":{"line":469,"column":47}}},"9":{"name":"(anonymous_9)","line":500,"loc":{"start":{"line":500,"column":17},"end":{"line":500,"column":45}}},"10":{"name":"(anonymous_10)","line":581,"loc":{"start":{"line":581,"column":15},"end":{"line":581,"column":31}}},"11":{"name":"(anonymous_11)","line":595,"loc":{"start":{"line":595,"column":34},"end":{"line":595,"column":50}}},"12":{"name":"(anonymous_12)","line":621,"loc":{"start":{"line":621,"column":25},"end":{"line":621,"column":37}}},"13":{"name":"(anonymous_13)","line":635,"loc":{"start":{"line":635,"column":22},"end":{"line":635,"column":35}}},"14":{"name":"(anonymous_14)","line":707,"loc":{"start":{"line":707,"column":15},"end":{"line":707,"column":32}}},"15":{"name":"(anonymous_15)","line":718,"loc":{"start":{"line":718,"column":34},"end":{"line":718,"column":46}}},"16":{"name":"(anonymous_16)","line":731,"loc":{"start":{"line":731,"column":30},"end":{"line":731,"column":48}}},"17":{"name":"(anonymous_17)","line":756,"loc":{"start":{"line":756,"column":27},"end":{"line":756,"column":39}}},"18":{"name":"(anonymous_18)","line":780,"loc":{"start":{"line":780,"column":26},"end":{"line":780,"column":56}}},"19":{"name":"(anonymous_19)","line":797,"loc":{"start":{"line":797,"column":22},"end":{"line":797,"column":47}}},"20":{"name":"(anonymous_20)","line":844,"loc":{"start":{"line":844,"column":12},"end":{"line":844,"column":24}}},"21":{"name":"(anonymous_21)","line":875,"loc":{"start":{"line":875,"column":21},"end":{"line":875,"column":44}}},"22":{"name":"(anonymous_22)","line":880,"loc":{"start":{"line":880,"column":22},"end":{"line":880,"column":46}}},"23":{"name":"(anonymous_23)","line":923,"loc":{"start":{"line":923,"column":20},"end":{"line":923,"column":57}}},"24":{"name":"(anonymous_24)","line":986,"loc":{"start":{"line":986,"column":18},"end":{"line":986,"column":33}}},"25":{"name":"(anonymous_25)","line":1020,"loc":{"start":{"line":1020,"column":24},"end":{"line":1020,"column":47}}},"26":{"name":"(anonymous_26)","line":1070,"loc":{"start":{"line":1070,"column":28},"end":{"line":1070,"column":51}}},"27":{"name":"(anonymous_27)","line":1101,"loc":{"start":{"line":1101,"column":22},"end":{"line":1101,"column":34}}},"28":{"name":"(anonymous_28)","line":1114,"loc":{"start":{"line":1114,"column":16},"end":{"line":1114,"column":28}}},"29":{"name":"(anonymous_29)","line":1138,"loc":{"start":{"line":1138,"column":15},"end":{"line":1138,"column":35}}},"30":{"name":"(anonymous_30)","line":1164,"loc":{"start":{"line":1164,"column":17},"end":{"line":1164,"column":35}}}},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":1207,"column":78}},"2":{"start":{"line":11,"column":0},"end":{"line":21,"column":40}},"3":{"start":{"line":116,"column":0},"end":{"line":1204,"column":3}},"4":{"start":{"line":215,"column":8},"end":{"line":216,"column":45}},"5":{"start":{"line":218,"column":8},"end":{"line":247,"column":9}},"6":{"start":{"line":219,"column":12},"end":{"line":224,"column":13}},"7":{"start":{"line":220,"column":16},"end":{"line":220,"column":58}},"8":{"start":{"line":221,"column":16},"end":{"line":221,"column":64}},"9":{"start":{"line":222,"column":19},"end":{"line":224,"column":13}},"10":{"start":{"line":223,"column":16},"end":{"line":223,"column":76}},"11":{"start":{"line":226,"column":12},"end":{"line":246,"column":13}},"12":{"start":{"line":227,"column":16},"end":{"line":227,"column":66}},"13":{"start":{"line":228,"column":16},"end":{"line":236,"column":17}},"14":{"start":{"line":230,"column":20},"end":{"line":235,"column":21}},"15":{"start":{"line":231,"column":41},"end":{"line":231,"column":57}},"16":{"start":{"line":231,"column":58},"end":{"line":231,"column":64}},"17":{"start":{"line":232,"column":41},"end":{"line":232,"column":56}},"18":{"start":{"line":232,"column":57},"end":{"line":232,"column":63}},"19":{"start":{"line":233,"column":41},"end":{"line":233,"column":56}},"20":{"start":{"line":233,"column":57},"end":{"line":233,"column":63}},"21":{"start":{"line":234,"column":41},"end":{"line":234,"column":57}},"22":{"start":{"line":234,"column":58},"end":{"line":234,"column":64}},"23":{"start":{"line":238,"column":16},"end":{"line":245,"column":17}},"24":{"start":{"line":239,"column":20},"end":{"line":240,"column":58}},"25":{"start":{"line":241,"column":20},"end":{"line":241,"column":62}},"26":{"start":{"line":243,"column":20},"end":{"line":243,"column":61}},"27":{"start":{"line":244,"column":20},"end":{"line":244,"column":67}},"28":{"start":{"line":249,"column":8},"end":{"line":249,"column":28}},"29":{"start":{"line":268,"column":8},"end":{"line":269,"column":17}},"30":{"start":{"line":271,"column":8},"end":{"line":278,"column":9}},"31":{"start":{"line":272,"column":12},"end":{"line":272,"column":60}},"32":{"start":{"line":274,"column":12},"end":{"line":274,"column":38}},"33":{"start":{"line":275,"column":12},"end":{"line":275,"column":48}},"34":{"start":{"line":276,"column":12},"end":{"line":277,"column":49}},"35":{"start":{"line":293,"column":8},"end":{"line":296,"column":19}},"36":{"start":{"line":298,"column":8},"end":{"line":311,"column":9}},"37":{"start":{"line":299,"column":12},"end":{"line":301,"column":13}},"38":{"start":{"line":300,"column":16},"end":{"line":300,"column":45}},"39":{"start":{"line":303,"column":12},"end":{"line":310,"column":13}},"40":{"start":{"line":304,"column":16},"end":{"line":306,"column":25}},"41":{"start":{"line":305,"column":20},"end":{"line":305,"column":67}},"42":{"start":{"line":308,"column":16},"end":{"line":309,"column":72}},"43":{"start":{"line":313,"column":8},"end":{"line":313,"column":30}},"44":{"start":{"line":327,"column":8},"end":{"line":328,"column":23}},"45":{"start":{"line":330,"column":8},"end":{"line":338,"column":9}},"46":{"start":{"line":331,"column":12},"end":{"line":333,"column":13}},"47":{"start":{"line":332,"column":16},"end":{"line":332,"column":73}},"48":{"start":{"line":335,"column":12},"end":{"line":337,"column":36}},"49":{"start":{"line":340,"column":8},"end":{"line":340,"column":19}},"50":{"start":{"line":434,"column":8},"end":{"line":438,"column":65}},"51":{"start":{"line":441,"column":8},"end":{"line":441,"column":45}},"52":{"start":{"line":443,"column":8},"end":{"line":447,"column":9}},"53":{"start":{"line":444,"column":12},"end":{"line":444,"column":61}},"54":{"start":{"line":446,"column":12},"end":{"line":446,"column":58}},"55":{"start":{"line":449,"column":8},"end":{"line":451,"column":9}},"56":{"start":{"line":450,"column":12},"end":{"line":450,"column":37}},"57":{"start":{"line":453,"column":8},"end":{"line":453,"column":22}},"58":{"start":{"line":455,"column":8},"end":{"line":455,"column":20}},"59":{"start":{"line":470,"column":8},"end":{"line":473,"column":14}},"60":{"start":{"line":475,"column":8},"end":{"line":482,"column":9}},"61":{"start":{"line":476,"column":12},"end":{"line":476,"column":45}},"62":{"start":{"line":478,"column":12},"end":{"line":481,"column":13}},"63":{"start":{"line":479,"column":16},"end":{"line":479,"column":83}},"64":{"start":{"line":480,"column":16},"end":{"line":480,"column":46}},"65":{"start":{"line":484,"column":8},"end":{"line":484,"column":20}},"66":{"start":{"line":501,"column":8},"end":{"line":504,"column":34}},"67":{"start":{"line":506,"column":8},"end":{"line":506,"column":34}},"68":{"start":{"line":508,"column":8},"end":{"line":508,"column":48}},"69":{"start":{"line":509,"column":8},"end":{"line":509,"column":44}},"70":{"start":{"line":512,"column":8},"end":{"line":567,"column":9}},"71":{"start":{"line":513,"column":12},"end":{"line":521,"column":14}},"72":{"start":{"line":523,"column":12},"end":{"line":523,"column":62}},"73":{"start":{"line":525,"column":12},"end":{"line":532,"column":13}},"74":{"start":{"line":531,"column":16},"end":{"line":531,"column":35}},"75":{"start":{"line":534,"column":15},"end":{"line":567,"column":9}},"76":{"start":{"line":535,"column":12},"end":{"line":537,"column":13}},"77":{"start":{"line":536,"column":16},"end":{"line":536,"column":60}},"78":{"start":{"line":539,"column":12},"end":{"line":539,"column":51}},"79":{"start":{"line":541,"column":12},"end":{"line":559,"column":13}},"80":{"start":{"line":542,"column":16},"end":{"line":550,"column":18}},"81":{"start":{"line":553,"column":16},"end":{"line":553,"column":76}},"82":{"start":{"line":556,"column":16},"end":{"line":558,"column":17}},"83":{"start":{"line":557,"column":20},"end":{"line":557,"column":50}},"84":{"start":{"line":561,"column":12},"end":{"line":563,"column":13}},"85":{"start":{"line":562,"column":16},"end":{"line":562,"column":51}},"86":{"start":{"line":566,"column":12},"end":{"line":566,"column":64}},"87":{"start":{"line":569,"column":8},"end":{"line":569,"column":71}},"88":{"start":{"line":571,"column":8},"end":{"line":571,"column":20}},"89":{"start":{"line":582,"column":8},"end":{"line":587,"column":9}},"90":{"start":{"line":584,"column":12},"end":{"line":586,"column":17}},"91":{"start":{"line":589,"column":8},"end":{"line":591,"column":9}},"92":{"start":{"line":590,"column":12},"end":{"line":590,"column":54}},"93":{"start":{"line":592,"column":8},"end":{"line":593,"column":23}},"94":{"start":{"line":595,"column":8},"end":{"line":600,"column":11}},"95":{"start":{"line":596,"column":12},"end":{"line":599,"column":13}},"96":{"start":{"line":597,"column":16},"end":{"line":597,"column":27}},"97":{"start":{"line":598,"column":16},"end":{"line":598,"column":28}},"98":{"start":{"line":602,"column":8},"end":{"line":602,"column":19}},"99":{"start":{"line":622,"column":8},"end":{"line":622,"column":22}},"100":{"start":{"line":636,"column":8},"end":{"line":644,"column":16}},"101":{"start":{"line":646,"column":8},"end":{"line":658,"column":9}},"102":{"start":{"line":647,"column":12},"end":{"line":647,"column":33}},"103":{"start":{"line":653,"column":12},"end":{"line":657,"column":13}},"104":{"start":{"line":654,"column":16},"end":{"line":654,"column":30}},"105":{"start":{"line":655,"column":16},"end":{"line":655,"column":45}},"106":{"start":{"line":656,"column":16},"end":{"line":656,"column":23}},"107":{"start":{"line":661,"column":8},"end":{"line":689,"column":9}},"108":{"start":{"line":663,"column":16},"end":{"line":669,"column":17}},"109":{"start":{"line":664,"column":20},"end":{"line":664,"column":41}},"110":{"start":{"line":665,"column":20},"end":{"line":665,"column":34}},"111":{"start":{"line":666,"column":20},"end":{"line":668,"column":21}},"112":{"start":{"line":667,"column":24},"end":{"line":667,"column":42}},"113":{"start":{"line":670,"column":16},"end":{"line":670,"column":74}},"114":{"start":{"line":671,"column":16},"end":{"line":671,"column":22}},"115":{"start":{"line":674,"column":16},"end":{"line":674,"column":75}},"116":{"start":{"line":677,"column":16},"end":{"line":677,"column":57}},"117":{"start":{"line":678,"column":16},"end":{"line":678,"column":86}},"118":{"start":{"line":679,"column":16},"end":{"line":679,"column":50}},"119":{"start":{"line":680,"column":16},"end":{"line":680,"column":38}},"120":{"start":{"line":681,"column":16},"end":{"line":681,"column":22}},"121":{"start":{"line":683,"column":16},"end":{"line":683,"column":48}},"122":{"start":{"line":685,"column":16},"end":{"line":685,"column":42}},"123":{"start":{"line":686,"column":16},"end":{"line":686,"column":22}},"124":{"start":{"line":688,"column":16},"end":{"line":688,"column":30}},"125":{"start":{"line":693,"column":8},"end":{"line":693,"column":37}},"126":{"start":{"line":708,"column":8},"end":{"line":709,"column":17}},"127":{"start":{"line":712,"column":8},"end":{"line":712,"column":39}},"128":{"start":{"line":714,"column":8},"end":{"line":742,"column":9}},"129":{"start":{"line":715,"column":12},"end":{"line":715,"column":24}},"130":{"start":{"line":717,"column":12},"end":{"line":739,"column":14}},"131":{"start":{"line":720,"column":20},"end":{"line":723,"column":21}},"132":{"start":{"line":721,"column":24},"end":{"line":721,"column":50}},"133":{"start":{"line":722,"column":24},"end":{"line":722,"column":31}},"134":{"start":{"line":725,"column":20},"end":{"line":727,"column":57}},"135":{"start":{"line":729,"column":20},"end":{"line":733,"column":27}},"136":{"start":{"line":732,"column":28},"end":{"line":732,"column":86}},"137":{"start":{"line":735,"column":20},"end":{"line":735,"column":46}},"138":{"start":{"line":741,"column":12},"end":{"line":741,"column":53}},"139":{"start":{"line":757,"column":8},"end":{"line":757,"column":41}},"140":{"start":{"line":759,"column":8},"end":{"line":763,"column":9}},"141":{"start":{"line":760,"column":12},"end":{"line":760,"column":40}},"142":{"start":{"line":761,"column":12},"end":{"line":761,"column":38}},"143":{"start":{"line":762,"column":12},"end":{"line":762,"column":26}},"144":{"start":{"line":765,"column":8},"end":{"line":767,"column":9}},"145":{"start":{"line":766,"column":12},"end":{"line":766,"column":26}},"146":{"start":{"line":781,"column":8},"end":{"line":785,"column":25}},"147":{"start":{"line":788,"column":8},"end":{"line":792,"column":9}},"148":{"start":{"line":789,"column":12},"end":{"line":791,"column":13}},"149":{"start":{"line":790,"column":16},"end":{"line":790,"column":35}},"150":{"start":{"line":794,"column":8},"end":{"line":834,"column":9}},"151":{"start":{"line":795,"column":12},"end":{"line":795,"column":43}},"152":{"start":{"line":797,"column":12},"end":{"line":833,"column":15}},"153":{"start":{"line":798,"column":16},"end":{"line":804,"column":56}},"154":{"start":{"line":807,"column":16},"end":{"line":832,"column":17}},"155":{"start":{"line":808,"column":20},"end":{"line":808,"column":50}},"156":{"start":{"line":809,"column":20},"end":{"line":831,"column":21}},"157":{"start":{"line":810,"column":24},"end":{"line":810,"column":57}},"158":{"start":{"line":812,"column":24},"end":{"line":830,"column":25}},"159":{"start":{"line":813,"column":28},"end":{"line":813,"column":84}},"160":{"start":{"line":814,"column":28},"end":{"line":814,"column":52}},"161":{"start":{"line":816,"column":28},"end":{"line":816,"column":66}},"162":{"start":{"line":817,"column":28},"end":{"line":817,"column":55}},"163":{"start":{"line":818,"column":28},"end":{"line":818,"column":79}},"164":{"start":{"line":820,"column":28},"end":{"line":820,"column":78}},"165":{"start":{"line":822,"column":28},"end":{"line":829,"column":29}},"166":{"start":{"line":828,"column":32},"end":{"line":828,"column":51}},"167":{"start":{"line":845,"column":8},"end":{"line":847,"column":59}},"168":{"start":{"line":849,"column":8},"end":{"line":852,"column":9}},"169":{"start":{"line":850,"column":12},"end":{"line":851,"column":51}},"170":{"start":{"line":854,"column":8},"end":{"line":858,"column":9}},"171":{"start":{"line":855,"column":12},"end":{"line":857,"column":48}},"172":{"start":{"line":876,"column":8},"end":{"line":877,"column":22}},"173":{"start":{"line":879,"column":8},"end":{"line":883,"column":9}},"174":{"start":{"line":880,"column":12},"end":{"line":882,"column":21}},"175":{"start":{"line":881,"column":16},"end":{"line":881,"column":71}},"176":{"start":{"line":885,"column":8},"end":{"line":885,"column":20}},"177":{"start":{"line":924,"column":8},"end":{"line":932,"column":53}},"178":{"start":{"line":934,"column":8},"end":{"line":972,"column":9}},"179":{"start":{"line":935,"column":12},"end":{"line":935,"column":35}},"180":{"start":{"line":936,"column":12},"end":{"line":936,"column":34}},"181":{"start":{"line":937,"column":12},"end":{"line":937,"column":39}},"182":{"start":{"line":939,"column":12},"end":{"line":939,"column":46}},"183":{"start":{"line":941,"column":12},"end":{"line":962,"column":13}},"184":{"start":{"line":942,"column":16},"end":{"line":950,"column":18}},"185":{"start":{"line":953,"column":16},"end":{"line":953,"column":67}},"186":{"start":{"line":956,"column":16},"end":{"line":958,"column":17}},"187":{"start":{"line":957,"column":20},"end":{"line":957,"column":48}},"188":{"start":{"line":960,"column":16},"end":{"line":960,"column":71}},"189":{"start":{"line":961,"column":16},"end":{"line":961,"column":64}},"190":{"start":{"line":965,"column":12},"end":{"line":971,"column":13}},"191":{"start":{"line":966,"column":16},"end":{"line":968,"column":17}},"192":{"start":{"line":967,"column":20},"end":{"line":967,"column":53}},"193":{"start":{"line":970,"column":16},"end":{"line":970,"column":74}},"194":{"start":{"line":975,"column":8},"end":{"line":975,"column":63}},"195":{"start":{"line":977,"column":8},"end":{"line":977,"column":55}},"196":{"start":{"line":987,"column":8},"end":{"line":988,"column":22}},"197":{"start":{"line":990,"column":8},"end":{"line":1003,"column":9}},"198":{"start":{"line":993,"column":12},"end":{"line":995,"column":13}},"199":{"start":{"line":994,"column":16},"end":{"line":994,"column":28}},"200":{"start":{"line":999,"column":12},"end":{"line":1002,"column":13}},"201":{"start":{"line":1001,"column":16},"end":{"line":1001,"column":24}},"202":{"start":{"line":1005,"column":8},"end":{"line":1005,"column":21}},"203":{"start":{"line":1021,"column":8},"end":{"line":1023,"column":69}},"204":{"start":{"line":1025,"column":8},"end":{"line":1025,"column":49}},"205":{"start":{"line":1027,"column":8},"end":{"line":1054,"column":9}},"206":{"start":{"line":1028,"column":12},"end":{"line":1028,"column":37}},"207":{"start":{"line":1029,"column":12},"end":{"line":1029,"column":30}},"208":{"start":{"line":1030,"column":12},"end":{"line":1030,"column":37}},"209":{"start":{"line":1031,"column":12},"end":{"line":1031,"column":41}},"210":{"start":{"line":1033,"column":12},"end":{"line":1034,"column":72}},"211":{"start":{"line":1036,"column":12},"end":{"line":1043,"column":14}},"212":{"start":{"line":1044,"column":12},"end":{"line":1046,"column":13}},"213":{"start":{"line":1045,"column":16},"end":{"line":1045,"column":94}},"214":{"start":{"line":1048,"column":12},"end":{"line":1051,"column":13}},"215":{"start":{"line":1050,"column":16},"end":{"line":1050,"column":41}},"216":{"start":{"line":1053,"column":12},"end":{"line":1053,"column":80}},"217":{"start":{"line":1056,"column":8},"end":{"line":1058,"column":11}},"218":{"start":{"line":1071,"column":8},"end":{"line":1075,"column":16}},"219":{"start":{"line":1077,"column":8},"end":{"line":1088,"column":9}},"220":{"start":{"line":1078,"column":12},"end":{"line":1078,"column":33}},"221":{"start":{"line":1079,"column":12},"end":{"line":1079,"column":38}},"222":{"start":{"line":1081,"column":12},"end":{"line":1087,"column":13}},"223":{"start":{"line":1082,"column":16},"end":{"line":1086,"column":17}},"224":{"start":{"line":1083,"column":20},"end":{"line":1083,"column":49}},"225":{"start":{"line":1084,"column":23},"end":{"line":1086,"column":17}},"226":{"start":{"line":1085,"column":20},"end":{"line":1085,"column":90}},"227":{"start":{"line":1090,"column":8},"end":{"line":1090,"column":27}},"228":{"start":{"line":1102,"column":8},"end":{"line":1104,"column":12}},"229":{"start":{"line":1115,"column":8},"end":{"line":1115,"column":73}},"230":{"start":{"line":1139,"column":8},"end":{"line":1139,"column":75}},"231":{"start":{"line":1165,"column":8},"end":{"line":1165,"column":32}},"232":{"start":{"line":1167,"column":8},"end":{"line":1170,"column":10}},"233":{"start":{"line":1171,"column":8},"end":{"line":1171,"column":25}},"234":{"start":{"line":1173,"column":8},"end":{"line":1173,"column":51}},"235":{"start":{"line":1174,"column":8},"end":{"line":1174,"column":52}}},"branchMap":{"1":{"line":218,"type":"if","locations":[{"start":{"line":218,"column":8},"end":{"line":218,"column":8}},{"start":{"line":218,"column":8},"end":{"line":218,"column":8}}]},"2":{"line":218,"type":"binary-expr","locations":[{"start":{"line":218,"column":12},"end":{"line":218,"column":16}},{"start":{"line":218,"column":20},"end":{"line":218,"column":25}}]},"3":{"line":219,"type":"if","locations":[{"start":{"line":219,"column":12},"end":{"line":219,"column":12}},{"start":{"line":219,"column":12},"end":{"line":219,"column":12}}]},"4":{"line":221,"type":"binary-expr","locations":[{"start":{"line":221,"column":23},"end":{"line":221,"column":26}},{"start":{"line":221,"column":30},"end":{"line":221,"column":63}}]},"5":{"line":222,"type":"if","locations":[{"start":{"line":222,"column":19},"end":{"line":222,"column":19}},{"start":{"line":222,"column":19},"end":{"line":222,"column":19}}]},"6":{"line":226,"type":"if","locations":[{"start":{"line":226,"column":12},"end":{"line":226,"column":12}},{"start":{"line":226,"column":12},"end":{"line":226,"column":12}}]},"7":{"line":226,"type":"binary-expr","locations":[{"start":{"line":226,"column":16},"end":{"line":226,"column":20}},{"start":{"line":226,"column":24},"end":{"line":226,"column":29}}]},"8":{"line":228,"type":"if","locations":[{"start":{"line":228,"column":16},"end":{"line":228,"column":16}},{"start":{"line":228,"column":16},"end":{"line":228,"column":16}}]},"9":{"line":230,"type":"switch","locations":[{"start":{"line":231,"column":24},"end":{"line":231,"column":64}},{"start":{"line":232,"column":24},"end":{"line":232,"column":63}},{"start":{"line":233,"column":24},"end":{"line":233,"column":63}},{"start":{"line":234,"column":24},"end":{"line":234,"column":64}}]},"10":{"line":238,"type":"if","locations":[{"start":{"line":238,"column":16},"end":{"line":238,"column":16}},{"start":{"line":238,"column":16},"end":{"line":238,"column":16}}]},"11":{"line":244,"type":"binary-expr","locations":[{"start":{"line":244,"column":28},"end":{"line":244,"column":31}},{"start":{"line":244,"column":35},"end":{"line":244,"column":66}}]},"12":{"line":249,"type":"binary-expr","locations":[{"start":{"line":249,"column":15},"end":{"line":249,"column":19}},{"start":{"line":249,"column":23},"end":{"line":249,"column":27}}]},"13":{"line":271,"type":"if","locations":[{"start":{"line":271,"column":8},"end":{"line":271,"column":8}},{"start":{"line":271,"column":8},"end":{"line":271,"column":8}}]},"14":{"line":271,"type":"binary-expr","locations":[{"start":{"line":271,"column":12},"end":{"line":271,"column":16}},{"start":{"line":271,"column":20},"end":{"line":271,"column":37}}]},"15":{"line":298,"type":"if","locations":[{"start":{"line":298,"column":8},"end":{"line":298,"column":8}},{"start":{"line":298,"column":8},"end":{"line":298,"column":8}}]},"16":{"line":299,"type":"if","locations":[{"start":{"line":299,"column":12},"end":{"line":299,"column":12}},{"start":{"line":299,"column":12},"end":{"line":299,"column":12}}]},"17":{"line":303,"type":"if","locations":[{"start":{"line":303,"column":12},"end":{"line":303,"column":12}},{"start":{"line":303,"column":12},"end":{"line":303,"column":12}}]},"18":{"line":308,"type":"binary-expr","locations":[{"start":{"line":308,"column":25},"end":{"line":308,"column":28}},{"start":{"line":309,"column":20},"end":{"line":309,"column":71}}]},"19":{"line":313,"type":"binary-expr","locations":[{"start":{"line":313,"column":15},"end":{"line":313,"column":21}},{"start":{"line":313,"column":25},"end":{"line":313,"column":29}}]},"20":{"line":330,"type":"if","locations":[{"start":{"line":330,"column":8},"end":{"line":330,"column":8}},{"start":{"line":330,"column":8},"end":{"line":330,"column":8}}]},"21":{"line":331,"type":"if","locations":[{"start":{"line":331,"column":12},"end":{"line":331,"column":12}},{"start":{"line":331,"column":12},"end":{"line":331,"column":12}}]},"22":{"line":332,"type":"binary-expr","locations":[{"start":{"line":332,"column":21},"end":{"line":332,"column":66}},{"start":{"line":332,"column":70},"end":{"line":332,"column":72}}]},"23":{"line":332,"type":"cond-expr","locations":[{"start":{"line":332,"column":42},"end":{"line":332,"column":60}},{"start":{"line":332,"column":63},"end":{"line":332,"column":65}}]},"24":{"line":335,"type":"cond-expr","locations":[{"start":{"line":336,"column":16},"end":{"line":336,"column":46}},{"start":{"line":337,"column":16},"end":{"line":337,"column":35}}]},"25":{"line":437,"type":"binary-expr","locations":[{"start":{"line":437,"column":22},"end":{"line":437,"column":36}},{"start":{"line":438,"column":23},"end":{"line":438,"column":63}}]},"26":{"line":443,"type":"if","locations":[{"start":{"line":443,"column":8},"end":{"line":443,"column":8}},{"start":{"line":443,"column":8},"end":{"line":443,"column":8}}]},"27":{"line":449,"type":"if","locations":[{"start":{"line":449,"column":8},"end":{"line":449,"column":8}},{"start":{"line":449,"column":8},"end":{"line":449,"column":8}}]},"28":{"line":478,"type":"if","locations":[{"start":{"line":478,"column":12},"end":{"line":478,"column":12}},{"start":{"line":478,"column":12},"end":{"line":478,"column":12}}]},"29":{"line":479,"type":"binary-expr","locations":[{"start":{"line":479,"column":62},"end":{"line":479,"column":69}},{"start":{"line":479,"column":73},"end":{"line":479,"column":80}}]},"30":{"line":508,"type":"binary-expr","locations":[{"start":{"line":508,"column":8},"end":{"line":508,"column":13}},{"start":{"line":508,"column":18},"end":{"line":508,"column":46}}]},"31":{"line":509,"type":"binary-expr","locations":[{"start":{"line":509,"column":8},"end":{"line":509,"column":11}},{"start":{"line":509,"column":16},"end":{"line":509,"column":42}}]},"32":{"line":512,"type":"if","locations":[{"start":{"line":512,"column":8},"end":{"line":512,"column":8}},{"start":{"line":512,"column":8},"end":{"line":512,"column":8}}]},"33":{"line":514,"type":"binary-expr","locations":[{"start":{"line":514,"column":22},"end":{"line":514,"column":64}},{"start":{"line":514,"column":68},"end":{"line":514,"column":72}}]},"34":{"line":525,"type":"if","locations":[{"start":{"line":525,"column":12},"end":{"line":525,"column":12}},{"start":{"line":525,"column":12},"end":{"line":525,"column":12}}]},"35":{"line":534,"type":"if","locations":[{"start":{"line":534,"column":15},"end":{"line":534,"column":15}},{"start":{"line":534,"column":15},"end":{"line":534,"column":15}}]},"36":{"line":535,"type":"if","locations":[{"start":{"line":535,"column":12},"end":{"line":535,"column":12}},{"start":{"line":535,"column":12},"end":{"line":535,"column":12}}]},"37":{"line":539,"type":"binary-expr","locations":[{"start":{"line":539,"column":26},"end":{"line":539,"column":42}},{"start":{"line":539,"column":46},"end":{"line":539,"column":50}}]},"38":{"line":541,"type":"if","locations":[{"start":{"line":541,"column":12},"end":{"line":541,"column":12}},{"start":{"line":541,"column":12},"end":{"line":541,"column":12}}]},"39":{"line":556,"type":"if","locations":[{"start":{"line":556,"column":16},"end":{"line":556,"column":16}},{"start":{"line":556,"column":16},"end":{"line":556,"column":16}}]},"40":{"line":561,"type":"if","locations":[{"start":{"line":561,"column":12},"end":{"line":561,"column":12}},{"start":{"line":561,"column":12},"end":{"line":561,"column":12}}]},"41":{"line":561,"type":"binary-expr","locations":[{"start":{"line":561,"column":16},"end":{"line":561,"column":37}},{"start":{"line":561,"column":41},"end":{"line":561,"column":57}},{"start":{"line":561,"column":61},"end":{"line":561,"column":75}}]},"42":{"line":562,"type":"binary-expr","locations":[{"start":{"line":562,"column":26},"end":{"line":562,"column":44}},{"start":{"line":562,"column":48},"end":{"line":562,"column":50}}]},"43":{"line":566,"type":"binary-expr","locations":[{"start":{"line":566,"column":22},"end":{"line":566,"column":35}},{"start":{"line":566,"column":39},"end":{"line":566,"column":57}},{"start":{"line":566,"column":61},"end":{"line":566,"column":63}}]},"44":{"line":569,"type":"cond-expr","locations":[{"start":{"line":569,"column":37},"end":{"line":569,"column":44}},{"start":{"line":569,"column":47},"end":{"line":569,"column":69}}]},"45":{"line":582,"type":"if","locations":[{"start":{"line":582,"column":8},"end":{"line":582,"column":8}},{"start":{"line":582,"column":8},"end":{"line":582,"column":8}}]},"46":{"line":589,"type":"if","locations":[{"start":{"line":589,"column":8},"end":{"line":589,"column":8}},{"start":{"line":589,"column":8},"end":{"line":589,"column":8}}]},"47":{"line":590,"type":"binary-expr","locations":[{"start":{"line":590,"column":19},"end":{"line":590,"column":45}},{"start":{"line":590,"column":49},"end":{"line":590,"column":53}}]},"48":{"line":596,"type":"if","locations":[{"start":{"line":596,"column":12},"end":{"line":596,"column":12}},{"start":{"line":596,"column":12},"end":{"line":596,"column":12}}]},"49":{"line":596,"type":"binary-expr","locations":[{"start":{"line":596,"column":17},"end":{"line":596,"column":25}},{"start":{"line":596,"column":29},"end":{"line":596,"column":37}}]},"50":{"line":636,"type":"binary-expr","locations":[{"start":{"line":636,"column":20},"end":{"line":636,"column":57}},{"start":{"line":636,"column":61},"end":{"line":636,"column":63}}]},"51":{"line":640,"type":"binary-expr","locations":[{"start":{"line":640,"column":22},"end":{"line":640,"column":31}},{"start":{"line":640,"column":35},"end":{"line":640,"column":59}}]},"52":{"line":653,"type":"if","locations":[{"start":{"line":653,"column":12},"end":{"line":653,"column":12}},{"start":{"line":653,"column":12},"end":{"line":653,"column":12}}]},"53":{"line":661,"type":"switch","locations":[{"start":{"line":662,"column":12},"end":{"line":671,"column":22}},{"start":{"line":672,"column":12},"end":{"line":681,"column":22}},{"start":{"line":682,"column":12},"end":{"line":686,"column":22}},{"start":{"line":687,"column":12},"end":{"line":688,"column":30}}]},"54":{"line":666,"type":"if","locations":[{"start":{"line":666,"column":20},"end":{"line":666,"column":20}},{"start":{"line":666,"column":20},"end":{"line":666,"column":20}}]},"55":{"line":666,"type":"binary-expr","locations":[{"start":{"line":666,"column":24},"end":{"line":666,"column":37}},{"start":{"line":666,"column":41},"end":{"line":666,"column":56}}]},"56":{"line":714,"type":"if","locations":[{"start":{"line":714,"column":8},"end":{"line":714,"column":8}},{"start":{"line":714,"column":8},"end":{"line":714,"column":8}}]},"57":{"line":720,"type":"if","locations":[{"start":{"line":720,"column":20},"end":{"line":720,"column":20}},{"start":{"line":720,"column":20},"end":{"line":720,"column":20}}]},"58":{"line":720,"type":"binary-expr","locations":[{"start":{"line":720,"column":24},"end":{"line":720,"column":29}},{"start":{"line":720,"column":33},"end":{"line":720,"column":52}},{"start":{"line":720,"column":56},"end":{"line":720,"column":71}},{"start":{"line":720,"column":75},"end":{"line":720,"column":98}}]},"59":{"line":732,"type":"cond-expr","locations":[{"start":{"line":732,"column":74},"end":{"line":732,"column":78}},{"start":{"line":732,"column":81},"end":{"line":732,"column":84}}]},"60":{"line":759,"type":"if","locations":[{"start":{"line":759,"column":8},"end":{"line":759,"column":8}},{"start":{"line":759,"column":8},"end":{"line":759,"column":8}}]},"61":{"line":765,"type":"if","locations":[{"start":{"line":765,"column":8},"end":{"line":765,"column":8}},{"start":{"line":765,"column":8},"end":{"line":765,"column":8}}]},"62":{"line":781,"type":"binary-expr","locations":[{"start":{"line":781,"column":19},"end":{"line":781,"column":28}},{"start":{"line":781,"column":32},"end":{"line":781,"column":36}}]},"63":{"line":789,"type":"if","locations":[{"start":{"line":789,"column":12},"end":{"line":789,"column":12}},{"start":{"line":789,"column":12},"end":{"line":789,"column":12}}]},"64":{"line":794,"type":"if","locations":[{"start":{"line":794,"column":8},"end":{"line":794,"column":8}},{"start":{"line":794,"column":8},"end":{"line":794,"column":8}}]},"65":{"line":794,"type":"binary-expr","locations":[{"start":{"line":794,"column":12},"end":{"line":794,"column":16}},{"start":{"line":794,"column":20},"end":{"line":794,"column":37}}]},"66":{"line":807,"type":"if","locations":[{"start":{"line":807,"column":16},"end":{"line":807,"column":16}},{"start":{"line":807,"column":16},"end":{"line":807,"column":16}}]},"67":{"line":812,"type":"if","locations":[{"start":{"line":812,"column":24},"end":{"line":812,"column":24}},{"start":{"line":812,"column":24},"end":{"line":812,"column":24}}]},"68":{"line":814,"type":"binary-expr","locations":[{"start":{"line":814,"column":34},"end":{"line":814,"column":41}},{"start":{"line":814,"column":45},"end":{"line":814,"column":51}}]},"69":{"line":818,"type":"binary-expr","locations":[{"start":{"line":818,"column":50},"end":{"line":818,"column":70}},{"start":{"line":818,"column":74},"end":{"line":818,"column":78}}]},"70":{"line":822,"type":"if","locations":[{"start":{"line":822,"column":28},"end":{"line":822,"column":28}},{"start":{"line":822,"column":28},"end":{"line":822,"column":28}}]},"71":{"line":849,"type":"if","locations":[{"start":{"line":849,"column":8},"end":{"line":849,"column":8}},{"start":{"line":849,"column":8},"end":{"line":849,"column":8}}]},"72":{"line":854,"type":"if","locations":[{"start":{"line":854,"column":8},"end":{"line":854,"column":8}},{"start":{"line":854,"column":8},"end":{"line":854,"column":8}}]},"73":{"line":854,"type":"binary-expr","locations":[{"start":{"line":854,"column":12},"end":{"line":854,"column":21}},{"start":{"line":854,"column":25},"end":{"line":854,"column":44}}]},"74":{"line":879,"type":"if","locations":[{"start":{"line":879,"column":8},"end":{"line":879,"column":8}},{"start":{"line":879,"column":8},"end":{"line":879,"column":8}}]},"75":{"line":929,"type":"cond-expr","locations":[{"start":{"line":929,"column":40},"end":{"line":929,"column":54}},{"start":{"line":929,"column":57},"end":{"line":929,"column":72}}]},"76":{"line":931,"type":"binary-expr","locations":[{"start":{"line":931,"column":19},"end":{"line":931,"column":28}},{"start":{"line":931,"column":32},"end":{"line":931,"column":36}}]},"77":{"line":937,"type":"binary-expr","locations":[{"start":{"line":937,"column":20},"end":{"line":937,"column":27}},{"start":{"line":937,"column":31},"end":{"line":937,"column":38}}]},"78":{"line":941,"type":"if","locations":[{"start":{"line":941,"column":12},"end":{"line":941,"column":12}},{"start":{"line":941,"column":12},"end":{"line":941,"column":12}}]},"79":{"line":956,"type":"if","locations":[{"start":{"line":956,"column":16},"end":{"line":956,"column":16}},{"start":{"line":956,"column":16},"end":{"line":956,"column":16}}]},"80":{"line":965,"type":"if","locations":[{"start":{"line":965,"column":12},"end":{"line":965,"column":12}},{"start":{"line":965,"column":12},"end":{"line":965,"column":12}}]},"81":{"line":965,"type":"binary-expr","locations":[{"start":{"line":965,"column":16},"end":{"line":965,"column":45}},{"start":{"line":965,"column":49},"end":{"line":965,"column":77}}]},"82":{"line":966,"type":"if","locations":[{"start":{"line":966,"column":16},"end":{"line":966,"column":16}},{"start":{"line":966,"column":16},"end":{"line":966,"column":16}}]},"83":{"line":966,"type":"binary-expr","locations":[{"start":{"line":966,"column":20},"end":{"line":966,"column":39}},{"start":{"line":966,"column":43},"end":{"line":966,"column":57}},{"start":{"line":966,"column":61},"end":{"line":966,"column":73}}]},"84":{"line":967,"type":"binary-expr","locations":[{"start":{"line":967,"column":28},"end":{"line":967,"column":46}},{"start":{"line":967,"column":50},"end":{"line":967,"column":52}}]},"85":{"line":970,"type":"cond-expr","locations":[{"start":{"line":970,"column":48},"end":{"line":970,"column":53}},{"start":{"line":970,"column":56},"end":{"line":970,"column":73}}]},"86":{"line":990,"type":"if","locations":[{"start":{"line":990,"column":8},"end":{"line":990,"column":8}},{"start":{"line":990,"column":8},"end":{"line":990,"column":8}}]},"87":{"line":990,"type":"binary-expr","locations":[{"start":{"line":990,"column":12},"end":{"line":990,"column":17}},{"start":{"line":990,"column":21},"end":{"line":990,"column":24}}]},"88":{"line":993,"type":"if","locations":[{"start":{"line":993,"column":12},"end":{"line":993,"column":12}},{"start":{"line":993,"column":12},"end":{"line":993,"column":12}}]},"89":{"line":1030,"type":"binary-expr","locations":[{"start":{"line":1030,"column":22},"end":{"line":1030,"column":29}},{"start":{"line":1030,"column":33},"end":{"line":1030,"column":36}}]},"90":{"line":1033,"type":"cond-expr","locations":[{"start":{"line":1034,"column":24},"end":{"line":1034,"column":66}},{"start":{"line":1034,"column":69},"end":{"line":1034,"column":71}}]},"91":{"line":1033,"type":"binary-expr","locations":[{"start":{"line":1033,"column":23},"end":{"line":1033,"column":35}},{"start":{"line":1033,"column":39},"end":{"line":1033,"column":41}}]},"92":{"line":1040,"type":"binary-expr","locations":[{"start":{"line":1040,"column":28},"end":{"line":1040,"column":41}},{"start":{"line":1040,"column":45},"end":{"line":1040,"column":47}}]},"93":{"line":1044,"type":"if","locations":[{"start":{"line":1044,"column":12},"end":{"line":1044,"column":12}},{"start":{"line":1044,"column":12},"end":{"line":1044,"column":12}}]},"94":{"line":1044,"type":"binary-expr","locations":[{"start":{"line":1044,"column":16},"end":{"line":1044,"column":26}},{"start":{"line":1044,"column":30},"end":{"line":1044,"column":43}}]},"95":{"line":1048,"type":"if","locations":[{"start":{"line":1048,"column":12},"end":{"line":1048,"column":12}},{"start":{"line":1048,"column":12},"end":{"line":1048,"column":12}}]},"96":{"line":1053,"type":"binary-expr","locations":[{"start":{"line":1053,"column":33},"end":{"line":1053,"column":49}},{"start":{"line":1053,"column":53},"end":{"line":1053,"column":65}}]},"97":{"line":1081,"type":"if","locations":[{"start":{"line":1081,"column":12},"end":{"line":1081,"column":12}},{"start":{"line":1081,"column":12},"end":{"line":1081,"column":12}}]},"98":{"line":1081,"type":"binary-expr","locations":[{"start":{"line":1081,"column":16},"end":{"line":1081,"column":33}},{"start":{"line":1081,"column":37},"end":{"line":1081,"column":46}}]},"99":{"line":1082,"type":"if","locations":[{"start":{"line":1082,"column":16},"end":{"line":1082,"column":16}},{"start":{"line":1082,"column":16},"end":{"line":1082,"column":16}}]},"100":{"line":1084,"type":"if","locations":[{"start":{"line":1084,"column":23},"end":{"line":1084,"column":23}},{"start":{"line":1084,"column":23},"end":{"line":1084,"column":23}}]},"101":{"line":1085,"type":"binary-expr","locations":[{"start":{"line":1085,"column":66},"end":{"line":1085,"column":75}},{"start":{"line":1085,"column":79},"end":{"line":1085,"column":83}}]},"102":{"line":1139,"type":"binary-expr","locations":[{"start":{"line":1139,"column":15},"end":{"line":1139,"column":36}},{"start":{"line":1139,"column":41},"end":{"line":1139,"column":73}}]}},"code":["(function () { 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,"," valueRegExp = /\\{value\\}/g,"," EV_CONTENT_UPDATE = 'contentUpdate';","","/**","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 amended 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.","","A column `formatter` can be:",""," * a function, as described below."," * a string which can be:"," * the name of a pre-defined formatter function"," which can be located in the `Y.DataTable.BodyView.Formatters` hash using the"," value of the `formatter` property as the index."," * A template that can use the `{value}` placeholder to include the value"," for the current cell or the name of any field in the underlaying model"," also enclosed in curly braces. Any number and type of these placeholders"," can be used.","","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.target, [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 concatenating 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'),"," displayCols = this.get('columns'),"," tbody = this.tbodyNode ||"," (this.tbodyNode = this._createTBodyNode());",""," // Needed for mutation"," this._createRowTemplate(displayCols);",""," if (data) {"," tbody.setHTML(this._createDataHTML(displayCols));",""," this._applyNodeFormatters(tbody, displayCols);"," }",""," if (tbody.get('parentNode') !== table) {"," table.appendChild(tbody);"," }",""," this.bindUI();",""," return this;"," },",""," /**"," Refreshes the provided row against the provided model and the Array of"," columns to be updated.",""," @method refreshRow"," @param {Y.Node} row"," @param {Y.Model} model Y.Model representation of the row"," @param {String[]} colKeys Array of column keys",""," @chainable"," */"," refreshRow: function (row, model, colKeys) {"," var col,"," cell,"," len = colKeys.length,"," i;",""," for (i = 0; i < len; i++) {"," col = this.getColumn(colKeys[i]);",""," if (col !== null) {"," cell = row.one('.' + this.getClassName('col', col._id || col.key));"," this.refreshCell(cell, model);"," }"," }",""," return this;"," },",""," /**"," Refreshes the given cell with the provided model data and the provided"," column configuration.",""," Uses the provided column formatter if aviable.",""," @method refreshCell"," @param {Y.Node} cell Y.Node pointer to the cell element to be updated"," @param {Y.Model} [model] Y.Model representation of the row"," @param {Object} [col] Column configuration object for the cell",""," @chainable"," */"," refreshCell: function (cell, model, col) {"," var content,"," formatterFn,"," formatterData,"," data = model.toJSON();",""," cell = this.getCell(cell);"," /* jshint -W030 */"," model || (model = this.getRecord(cell));"," col || (col = this.getColumn(cell));"," /* jshint +W030 */",""," if (col.nodeFormatter) {"," formatterData = {"," cell: cell.one('.' + this.getClassName('liner')) || cell,"," column: col,"," data: data,"," record: model,"," rowIndex: this._getRowIndex(cell.ancestor('tr')),"," td: cell,"," value: data[col.key]"," };",""," 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);"," }",""," } else if (col.formatter) {"," if (!col._formatterFn) {"," col = this._setColumnsFormatterFn([col])[0];"," }",""," formatterFn = col._formatterFn || null;",""," if (formatterFn) {"," formatterData = {"," value : data[col.key],"," data : data,"," column : col,"," record : model,"," className: '',"," rowClass : '',"," rowIndex : this._getRowIndex(cell.ancestor('tr'))"," };",""," // Formatters can either return a value ..."," content = formatterFn.call(this.get('host'), formatterData);",""," // ... or update the value property of the data obj passed"," if (content === undefined) {"," content = formatterData.value;"," }"," }",""," if (content === undefined || content === null || content === '') {"," content = col.emptyCellValue || '';"," }",""," } else {"," content = data[col.key] || col.emptyCellValue || '';"," }",""," cell.setHTML(col.allowHTML ? content : Y.Escape.html(content));",""," return this;"," },",""," /**"," Returns column data from this.get('columns'). If a Y.Node is provided as"," the key, will try to determine the key from the classname"," @method getColumn"," @param {String|Y.Node} name"," @return {Object} Returns column configuration"," */"," getColumn: function (name) {"," if (Y.instanceOf(name, Y.Node)) {"," // get column name from node"," name = name.get('className').match("," new RegExp( this.getClassName('col') +'-([^ ]*)' )"," )[1];"," }",""," if (this.host) {"," return this.host._columnMap[name] || null;"," }"," var displayCols = this.get('columns'),"," col = null;",""," Y.Array.some(displayCols, function (_col) {"," if ((_col._id || _col.key) === name) {"," col = _col;"," return true;"," }"," });",""," return col;"," },",""," // -- 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 () {"," 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.match(/:(add|change|remove)$/) || [])[1],"," index = e.index,"," displayCols = this.get('columns'),"," col,"," changed = e.changed && Y.Object.keys(e.changed),"," key,"," row,"," i,"," len;",""," for (i = 0, len = displayCols.length; i < len; i++ ) {"," col = displayCols[i];",""," // since nodeFormatters typcially make changes outside of it's"," // cell, we need to see if there are any columns that have a"," // nodeFormatter and if so, we need to do a full render() of the"," // tbody"," if (col.hasOwnProperty('nodeFormatter')) {"," this.render();"," this.fire(EV_CONTENT_UPDATE);"," return;"," }"," }",""," // TODO: if multiple rows are being added/remove/swapped, can we avoid the restriping?"," switch (type) {"," case 'change':"," for (i = 0, len = displayCols.length; i < len; i++) {"," col = displayCols[i];"," key = col.key;"," if (col.formatter && !e.changed[key]) {"," changed.push(key);"," }"," }"," this.refreshRow(this.getRow(e.target), e.target, changed);"," break;"," case 'add':"," // we need to make sure we don't have an index larger than the data we have"," index = Math.min(index, this.get('modelList').size() - 1);",""," // updates the columns with formatter functions"," this._setColumnsFormatterFn(displayCols);"," row = Y.Node.create(this._createRowHTML(e.model, index, displayCols));"," this.tbodyNode.insert(row, index);"," this._restripe(index);"," break;"," case 'remove':"," this.getRow(index).remove(true);"," // we removed a row, so we need to back up our index to stripe"," this._restripe(index - 1);"," break;"," default:"," this.render();"," }",""," // Event fired to tell users when we are done updating after the data"," // was changed"," this.fire(EV_CONTENT_UPDATE);"," },",""," /**"," Toggles the odd/even classname of the row after the given index. This method"," is used to update rows after a row is inserted into or removed from the table."," Note this event is delayed so the table is only restriped once when multiple"," rows are updated at one time.",""," @protected"," @method _restripe"," @param {Number} [index] Index of row to start restriping after"," @since 3.11.0"," */"," _restripe: function (index) {"," var task = this._restripeTask,"," self;",""," // index|0 to force int, avoid NaN. Math.max() to avoid neg indexes."," index = Math.max((index|0), 0);",""," if (!task) {"," self = this;",""," this._restripeTask = {"," timer: setTimeout(function () {"," // Check for self existence before continuing"," if (!self || self.get('destroy') || !self.tbodyNode || !self.tbodyNode.inDoc()) {"," self._restripeTask = null;"," return;"," }",""," var odd = [self.CLASS_ODD, self.CLASS_EVEN],"," even = [self.CLASS_EVEN, self.CLASS_ODD],"," index = self._restripeTask.index;",""," self.tbodyNode.get('childNodes')"," .slice(index)"," .each(function (row, i) { // TODO: each vs batch"," row.replaceClass.apply(row, (index + i) % 2 ? even : odd);"," });",""," self._restripeTask = null;"," }, 0),",""," index: index"," };"," } else {"," task.index = Math.min(task.index, index);"," }",""," },",""," /**"," Handles replacement of the modelList.",""," Rerenders the `<tbody>` contents.",""," @method _afterModelListChange"," @param {EventFacade} e The `modelListChange` event"," @protected"," @since 3.6.0"," **/"," _afterModelListChange: function () {"," 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[]} displayCols The column configurations"," @protected"," @since 3.5.0"," **/"," _applyNodeFormatters: function (tbody, displayCols) {"," var host = this.host || this,"," 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 = displayCols.length; i < len; ++i) {"," if (displayCols[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 = displayCols[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[]} displayCols 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 (displayCols) {"," var data = this.get('modelList'),"," html = '';",""," if (data) {"," data.each(function (model, index) {"," html += this._createRowHTML(model, index, displayCols);"," }, 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[]} displayCols The column configurations"," @return {HTML} The markup for the provided Model, less any `nodeFormatter`s"," @protected"," @since 3.5.0"," **/"," _createRowHTML: function (model, index, displayCols) {"," 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 = displayCols.length; i < len; ++i) {"," col = displayCols[i];"," value = data[col.key];"," token = col._id || col.key;",""," values[token + '-className'] = '';",""," if (col._formatterFn) {"," formatterData = {"," value : value,"," data : data,"," column : col,"," record : model,"," className: '',"," rowClass : '',"," rowIndex : index"," };",""," // Formatters can either return a value"," value = col._formatterFn.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 the token missing OR is the value a legit value"," if (!values.hasOwnProperty(token) || data.hasOwnProperty(col.key)) {"," if (value === undefined || value === null || value === '') {"," value = col.emptyCellValue || '';"," }",""," values[token] = col.allowHTML ? value : htmlEscape(value);"," }"," }",""," // replace consecutive whitespace with a single space"," values.rowClass = values.rowClass.replace(/\\s+/g, ' ');",""," return fromTemplate(this._rowTemplate, values);"," },",""," /**"," Locates the row within the tbodyNode and returns the found index, or Null"," if it is not found in the tbodyNode"," @param {Y.Node} row"," @return {Number} Index of row in tbodyNode"," */"," _getRowIndex: function (row) {"," var tbody = this.tbodyNode,"," index = 1;",""," if (tbody && row) {",""," //if row is not in the tbody, return"," if (row.ancestor('tbody') !== tbody) {"," return null;"," }",""," // increment until we no longer have a previous node"," /*jshint boss: true*/"," while (row = row.previous()) { // NOTE: assignment"," /*jshint boss: false*/"," index++;"," }"," }",""," return index;"," },",""," /**"," 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[]} displayCols Array of column configuration objects"," @protected"," @since 3.5.0"," **/"," _createRowTemplate: function (displayCols) {"," var html = '',"," cellTemplate = this.CELL_TEMPLATE,"," i, len, col, key, token, headers, tokenValues, formatter;",""," this._setColumnsFormatterFn(displayCols);",""," for (i = 0, len = displayCols.length; i < len; ++i) {"," col = displayCols[i];"," key = col.key;"," token = col._id || key;"," formatter = col._formatterFn;"," // 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 (!formatter && col.formatter) {"," tokenValues.content = col.formatter.replace(valueRegExp, tokenValues.content);"," }",""," 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"," });"," },",""," /**"," Parses the columns array and defines the column's _formatterFn if there"," is a formatter available on the column"," @protected"," @method _setColumnsFormatterFn"," @param {Object[]} displayCols Array of column configuration objects",""," @return {Object[]} Returns modified displayCols configuration Array"," */"," _setColumnsFormatterFn: function (displayCols) {"," var Formatters = Y.DataTable.BodyView.Formatters,"," formatter,"," col,"," i,"," len;",""," for (i = 0, len = displayCols.length; i < len; i++) {"," col = displayCols[i];"," formatter = col.formatter;",""," if (!col._formatterFn && formatter) {"," if (Lang.isFunction(formatter)) {"," col._formatterFn = formatter;"," } else if (formatter in Formatters) {"," col._formatterFn = Formatters[formatter].call(this.host || this, col);"," }"," }"," }",""," return displayCols;"," },",""," /**"," 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","},{"," /**"," Hash of formatting functions for cell contents.",""," This property can be populated with a hash of formatting functions by the developer"," or a set of pre-defined functions can be loaded via the `datatable-formatters` module.",""," See: [DataTable.BodyView.Formatters](./DataTable.BodyView.Formatters.html)"," @property Formatters"," @type Object"," @since 3.8.0"," @static"," **/"," Formatters: {}","});","","","}, '@VERSION@', {\"requires\": [\"datatable-core\", \"view\", \"classnamemanager\"]});","","}());"]};
}
var __cov_lwdQmRpEAfazeg1nWBy89g = __coverage__['build/datatable-body/datatable-body.js'];
__cov_lwdQmRpEAfazeg1nWBy89g.s['1']++;YUI.add('datatable-body',function(Y,NAME){__cov_lwdQmRpEAfazeg1nWBy89g.f['1']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['2']++;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,valueRegExp=/\{value\}/g,EV_CONTENT_UPDATE='contentUpdate';__cov_lwdQmRpEAfazeg1nWBy89g.s['3']++;Y.namespace('DataTable').BodyView=Y.Base.create('tableBody',Y.View,[],{CELL_TEMPLATE:'<td {headers} class="{className}">{content}</td>',ROW_TEMPLATE:'<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>',TBODY_TEMPLATE:'<tbody class="{className}"></tbody>',getCell:function(seed,shift){__cov_lwdQmRpEAfazeg1nWBy89g.f['2']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['4']++;var tbody=this.tbodyNode,row,cell,index,rowIndexOffset;__cov_lwdQmRpEAfazeg1nWBy89g.s['5']++;if((__cov_lwdQmRpEAfazeg1nWBy89g.b['2'][0]++,seed)&&(__cov_lwdQmRpEAfazeg1nWBy89g.b['2'][1]++,tbody)){__cov_lwdQmRpEAfazeg1nWBy89g.b['1'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['6']++;if(isArray(seed)){__cov_lwdQmRpEAfazeg1nWBy89g.b['3'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['7']++;row=tbody.get('children').item(seed[0]);__cov_lwdQmRpEAfazeg1nWBy89g.s['8']++;cell=(__cov_lwdQmRpEAfazeg1nWBy89g.b['4'][0]++,row)&&(__cov_lwdQmRpEAfazeg1nWBy89g.b['4'][1]++,row.get('children').item(seed[1]));}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['3'][1]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['9']++;if(Y.instanceOf(seed,Y.Node)){__cov_lwdQmRpEAfazeg1nWBy89g.b['5'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['10']++;cell=seed.ancestor('.'+this.getClassName('cell'),true);}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['5'][1]++;}}__cov_lwdQmRpEAfazeg1nWBy89g.s['11']++;if((__cov_lwdQmRpEAfazeg1nWBy89g.b['7'][0]++,cell)&&(__cov_lwdQmRpEAfazeg1nWBy89g.b['7'][1]++,shift)){__cov_lwdQmRpEAfazeg1nWBy89g.b['6'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['12']++;rowIndexOffset=tbody.get('firstChild.rowIndex');__cov_lwdQmRpEAfazeg1nWBy89g.s['13']++;if(isString(shift)){__cov_lwdQmRpEAfazeg1nWBy89g.b['8'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['14']++;switch(shift){case'above':__cov_lwdQmRpEAfazeg1nWBy89g.b['9'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['15']++;shift=[-1,0];__cov_lwdQmRpEAfazeg1nWBy89g.s['16']++;break;case'below':__cov_lwdQmRpEAfazeg1nWBy89g.b['9'][1]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['17']++;shift=[1,0];__cov_lwdQmRpEAfazeg1nWBy89g.s['18']++;break;case'next':__cov_lwdQmRpEAfazeg1nWBy89g.b['9'][2]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['19']++;shift=[0,1];__cov_lwdQmRpEAfazeg1nWBy89g.s['20']++;break;case'previous':__cov_lwdQmRpEAfazeg1nWBy89g.b['9'][3]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['21']++;shift=[0,-1];__cov_lwdQmRpEAfazeg1nWBy89g.s['22']++;break;}}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['8'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['23']++;if(isArray(shift)){__cov_lwdQmRpEAfazeg1nWBy89g.b['10'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['24']++;index=cell.get('parentNode.rowIndex')+shift[0]-rowIndexOffset;__cov_lwdQmRpEAfazeg1nWBy89g.s['25']++;row=tbody.get('children').item(index);__cov_lwdQmRpEAfazeg1nWBy89g.s['26']++;index=cell.get('cellIndex')+shift[1];__cov_lwdQmRpEAfazeg1nWBy89g.s['27']++;cell=(__cov_lwdQmRpEAfazeg1nWBy89g.b['11'][0]++,row)&&(__cov_lwdQmRpEAfazeg1nWBy89g.b['11'][1]++,row.get('children').item(index));}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['10'][1]++;}}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['6'][1]++;}}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['1'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['28']++;return(__cov_lwdQmRpEAfazeg1nWBy89g.b['12'][0]++,cell)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['12'][1]++,null);},getClassName:function(){__cov_lwdQmRpEAfazeg1nWBy89g.f['3']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['29']++;var host=this.host,args;__cov_lwdQmRpEAfazeg1nWBy89g.s['30']++;if((__cov_lwdQmRpEAfazeg1nWBy89g.b['14'][0]++,host)&&(__cov_lwdQmRpEAfazeg1nWBy89g.b['14'][1]++,host.getClassName)){__cov_lwdQmRpEAfazeg1nWBy89g.b['13'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['31']++;return host.getClassName.apply(host,arguments);}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['13'][1]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['32']++;args=toArray(arguments);__cov_lwdQmRpEAfazeg1nWBy89g.s['33']++;args.unshift(this.constructor.NAME);__cov_lwdQmRpEAfazeg1nWBy89g.s['34']++;return Y.ClassNameManager.getClassName.apply(Y.ClassNameManager,args);}},getRecord:function(seed){__cov_lwdQmRpEAfazeg1nWBy89g.f['4']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['35']++;var modelList=this.get('modelList'),tbody=this.tbodyNode,row=null,record;__cov_lwdQmRpEAfazeg1nWBy89g.s['36']++;if(tbody){__cov_lwdQmRpEAfazeg1nWBy89g.b['15'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['37']++;if(isString(seed)){__cov_lwdQmRpEAfazeg1nWBy89g.b['16'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['38']++;seed=tbody.one('#'+seed);}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['16'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['39']++;if(Y.instanceOf(seed,Y.Node)){__cov_lwdQmRpEAfazeg1nWBy89g.b['17'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['40']++;row=seed.ancestor(function(node){__cov_lwdQmRpEAfazeg1nWBy89g.f['5']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['41']++;return node.get('parentNode').compareTo(tbody);},true);__cov_lwdQmRpEAfazeg1nWBy89g.s['42']++;record=(__cov_lwdQmRpEAfazeg1nWBy89g.b['18'][0]++,row)&&(__cov_lwdQmRpEAfazeg1nWBy89g.b['18'][1]++,modelList.getByClientId(row.getData('yui3-record')));}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['17'][1]++;}}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['15'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['43']++;return(__cov_lwdQmRpEAfazeg1nWBy89g.b['19'][0]++,record)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['19'][1]++,null);},getRow:function(id){__cov_lwdQmRpEAfazeg1nWBy89g.f['6']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['44']++;var tbody=this.tbodyNode,row=null;__cov_lwdQmRpEAfazeg1nWBy89g.s['45']++;if(tbody){__cov_lwdQmRpEAfazeg1nWBy89g.b['20'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['46']++;if(id){__cov_lwdQmRpEAfazeg1nWBy89g.b['21'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['47']++;id=(__cov_lwdQmRpEAfazeg1nWBy89g.b['22'][0]++,this._idMap[id.get?(__cov_lwdQmRpEAfazeg1nWBy89g.b['23'][0]++,id.get('clientId')):(__cov_lwdQmRpEAfazeg1nWBy89g.b['23'][1]++,id)])||(__cov_lwdQmRpEAfazeg1nWBy89g.b['22'][1]++,id);}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['21'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['48']++;row=isNumber(id)?(__cov_lwdQmRpEAfazeg1nWBy89g.b['24'][0]++,tbody.get('children').item(id)):(__cov_lwdQmRpEAfazeg1nWBy89g.b['24'][1]++,tbody.one('#'+id));}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['20'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['49']++;return row;},render:function(){__cov_lwdQmRpEAfazeg1nWBy89g.f['7']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['50']++;var table=this.get('container'),data=this.get('modelList'),displayCols=this.get('columns'),tbody=(__cov_lwdQmRpEAfazeg1nWBy89g.b['25'][0]++,this.tbodyNode)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['25'][1]++,this.tbodyNode=this._createTBodyNode());__cov_lwdQmRpEAfazeg1nWBy89g.s['51']++;this._createRowTemplate(displayCols);__cov_lwdQmRpEAfazeg1nWBy89g.s['52']++;if(data){__cov_lwdQmRpEAfazeg1nWBy89g.b['26'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['53']++;tbody.setHTML(this._createDataHTML(displayCols));__cov_lwdQmRpEAfazeg1nWBy89g.s['54']++;this._applyNodeFormatters(tbody,displayCols);}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['26'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['55']++;if(tbody.get('parentNode')!==table){__cov_lwdQmRpEAfazeg1nWBy89g.b['27'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['56']++;table.appendChild(tbody);}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['27'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['57']++;this.bindUI();__cov_lwdQmRpEAfazeg1nWBy89g.s['58']++;return this;},refreshRow:function(row,model,colKeys){__cov_lwdQmRpEAfazeg1nWBy89g.f['8']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['59']++;var col,cell,len=colKeys.length,i;__cov_lwdQmRpEAfazeg1nWBy89g.s['60']++;for(i=0;i<len;i++){__cov_lwdQmRpEAfazeg1nWBy89g.s['61']++;col=this.getColumn(colKeys[i]);__cov_lwdQmRpEAfazeg1nWBy89g.s['62']++;if(col!==null){__cov_lwdQmRpEAfazeg1nWBy89g.b['28'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['63']++;cell=row.one('.'+this.getClassName('col',(__cov_lwdQmRpEAfazeg1nWBy89g.b['29'][0]++,col._id)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['29'][1]++,col.key)));__cov_lwdQmRpEAfazeg1nWBy89g.s['64']++;this.refreshCell(cell,model);}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['28'][1]++;}}__cov_lwdQmRpEAfazeg1nWBy89g.s['65']++;return this;},refreshCell:function(cell,model,col){__cov_lwdQmRpEAfazeg1nWBy89g.f['9']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['66']++;var content,formatterFn,formatterData,data=model.toJSON();__cov_lwdQmRpEAfazeg1nWBy89g.s['67']++;cell=this.getCell(cell);__cov_lwdQmRpEAfazeg1nWBy89g.s['68']++;(__cov_lwdQmRpEAfazeg1nWBy89g.b['30'][0]++,model)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['30'][1]++,model=this.getRecord(cell));__cov_lwdQmRpEAfazeg1nWBy89g.s['69']++;(__cov_lwdQmRpEAfazeg1nWBy89g.b['31'][0]++,col)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['31'][1]++,col=this.getColumn(cell));__cov_lwdQmRpEAfazeg1nWBy89g.s['70']++;if(col.nodeFormatter){__cov_lwdQmRpEAfazeg1nWBy89g.b['32'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['71']++;formatterData={cell:(__cov_lwdQmRpEAfazeg1nWBy89g.b['33'][0]++,cell.one('.'+this.getClassName('liner')))||(__cov_lwdQmRpEAfazeg1nWBy89g.b['33'][1]++,cell),column:col,data:data,record:model,rowIndex:this._getRowIndex(cell.ancestor('tr')),td:cell,value:data[col.key]};__cov_lwdQmRpEAfazeg1nWBy89g.s['72']++;keep=col.nodeFormatter.call(host,formatterData);__cov_lwdQmRpEAfazeg1nWBy89g.s['73']++;if(keep===false){__cov_lwdQmRpEAfazeg1nWBy89g.b['34'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['74']++;cell.destroy(true);}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['34'][1]++;}}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['32'][1]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['75']++;if(col.formatter){__cov_lwdQmRpEAfazeg1nWBy89g.b['35'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['76']++;if(!col._formatterFn){__cov_lwdQmRpEAfazeg1nWBy89g.b['36'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['77']++;col=this._setColumnsFormatterFn([col])[0];}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['36'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['78']++;formatterFn=(__cov_lwdQmRpEAfazeg1nWBy89g.b['37'][0]++,col._formatterFn)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['37'][1]++,null);__cov_lwdQmRpEAfazeg1nWBy89g.s['79']++;if(formatterFn){__cov_lwdQmRpEAfazeg1nWBy89g.b['38'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['80']++;formatterData={value:data[col.key],data:data,column:col,record:model,className:'',rowClass:'',rowIndex:this._getRowIndex(cell.ancestor('tr'))};__cov_lwdQmRpEAfazeg1nWBy89g.s['81']++;content=formatterFn.call(this.get('host'),formatterData);__cov_lwdQmRpEAfazeg1nWBy89g.s['82']++;if(content===undefined){__cov_lwdQmRpEAfazeg1nWBy89g.b['39'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['83']++;content=formatterData.value;}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['39'][1]++;}}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['38'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['84']++;if((__cov_lwdQmRpEAfazeg1nWBy89g.b['41'][0]++,content===undefined)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['41'][1]++,content===null)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['41'][2]++,content==='')){__cov_lwdQmRpEAfazeg1nWBy89g.b['40'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['85']++;content=(__cov_lwdQmRpEAfazeg1nWBy89g.b['42'][0]++,col.emptyCellValue)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['42'][1]++,'');}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['40'][1]++;}}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['35'][1]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['86']++;content=(__cov_lwdQmRpEAfazeg1nWBy89g.b['43'][0]++,data[col.key])||(__cov_lwdQmRpEAfazeg1nWBy89g.b['43'][1]++,col.emptyCellValue)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['43'][2]++,'');}}__cov_lwdQmRpEAfazeg1nWBy89g.s['87']++;cell.setHTML(col.allowHTML?(__cov_lwdQmRpEAfazeg1nWBy89g.b['44'][0]++,content):(__cov_lwdQmRpEAfazeg1nWBy89g.b['44'][1]++,Y.Escape.html(content)));__cov_lwdQmRpEAfazeg1nWBy89g.s['88']++;return this;},getColumn:function(name){__cov_lwdQmRpEAfazeg1nWBy89g.f['10']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['89']++;if(Y.instanceOf(name,Y.Node)){__cov_lwdQmRpEAfazeg1nWBy89g.b['45'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['90']++;name=name.get('className').match(new RegExp(this.getClassName('col')+'-([^ ]*)'))[1];}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['45'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['91']++;if(this.host){__cov_lwdQmRpEAfazeg1nWBy89g.b['46'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['92']++;return(__cov_lwdQmRpEAfazeg1nWBy89g.b['47'][0]++,this.host._columnMap[name])||(__cov_lwdQmRpEAfazeg1nWBy89g.b['47'][1]++,null);}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['46'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['93']++;var displayCols=this.get('columns'),col=null;__cov_lwdQmRpEAfazeg1nWBy89g.s['94']++;Y.Array.some(displayCols,function(_col){__cov_lwdQmRpEAfazeg1nWBy89g.f['11']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['95']++;if(((__cov_lwdQmRpEAfazeg1nWBy89g.b['49'][0]++,_col._id)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['49'][1]++,_col.key))===name){__cov_lwdQmRpEAfazeg1nWBy89g.b['48'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['96']++;col=_col;__cov_lwdQmRpEAfazeg1nWBy89g.s['97']++;return true;}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['48'][1]++;}});__cov_lwdQmRpEAfazeg1nWBy89g.s['98']++;return col;},_afterColumnsChange:function(){__cov_lwdQmRpEAfazeg1nWBy89g.f['12']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['99']++;this.render();},_afterDataChange:function(e){__cov_lwdQmRpEAfazeg1nWBy89g.f['13']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['100']++;var type=((__cov_lwdQmRpEAfazeg1nWBy89g.b['50'][0]++,e.type.match(/:(add|change|remove)$/))||(__cov_lwdQmRpEAfazeg1nWBy89g.b['50'][1]++,[]))[1],index=e.index,displayCols=this.get('columns'),col,changed=(__cov_lwdQmRpEAfazeg1nWBy89g.b['51'][0]++,e.changed)&&(__cov_lwdQmRpEAfazeg1nWBy89g.b['51'][1]++,Y.Object.keys(e.changed)),key,row,i,len;__cov_lwdQmRpEAfazeg1nWBy89g.s['101']++;for(i=0,len=displayCols.length;i<len;i++){__cov_lwdQmRpEAfazeg1nWBy89g.s['102']++;col=displayCols[i];__cov_lwdQmRpEAfazeg1nWBy89g.s['103']++;if(col.hasOwnProperty('nodeFormatter')){__cov_lwdQmRpEAfazeg1nWBy89g.b['52'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['104']++;this.render();__cov_lwdQmRpEAfazeg1nWBy89g.s['105']++;this.fire(EV_CONTENT_UPDATE);__cov_lwdQmRpEAfazeg1nWBy89g.s['106']++;return;}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['52'][1]++;}}__cov_lwdQmRpEAfazeg1nWBy89g.s['107']++;switch(type){case'change':__cov_lwdQmRpEAfazeg1nWBy89g.b['53'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['108']++;for(i=0,len=displayCols.length;i<len;i++){__cov_lwdQmRpEAfazeg1nWBy89g.s['109']++;col=displayCols[i];__cov_lwdQmRpEAfazeg1nWBy89g.s['110']++;key=col.key;__cov_lwdQmRpEAfazeg1nWBy89g.s['111']++;if((__cov_lwdQmRpEAfazeg1nWBy89g.b['55'][0]++,col.formatter)&&(__cov_lwdQmRpEAfazeg1nWBy89g.b['55'][1]++,!e.changed[key])){__cov_lwdQmRpEAfazeg1nWBy89g.b['54'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['112']++;changed.push(key);}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['54'][1]++;}}__cov_lwdQmRpEAfazeg1nWBy89g.s['113']++;this.refreshRow(this.getRow(e.target),e.target,changed);__cov_lwdQmRpEAfazeg1nWBy89g.s['114']++;break;case'add':__cov_lwdQmRpEAfazeg1nWBy89g.b['53'][1]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['115']++;index=Math.min(index,this.get('modelList').size()-1);__cov_lwdQmRpEAfazeg1nWBy89g.s['116']++;this._setColumnsFormatterFn(displayCols);__cov_lwdQmRpEAfazeg1nWBy89g.s['117']++;row=Y.Node.create(this._createRowHTML(e.model,index,displayCols));__cov_lwdQmRpEAfazeg1nWBy89g.s['118']++;this.tbodyNode.insert(row,index);__cov_lwdQmRpEAfazeg1nWBy89g.s['119']++;this._restripe(index);__cov_lwdQmRpEAfazeg1nWBy89g.s['120']++;break;case'remove':__cov_lwdQmRpEAfazeg1nWBy89g.b['53'][2]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['121']++;this.getRow(index).remove(true);__cov_lwdQmRpEAfazeg1nWBy89g.s['122']++;this._restripe(index-1);__cov_lwdQmRpEAfazeg1nWBy89g.s['123']++;break;default:__cov_lwdQmRpEAfazeg1nWBy89g.b['53'][3]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['124']++;this.render();}__cov_lwdQmRpEAfazeg1nWBy89g.s['125']++;this.fire(EV_CONTENT_UPDATE);},_restripe:function(index){__cov_lwdQmRpEAfazeg1nWBy89g.f['14']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['126']++;var task=this._restripeTask,self;__cov_lwdQmRpEAfazeg1nWBy89g.s['127']++;index=Math.max(index|0,0);__cov_lwdQmRpEAfazeg1nWBy89g.s['128']++;if(!task){__cov_lwdQmRpEAfazeg1nWBy89g.b['56'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['129']++;self=this;__cov_lwdQmRpEAfazeg1nWBy89g.s['130']++;this._restripeTask={timer:setTimeout(function(){__cov_lwdQmRpEAfazeg1nWBy89g.f['15']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['131']++;if((__cov_lwdQmRpEAfazeg1nWBy89g.b['58'][0]++,!self)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['58'][1]++,self.get('destroy'))||(__cov_lwdQmRpEAfazeg1nWBy89g.b['58'][2]++,!self.tbodyNode)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['58'][3]++,!self.tbodyNode.inDoc())){__cov_lwdQmRpEAfazeg1nWBy89g.b['57'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['132']++;self._restripeTask=null;__cov_lwdQmRpEAfazeg1nWBy89g.s['133']++;return;}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['57'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['134']++;var odd=[self.CLASS_ODD,self.CLASS_EVEN],even=[self.CLASS_EVEN,self.CLASS_ODD],index=self._restripeTask.index;__cov_lwdQmRpEAfazeg1nWBy89g.s['135']++;self.tbodyNode.get('childNodes').slice(index).each(function(row,i){__cov_lwdQmRpEAfazeg1nWBy89g.f['16']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['136']++;row.replaceClass.apply(row,(index+i)%2?(__cov_lwdQmRpEAfazeg1nWBy89g.b['59'][0]++,even):(__cov_lwdQmRpEAfazeg1nWBy89g.b['59'][1]++,odd));});__cov_lwdQmRpEAfazeg1nWBy89g.s['137']++;self._restripeTask=null;},0),index:index};}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['56'][1]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['138']++;task.index=Math.min(task.index,index);}},_afterModelListChange:function(){__cov_lwdQmRpEAfazeg1nWBy89g.f['17']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['139']++;var handles=this._eventHandles;__cov_lwdQmRpEAfazeg1nWBy89g.s['140']++;if(handles.dataChange){__cov_lwdQmRpEAfazeg1nWBy89g.b['60'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['141']++;handles.dataChange.detach();__cov_lwdQmRpEAfazeg1nWBy89g.s['142']++;delete handles.dataChange;__cov_lwdQmRpEAfazeg1nWBy89g.s['143']++;this.bindUI();}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['60'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['144']++;if(this.tbodyNode){__cov_lwdQmRpEAfazeg1nWBy89g.b['61'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['145']++;this.render();}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['61'][1]++;}},_applyNodeFormatters:function(tbody,displayCols){__cov_lwdQmRpEAfazeg1nWBy89g.f['18']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['146']++;var host=(__cov_lwdQmRpEAfazeg1nWBy89g.b['62'][0]++,this.host)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['62'][1]++,this),data=this.get('modelList'),formatters=[],linerQuery='.'+this.getClassName('liner'),rows,i,len;__cov_lwdQmRpEAfazeg1nWBy89g.s['147']++;for(i=0,len=displayCols.length;i<len;++i){__cov_lwdQmRpEAfazeg1nWBy89g.s['148']++;if(displayCols[i].nodeFormatter){__cov_lwdQmRpEAfazeg1nWBy89g.b['63'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['149']++;formatters.push(i);}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['63'][1]++;}}__cov_lwdQmRpEAfazeg1nWBy89g.s['150']++;if((__cov_lwdQmRpEAfazeg1nWBy89g.b['65'][0]++,data)&&(__cov_lwdQmRpEAfazeg1nWBy89g.b['65'][1]++,formatters.length)){__cov_lwdQmRpEAfazeg1nWBy89g.b['64'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['151']++;rows=tbody.get('childNodes');__cov_lwdQmRpEAfazeg1nWBy89g.s['152']++;data.each(function(record,index){__cov_lwdQmRpEAfazeg1nWBy89g.f['19']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['153']++;var formatterData={data:record.toJSON(),record:record,rowIndex:index},row=rows.item(index),i,len,col,key,cells,cell,keep;__cov_lwdQmRpEAfazeg1nWBy89g.s['154']++;if(row){__cov_lwdQmRpEAfazeg1nWBy89g.b['66'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['155']++;cells=row.get('childNodes');__cov_lwdQmRpEAfazeg1nWBy89g.s['156']++;for(i=0,len=formatters.length;i<len;++i){__cov_lwdQmRpEAfazeg1nWBy89g.s['157']++;cell=cells.item(formatters[i]);__cov_lwdQmRpEAfazeg1nWBy89g.s['158']++;if(cell){__cov_lwdQmRpEAfazeg1nWBy89g.b['67'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['159']++;col=formatterData.column=displayCols[formatters[i]];__cov_lwdQmRpEAfazeg1nWBy89g.s['160']++;key=(__cov_lwdQmRpEAfazeg1nWBy89g.b['68'][0]++,col.key)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['68'][1]++,col.id);__cov_lwdQmRpEAfazeg1nWBy89g.s['161']++;formatterData.value=record.get(key);__cov_lwdQmRpEAfazeg1nWBy89g.s['162']++;formatterData.td=cell;__cov_lwdQmRpEAfazeg1nWBy89g.s['163']++;formatterData.cell=(__cov_lwdQmRpEAfazeg1nWBy89g.b['69'][0]++,cell.one(linerQuery))||(__cov_lwdQmRpEAfazeg1nWBy89g.b['69'][1]++,cell);__cov_lwdQmRpEAfazeg1nWBy89g.s['164']++;keep=col.nodeFormatter.call(host,formatterData);__cov_lwdQmRpEAfazeg1nWBy89g.s['165']++;if(keep===false){__cov_lwdQmRpEAfazeg1nWBy89g.b['70'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['166']++;cell.destroy(true);}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['70'][1]++;}}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['67'][1]++;}}}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['66'][1]++;}});}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['64'][1]++;}},bindUI:function(){__cov_lwdQmRpEAfazeg1nWBy89g.f['20']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['167']++;var handles=this._eventHandles,modelList=this.get('modelList'),changeEvent=modelList.model.NAME+':change';__cov_lwdQmRpEAfazeg1nWBy89g.s['168']++;if(!handles.columnsChange){__cov_lwdQmRpEAfazeg1nWBy89g.b['71'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['169']++;handles.columnsChange=this.after('columnsChange',bind('_afterColumnsChange',this));}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['71'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['170']++;if((__cov_lwdQmRpEAfazeg1nWBy89g.b['73'][0]++,modelList)&&(__cov_lwdQmRpEAfazeg1nWBy89g.b['73'][1]++,!handles.dataChange)){__cov_lwdQmRpEAfazeg1nWBy89g.b['72'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['171']++;handles.dataChange=modelList.after(['add','remove','reset',changeEvent],bind('_afterDataChange',this));}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['72'][1]++;}},_createDataHTML:function(displayCols){__cov_lwdQmRpEAfazeg1nWBy89g.f['21']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['172']++;var data=this.get('modelList'),html='';__cov_lwdQmRpEAfazeg1nWBy89g.s['173']++;if(data){__cov_lwdQmRpEAfazeg1nWBy89g.b['74'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['174']++;data.each(function(model,index){__cov_lwdQmRpEAfazeg1nWBy89g.f['22']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['175']++;html+=this._createRowHTML(model,index,displayCols);},this);}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['74'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['176']++;return html;},_createRowHTML:function(model,index,displayCols){__cov_lwdQmRpEAfazeg1nWBy89g.f['23']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['177']++;var data=model.toJSON(),clientId=model.get('clientId'),values={rowId:this._getRowId(clientId),clientId:clientId,rowClass:index%2?(__cov_lwdQmRpEAfazeg1nWBy89g.b['75'][0]++,this.CLASS_ODD):(__cov_lwdQmRpEAfazeg1nWBy89g.b['75'][1]++,this.CLASS_EVEN)},host=(__cov_lwdQmRpEAfazeg1nWBy89g.b['76'][0]++,this.host)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['76'][1]++,this),i,len,col,token,value,formatterData;__cov_lwdQmRpEAfazeg1nWBy89g.s['178']++;for(i=0,len=displayCols.length;i<len;++i){__cov_lwdQmRpEAfazeg1nWBy89g.s['179']++;col=displayCols[i];__cov_lwdQmRpEAfazeg1nWBy89g.s['180']++;value=data[col.key];__cov_lwdQmRpEAfazeg1nWBy89g.s['181']++;token=(__cov_lwdQmRpEAfazeg1nWBy89g.b['77'][0]++,col._id)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['77'][1]++,col.key);__cov_lwdQmRpEAfazeg1nWBy89g.s['182']++;values[token+'-className']='';__cov_lwdQmRpEAfazeg1nWBy89g.s['183']++;if(col._formatterFn){__cov_lwdQmRpEAfazeg1nWBy89g.b['78'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['184']++;formatterData={value:value,data:data,column:col,record:model,className:'',rowClass:'',rowIndex:index};__cov_lwdQmRpEAfazeg1nWBy89g.s['185']++;value=col._formatterFn.call(host,formatterData);__cov_lwdQmRpEAfazeg1nWBy89g.s['186']++;if(value===undefined){__cov_lwdQmRpEAfazeg1nWBy89g.b['79'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['187']++;value=formatterData.value;}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['79'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['188']++;values[token+'-className']=formatterData.className;__cov_lwdQmRpEAfazeg1nWBy89g.s['189']++;values.rowClass+=' '+formatterData.rowClass;}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['78'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['190']++;if((__cov_lwdQmRpEAfazeg1nWBy89g.b['81'][0]++,!values.hasOwnProperty(token))||(__cov_lwdQmRpEAfazeg1nWBy89g.b['81'][1]++,data.hasOwnProperty(col.key))){__cov_lwdQmRpEAfazeg1nWBy89g.b['80'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['191']++;if((__cov_lwdQmRpEAfazeg1nWBy89g.b['83'][0]++,value===undefined)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['83'][1]++,value===null)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['83'][2]++,value==='')){__cov_lwdQmRpEAfazeg1nWBy89g.b['82'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['192']++;value=(__cov_lwdQmRpEAfazeg1nWBy89g.b['84'][0]++,col.emptyCellValue)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['84'][1]++,'');}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['82'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['193']++;values[token]=col.allowHTML?(__cov_lwdQmRpEAfazeg1nWBy89g.b['85'][0]++,value):(__cov_lwdQmRpEAfazeg1nWBy89g.b['85'][1]++,htmlEscape(value));}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['80'][1]++;}}__cov_lwdQmRpEAfazeg1nWBy89g.s['194']++;values.rowClass=values.rowClass.replace(/\s+/g,' ');__cov_lwdQmRpEAfazeg1nWBy89g.s['195']++;return fromTemplate(this._rowTemplate,values);},_getRowIndex:function(row){__cov_lwdQmRpEAfazeg1nWBy89g.f['24']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['196']++;var tbody=this.tbodyNode,index=1;__cov_lwdQmRpEAfazeg1nWBy89g.s['197']++;if((__cov_lwdQmRpEAfazeg1nWBy89g.b['87'][0]++,tbody)&&(__cov_lwdQmRpEAfazeg1nWBy89g.b['87'][1]++,row)){__cov_lwdQmRpEAfazeg1nWBy89g.b['86'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['198']++;if(row.ancestor('tbody')!==tbody){__cov_lwdQmRpEAfazeg1nWBy89g.b['88'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['199']++;return null;}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['88'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['200']++;while(row=row.previous()){__cov_lwdQmRpEAfazeg1nWBy89g.s['201']++;index++;}}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['86'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['202']++;return index;},_createRowTemplate:function(displayCols){__cov_lwdQmRpEAfazeg1nWBy89g.f['25']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['203']++;var html='',cellTemplate=this.CELL_TEMPLATE,i,len,col,key,token,headers,tokenValues,formatter;__cov_lwdQmRpEAfazeg1nWBy89g.s['204']++;this._setColumnsFormatterFn(displayCols);__cov_lwdQmRpEAfazeg1nWBy89g.s['205']++;for(i=0,len=displayCols.length;i<len;++i){__cov_lwdQmRpEAfazeg1nWBy89g.s['206']++;col=displayCols[i];__cov_lwdQmRpEAfazeg1nWBy89g.s['207']++;key=col.key;__cov_lwdQmRpEAfazeg1nWBy89g.s['208']++;token=(__cov_lwdQmRpEAfazeg1nWBy89g.b['89'][0]++,col._id)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['89'][1]++,key);__cov_lwdQmRpEAfazeg1nWBy89g.s['209']++;formatter=col._formatterFn;__cov_lwdQmRpEAfazeg1nWBy89g.s['210']++;headers=((__cov_lwdQmRpEAfazeg1nWBy89g.b['91'][0]++,col._headers)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['91'][1]++,[])).length>1?(__cov_lwdQmRpEAfazeg1nWBy89g.b['90'][0]++,'headers="'+col._headers.join(' ')+'"'):(__cov_lwdQmRpEAfazeg1nWBy89g.b['90'][1]++,'');__cov_lwdQmRpEAfazeg1nWBy89g.s['211']++;tokenValues={content:'{'+token+'}',headers:headers,className:this.getClassName('col',token)+' '+((__cov_lwdQmRpEAfazeg1nWBy89g.b['92'][0]++,col.className)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['92'][1]++,''))+' '+this.getClassName('cell')+' {'+token+'-className}'};__cov_lwdQmRpEAfazeg1nWBy89g.s['212']++;if((__cov_lwdQmRpEAfazeg1nWBy89g.b['94'][0]++,!formatter)&&(__cov_lwdQmRpEAfazeg1nWBy89g.b['94'][1]++,col.formatter)){__cov_lwdQmRpEAfazeg1nWBy89g.b['93'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['213']++;tokenValues.content=col.formatter.replace(valueRegExp,tokenValues.content);}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['93'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['214']++;if(col.nodeFormatter){__cov_lwdQmRpEAfazeg1nWBy89g.b['95'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['215']++;tokenValues.content='';}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['95'][1]++;}__cov_lwdQmRpEAfazeg1nWBy89g.s['216']++;html+=fromTemplate((__cov_lwdQmRpEAfazeg1nWBy89g.b['96'][0]++,col.cellTemplate)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['96'][1]++,cellTemplate),tokenValues);}__cov_lwdQmRpEAfazeg1nWBy89g.s['217']++;this._rowTemplate=fromTemplate(this.ROW_TEMPLATE,{content:html});},_setColumnsFormatterFn:function(displayCols){__cov_lwdQmRpEAfazeg1nWBy89g.f['26']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['218']++;var Formatters=Y.DataTable.BodyView.Formatters,formatter,col,i,len;__cov_lwdQmRpEAfazeg1nWBy89g.s['219']++;for(i=0,len=displayCols.length;i<len;i++){__cov_lwdQmRpEAfazeg1nWBy89g.s['220']++;col=displayCols[i];__cov_lwdQmRpEAfazeg1nWBy89g.s['221']++;formatter=col.formatter;__cov_lwdQmRpEAfazeg1nWBy89g.s['222']++;if((__cov_lwdQmRpEAfazeg1nWBy89g.b['98'][0]++,!col._formatterFn)&&(__cov_lwdQmRpEAfazeg1nWBy89g.b['98'][1]++,formatter)){__cov_lwdQmRpEAfazeg1nWBy89g.b['97'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['223']++;if(Lang.isFunction(formatter)){__cov_lwdQmRpEAfazeg1nWBy89g.b['99'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['224']++;col._formatterFn=formatter;}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['99'][1]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['225']++;if(formatter in Formatters){__cov_lwdQmRpEAfazeg1nWBy89g.b['100'][0]++;__cov_lwdQmRpEAfazeg1nWBy89g.s['226']++;col._formatterFn=Formatters[formatter].call((__cov_lwdQmRpEAfazeg1nWBy89g.b['101'][0]++,this.host)||(__cov_lwdQmRpEAfazeg1nWBy89g.b['101'][1]++,this),col);}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['100'][1]++;}}}else{__cov_lwdQmRpEAfazeg1nWBy89g.b['97'][1]++;}}__cov_lwdQmRpEAfazeg1nWBy89g.s['227']++;return displayCols;},_createTBodyNode:function(){__cov_lwdQmRpEAfazeg1nWBy89g.f['27']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['228']++;return Y.Node.create(fromTemplate(this.TBODY_TEMPLATE,{className:this.getClassName('data')}));},destructor:function(){__cov_lwdQmRpEAfazeg1nWBy89g.f['28']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['229']++;new Y.EventHandle(YObject.values(this._eventHandles)).detach();},_getRowId:function(clientId){__cov_lwdQmRpEAfazeg1nWBy89g.f['29']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['230']++;return(__cov_lwdQmRpEAfazeg1nWBy89g.b['102'][0]++,this._idMap[clientId])||(__cov_lwdQmRpEAfazeg1nWBy89g.b['102'][1]++,this._idMap[clientId]=Y.guid());},initializer:function(config){__cov_lwdQmRpEAfazeg1nWBy89g.f['30']++;__cov_lwdQmRpEAfazeg1nWBy89g.s['231']++;this.host=config.host;__cov_lwdQmRpEAfazeg1nWBy89g.s['232']++;this._eventHandles={modelListChange:this.after('modelListChange',bind('_afterModelListChange',this))};__cov_lwdQmRpEAfazeg1nWBy89g.s['233']++;this._idMap={};__cov_lwdQmRpEAfazeg1nWBy89g.s['234']++;this.CLASS_ODD=this.getClassName('odd');__cov_lwdQmRpEAfazeg1nWBy89g.s['235']++;this.CLASS_EVEN=this.getClassName('even');}},{Formatters:{}});},'@VERSION@',{'requires':['datatable-core','view','classnamemanager']});
|
node_modules/react-bootstrap/es/Popover.js | ProjectSunday/rooibus | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import isRequiredForA11y from 'react-prop-types/lib/isRequiredForA11y';
import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
/**
* An html id attribute, necessary for accessibility
* @type {string}
* @required
*/
id: isRequiredForA11y(React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number])),
/**
* Sets the direction the Popover is positioned towards.
*/
placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
/**
* The "top" position value for the Popover.
*/
positionTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]),
/**
* The "left" position value for the Popover.
*/
positionLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]),
/**
* The "top" position value for the Popover arrow.
*/
arrowOffsetTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]),
/**
* The "left" position value for the Popover arrow.
*/
arrowOffsetLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]),
/**
* Title content
*/
title: React.PropTypes.node
};
var defaultProps = {
placement: 'right'
};
var Popover = function (_React$Component) {
_inherits(Popover, _React$Component);
function Popover() {
_classCallCheck(this, Popover);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Popover.prototype.render = function render() {
var _extends2;
var _props = this.props,
placement = _props.placement,
positionTop = _props.positionTop,
positionLeft = _props.positionLeft,
arrowOffsetTop = _props.arrowOffsetTop,
arrowOffsetLeft = _props.arrowOffsetLeft,
title = _props.title,
className = _props.className,
style = _props.style,
children = _props.children,
props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'title', 'className', 'style', 'children']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2));
var outerStyle = _extends({
display: 'block',
top: positionTop,
left: positionLeft
}, style);
var arrowStyle = {
top: arrowOffsetTop,
left: arrowOffsetLeft
};
return React.createElement(
'div',
_extends({}, elementProps, {
role: 'tooltip',
className: classNames(className, classes),
style: outerStyle
}),
React.createElement('div', { className: 'arrow', style: arrowStyle }),
title && React.createElement(
'h3',
{ className: prefix(bsProps, 'title') },
title
),
React.createElement(
'div',
{ className: prefix(bsProps, 'content') },
children
)
);
};
return Popover;
}(React.Component);
Popover.propTypes = propTypes;
Popover.defaultProps = defaultProps;
export default bsClass('popover', Popover); |
src/todo/todo.js | corgisamurai/spary_react | import React from 'react'
import { Component } from 'react'
import TodoInput from './input'
import TodoList from './list'
class Todo extends Component {
constructor(props) {
super(props);
this.state = {todos: this.props.initialTodos};
}
onAddToDo(newTodo){
this.setState({
todos : this.state.todos.concat([{todo:newTodo}])
});
}
onDeleteToDo(i){
alert(`${i}番目を削除`)
this.state.todos.splice(i, 1)
this.setState({
todos : this.state.todos
});
}
render () {
return (
<div>
<TodoInput onAddToDo={this.onAddToDo.bind(this)}/>
<TodoList onDeleteToDo={this.onDeleteToDo.bind(this)} todos={this.state.todos}/>
</div>
)
}
}
export default Todo
|
src/svg-icons/maps/tram.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsTram = (props) => (
<SvgIcon {...props}>
<path d="M19 16.94V8.5c0-2.79-2.61-3.4-6.01-3.49l.76-1.51H17V2H7v1.5h4.75l-.76 1.52C7.86 5.11 5 5.73 5 8.5v8.44c0 1.45 1.19 2.66 2.59 2.97L6 21.5v.5h2.23l2-2H14l2 2h2v-.5L16.5 20h-.08c1.69 0 2.58-1.37 2.58-3.06zm-7 1.56c-.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.5zm5-4.5H7V9h10v5z"/>
</SvgIcon>
);
MapsTram = pure(MapsTram);
MapsTram.displayName = 'MapsTram';
MapsTram.muiName = 'SvgIcon';
export default MapsTram;
|
actor-apps/app-web/src/app/index.js | liruqi/actor-platform | import polyfills from 'utils/polyfills'; // eslint-disable-line
import RouterContainer from 'utils/RouterContainer';
import crosstab from 'crosstab';
import React from 'react';
import Router from 'react-router';
import Raven from 'utils/Raven'; // eslint-disable-line
import isMobile from 'utils/IsMobile';
import ReactMixin from 'react-mixin';
import Intl from 'intl'; // eslint-disable-line
import LocaleData from 'intl/locale-data/jsonp/en-US'; // eslint-disable-line
import { IntlMixin } from 'react-intl';
import injectTapEventPlugin from 'react-tap-event-plugin';
import LoginStore from 'stores/LoginStore';
import PreferencesStore from 'stores/PreferencesStore';
import LoginActionCreators from 'actions/LoginActionCreators';
import PreferencesActionCreators from 'actions/PreferencesActionCreators';
import Deactivated from 'components/Deactivated.react';
import Login from 'components/Login.react';
import Main from 'components/Main.react';
import JoinGroup from 'components/JoinGroup.react';
import Install from 'components/Install.react';
//import AppCache from 'utils/AppCache'; // eslint-disable-line
import Pace from 'pace';
Pace.start({
ajax: false,
restartOnRequestAfter: false,
restartOnPushState: false
});
const DefaultRoute = Router.DefaultRoute;
const Route = Router.Route;
const RouteHandler = Router.RouteHandler;
const ActorInitEvent = 'concurrentActorInit';
if (crosstab.supported) {
crosstab.on(ActorInitEvent, (msg) => {
if (msg.origin !== crosstab.id && window.location.hash !== '#/deactivated') {
window.location.assign('#/deactivated');
window.location.reload();
}
});
}
// Check for mobile device, and force users to install native apps.
if (isMobile() && window.location.hash !== '#/install') {
window.location.assign('#/install');
document.body.classList.add('overflow');
} else if (window.location.hash === '#/install') {
window.location.assign('/');
}
@ReactMixin.decorate(IntlMixin)
class App extends React.Component {
render() {
return <RouteHandler/>;
}
}
// Internationalisation
let intlData;
PreferencesStore.addChangeListener(() => {
intlData = PreferencesStore.languageData;
});
PreferencesActionCreators.load();
const initReact = () => {
if (window.location.hash !== '#/deactivated') {
if (crosstab.supported) {
crosstab.broadcast(ActorInitEvent, {});
}
if (location.pathname === '/app/index.html') {
window.messenger = new window.actor.ActorApp(['ws://' + location.hostname + ':9080/']);
} else {
window.messenger = new window.actor.ActorApp();
}
}
const routes = (
<Route handler={App} name="app" path="/">
<Route handler={Main} name="main" path="/im/:id"/>
<Route handler={JoinGroup} name="join" path="/join/:token"/>
<Route handler={Login} name="login" path="/auth"/>
<Route handler={Deactivated} name="deactivated" path="/deactivated"/>
<Route handler={Install} name="install" path="/install"/>
<DefaultRoute handler={Main}/>
</Route>
);
const router = Router.create(routes, Router.HashLocation);
RouterContainer.set(router);
router.run((Root) => {
injectTapEventPlugin();
React.render(<Root {...intlData}/>, document.getElementById('actor-web-app'));
});
if (window.location.hash !== '#/deactivated') {
if (LoginStore.isLoggedIn()) {
LoginActionCreators.setLoggedIn(router, {redirect: false});
}
}
};
window.jsAppLoaded = () => {
setTimeout(initReact, 0);
};
|
packages/theme-patternfly-org/components/gdprBanner/gdprBanner.js | patternfly/patternfly-org | import React from 'react';
import { Button } from '@patternfly/react-core';
import TimesIcon from '@patternfly/react-icons/dist/esm/icons/times-icon';
import './gdprBanner.css';
export const GdprBanner = () => {
const initialBannerOpen = typeof window !== 'undefined' && window.localStorage && !localStorage.getItem('gdpr-banner-closed');
const [ isBannerOpen, setBannerOpen ] = React.useState(initialBannerOpen);
const closeBanner = () => {
localStorage.setItem('gdpr-banner-closed', 'true');
setBannerOpen(false);
}
return !isBannerOpen ? null : (
<div className="ws-gdpr-banner-container pf-l-flex">
<div id="ws-gdpr-banner" className="pf-l-flex pf-u-py-md pf-m-align-items-center">
<p id="ws-gdpr-banner-text" className="pf-u-ml-xl">
We use cookies on our websites to deliver our online services.
Details about how we use cookies and how you may disable them are set out in our <a href="//www.redhat.com/en/about/privacy-policy">Privacy Statement</a>.
By using this website you agree to our use of cookies.
</p>
<div className="pf-m-align-self-flex-start">
<Button variant="plain" aria-label="Close banner" onClick={closeBanner}>
<TimesIcon />
</Button>
</div>
</div>
</div>
);
}
|
2017-03-07/webpack.config.js | KamilSzot/365_programs | var webpack = require('webpack');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var path = require('path');
module.exports = {
entry: [
'./src/app.tsx',
],
// Output the bundled JS to dist/app.js
output: {
filename: 'app.js',
path: path.resolve(__dirname, 'dist')
},
module: {
loaders: [{
test: /\.ts(x?)$/,
exclude: /node_modules/,
loader: 'babel-loader?presets[]=es2016&presets[]=es2015&presets[]=react!ts-loader'
}, {
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2016', 'es2015', 'react']
}
}, { test: /\.css/, loader: 'style-loader!css-loader' },]
},
devtool: 'source-map',
devServer: {
contentBase: path.resolve(__dirname, 'dist'),
inline: true
},
plugins: [
new CopyWebpackPlugin([
{ from: 'src/index.html' }
])
]
}; |
ajax/libs/jquery/1.11.0-rc1/jquery.js | mitsuruog/cdnjs | /*!
* jQuery JavaScript Library v1.11.0-rc1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-01-16T20:28Z
*/
(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper window is present,
// execute the factory and get jQuery
// For environments that do not inherently posses a window with a document
// (such as Node.js), expose a jQuery-making factory as module.exports
// This accentuates the need for the creation of a real window
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//
var deletedIds = [];
var slice = deletedIds.slice;
var concat = deletedIds.concat;
var push = deletedIds.push;
var indexOf = deletedIds.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var trim = "".trim;
var support = {};
var
version = "1.11.0-rc1",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num != null ?
// Return a 'clean' array
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return just the object
slice.call( this );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: deletedIds.sort,
splice: deletedIds.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
return obj - parseFloat( obj ) >= 0;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
isPlainObject: function( obj ) {
var key;
// 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;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( support.ownLast ) {
for ( key in obj ) {
return hasOwn.call( obj, key );
}
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: trim && !trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( indexOf ) {
return 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 len = +second.length,
j = 0,
i = first.length;
while ( j < len ) {
first[ i++ ] = second[ j++ ];
}
// Support: IE<9
// Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)
if ( len !== len ) {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: function() {
return +( new Date() );
},
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v1.10.16
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-01-13
*/
(function( window ) {
var i,
support,
Expr,
getText,
isXML,
compile,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document (jQuery #6963)
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = attrs.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== strundefined && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var hasCompare,
doc = node ? node.ownerDocument || node : preferredDoc,
parent = doc.defaultView;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML( doc );
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
// IE6-8 do not support the defaultView property so parent will be undefined
if ( parent && parent !== parent.top ) {
// IE11 does not have attachEvent, so all must suffer
if ( parent.addEventListener ) {
parent.addEventListener( "unload", function() {
setDocument();
}, false );
} else if ( parent.attachEvent ) {
parent.attachEvent( "onunload", function() {
setDocument();
});
}
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select t=''><option selected=''></option></select>";
// Support: IE8, Opera 10-12
// Nothing should be selected when empty strings follow ^= or $= or *=
if ( div.querySelectorAll("[t^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( div.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] && match[4] !== undefined ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( (tokens = []) );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (oldCache = outerCache[ dir ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
outerCache[ dir ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context !== document && context;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
}
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome<14
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( div ) {
return div.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return elem[ name ] === true ? name.toLowerCase() :
(val = elem.getAttributeNode( name )) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})( window );
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
});
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
};
jQuery.fn.extend({
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
}
});
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function( selector, context ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return typeof rootjQuery.ready !== "undefined" ?
rootjQuery.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.extend({
dir: function( elem, dir, until ) {
var matched = [],
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;
}
});
jQuery.fn.extend({
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;
}
}
});
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return 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 ) {
return this.pushStack(
jQuery.unique(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
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 ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
ret = jQuery.unique( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
ret = ret.reverse();
}
}
return this.pushStack( ret );
};
});
var rnotwhite = (/\S+/g);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !(--remaining) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
}
});
/**
* Clean-up method for dom ready events
*/
function detach() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
}
/**
* The ready event handler and self cleanup method
*/
function completed() {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
var strundefined = typeof undefined;
// Support: IE<9
// Iteration over object's inherited properties before its own
var i;
for ( i in jQuery( support ) ) {
break;
}
support.ownLast = i !== "0";
// Note: most support tests are defined in their respective modules.
// false until the test is run
support.inlineBlockNeedsLayout = false;
jQuery(function() {
// We need to execute this one support test ASAP because we need to know
// if body.style.zoom needs to be set.
var container, div,
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
// Setup
container = document.createElement( "div" );
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
div = document.createElement( "div" );
body.appendChild( container ).appendChild( div );
if ( typeof div.style.zoom !== strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.style.cssText = "border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1";
if ( (support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 )) ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
// Null elements to avoid leaks in IE
container = div = null;
});
(function() {
var div = document.createElement( "div" );
// Execute the test only if not already executed in another module.
if (support.deleteExpando == null) {
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
}
// Null elements to avoid leaks in IE.
div = null;
})();
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function( elem ) {
var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ],
nodeType = +elem.nodeType || 1;
// Do not set data on non-element DOM nodes because it will not be cleared (#8335).
return nodeType !== 1 && nodeType !== 9 ?
false :
// Nodes accept data unless otherwise specified; rejection can be conditional
!noData || noData !== true && elem.getAttribute("classid") === noData;
};
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
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;
}
function internalData( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var ret, thisCache,
internalKey = jQuery.expando,
// 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)) && data === undefined && typeof name === "string" ) {
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 ) {
id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
// Avoid exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
cache[ id ] = isNode ? {} : { 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 ( typeof name === "string" ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
i = name.length;
while ( 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(thisCache) : !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)
/* jshint eqeqeq: false */
} else if ( support.deleteExpando || cache != cache.window ) {
/* jshint eqeqeq: true */
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// The following elements (space-suffixed to avoid Object.prototype collisions)
// throw uncatchable exceptions if you attempt to set expando properties
noData: {
"applet ": true,
"embed ": true,
// ...but Flash objects (which have this classid) *can* handle expandos
"object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var i, name, data,
elem = this[0],
attrs = elem && elem.attributes;
// Special expections of .data basically thwart jQuery.access,
// so implement the relevant behavior ourselves
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
name = attrs[i].name;
if ( name.indexOf("data-") === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return arguments.length > 1 ?
// Sets one value
this.each(function() {
jQuery.data( this, key, value );
}) :
// Gets one value
// Try to fetch any internally stored data first
elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined;
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHidden = function( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
};
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
};
var rcheckableType = (/^(?:checkbox|radio)$/i);
(function() {
var fragment = document.createDocumentFragment(),
div = document.createElement("div"),
input = document.createElement("input");
input.type = "checkbox";
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a>";
// IE strips leading whitespace when .innerHTML is used
support.leadingWhitespace = div.firstChild.nodeType === 3;
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
support.tbody = !div.getElementsByTagName( "tbody" ).length;
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
support.htmlSerialize = !!div.getElementsByTagName( "link" ).length;
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
support.html5Clone =
document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>";
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
fragment.appendChild( input );
support.appendChecked = input.checked;
// #11217 - WebKit loses check when the name is after the checked attribute
fragment.appendChild( div );
div.innerHTML = "<input type='radio' checked='checked' name='t'/>";
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
support.noCloneEvent = true;
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Execute the test only if not already executed in another module.
if (support.deleteExpando == null) {
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
}
// Null elements to avoid leaks in IE.
fragment = div = input = null;
})();
(function() {
var i, eventName,
div = document.createElement( "div" );
// Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event)
for ( i in { submit: true, change: true, focusin: true }) {
eventName = "on" + i;
if ( !(support[ i + "Bubbles" ] = eventName in window) ) {
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
div.setAttribute( eventName, "t" );
support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false;
}
}
// Null elements to avoid leaks in IE.
div = null;
})();
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && jQuery.acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Even when returnValue equals to undefined Firefox will still show alert
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined && (
// Support: IE < 9
src.returnValue === false ||
// Support: Android < 4.0
src.getPreventDefault && src.getPreventDefault() ) ?
returnTrue :
returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
jQuery._data( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
jQuery._removeData( doc, fix );
} else {
jQuery._data( doc, fix, attaches );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
// Support: IE<8
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!support.noCloneEvent || !support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
deletedIds.push( id );
}
}
}
}
}
});
jQuery.fn.extend({
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
remove: function( selector, keepData /* Internal Use Only */ ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map(function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var arg = arguments[ 0 ];
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
arg = this.parentNode;
jQuery.cleanData( getAll( this ) );
if ( arg ) {
arg.replaceChild( elem, this );
}
});
// Force removal if there was no new content (e.g., from empty arguments)
return arg && (arg.length || arg.nodeType) ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction ||
( l > 1 && typeof value === "string" &&
!support.checkClone && rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, self.html() );
}
self.domManip( args, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[i], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
var iframe,
elemdisplay = {};
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
// getDefaultComputedStyle might be reliably used only on attached element
display = window.getDefaultComputedStyle ?
// Use of this method is a temporary fix (more like optmization) until something better comes along,
// since it was removed from specification and supported only in FF
window.getDefaultComputedStyle( elem[ 0 ] ).display : jQuery.css( elem[ 0 ], "display" );
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
/**
* Try to determine the default display value of an element
* @param {String} nodeName
*/
function defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
(function() {
var a, shrinkWrapBlocksVal,
div = document.createElement( "div" ),
divReset =
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;" +
"display:block;padding:0;margin:0;border:0";
// Setup
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName( "a" )[ 0 ];
a.style.cssText = "float:left;opacity:.5";
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
support.opacity = /^0.5/.test( a.style.opacity );
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!a.style.cssFloat;
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Null elements to avoid leaks in IE.
a = div = null;
support.shrinkWrapBlocks = function() {
var body, container, div, containerStyles;
if ( shrinkWrapBlocksVal == null ) {
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
containerStyles = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px";
container = document.createElement( "div" );
div = document.createElement( "div" );
body.appendChild( container ).appendChild( div );
// Will be changed later if needed.
shrinkWrapBlocksVal = false;
if ( typeof div.style.zoom !== strundefined ) {
// Support: IE6
// Check if elements with layout shrink-wrap their children
div.style.cssText = divReset + ";width:1px;padding:1px;zoom:1";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
shrinkWrapBlocksVal = div.offsetWidth !== 3;
}
body.removeChild( container );
// Null elements to avoid leaks in IE.
body = container = div = null;
}
return shrinkWrapBlocksVal;
};
})();
var rmargin = (/^margin/);
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles, curCSS,
rposition = /^(top|right|bottom|left)$/;
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
};
curCSS = function( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "";
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, computed ) {
var left, rs, rsLeft, ret,
style = elem.style;
computed = computed || getStyles( elem );
ret = computed ? computed[ name ] : undefined;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "" || "auto";
};
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
var condition = conditionFn();
if ( condition == null ) {
// The test was not ready at this point; screw the hook this time
// but check again when needed next time.
return;
}
if ( condition ) {
// Hook not needed (or it's not possible to use it due to missing dependency),
// remove it.
// Since there are no other hooks for marginRight, remove the whole object.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return (this.get = hookFn).apply( this, arguments );
}
};
}
(function() {
var a, reliableHiddenOffsetsVal, boxSizingVal, boxSizingReliableVal,
pixelPositionVal, reliableMarginRightVal,
div = document.createElement( "div" ),
containerStyles = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px",
divReset =
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;" +
"display:block;padding:0;margin:0;border:0";
// Setup
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName( "a" )[ 0 ];
a.style.cssText = "float:left;opacity:.5";
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
support.opacity = /^0.5/.test( a.style.opacity );
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!a.style.cssFloat;
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Null elements to avoid leaks in IE.
a = div = null;
jQuery.extend(support, {
reliableHiddenOffsets: function() {
if ( reliableHiddenOffsetsVal != null ) {
return reliableHiddenOffsetsVal;
}
var container, tds, isSupported,
div = document.createElement( "div" ),
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
container = document.createElement( "div" );
container.style.cssText = containerStyles;
body.appendChild( container ).appendChild( div );
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName( "td" );
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Support: IE8
// Check if empty table cells still have offsetWidth/Height
reliableHiddenOffsetsVal = isSupported && ( tds[ 0 ].offsetHeight === 0 );
body.removeChild( container );
// Null elements to avoid leaks in IE.
div = body = null;
return reliableHiddenOffsetsVal;
},
boxSizing: function() {
if ( boxSizingVal == null ) {
computeStyleTests();
}
return boxSizingVal;
},
boxSizingReliable: function() {
if ( boxSizingReliableVal == null ) {
computeStyleTests();
}
return boxSizingReliableVal;
},
pixelPosition: function() {
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return pixelPositionVal;
},
reliableMarginRight: function() {
var body, container, div, marginDiv;
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( reliableMarginRightVal == null && window.getComputedStyle ) {
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
container = document.createElement( "div" );
div = document.createElement( "div" );
container.style.cssText = containerStyles;
body.appendChild( container ).appendChild( div );
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement( "div" ) );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
reliableMarginRightVal =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
body.removeChild( container );
}
return reliableMarginRightVal;
}
});
function computeStyleTests() {
var container, div,
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
container = document.createElement( "div" );
div = document.createElement( "div" );
container.style.cssText = containerStyles;
body.appendChild( container ).appendChild( div );
div.style.cssText =
"-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;" +
"position:absolute;display:block;padding:1px;border:1px;width:4px;" +
"margin-top:1%;top:1%";
// Workaround failing boxSizing test due to offsetWidth returning wrong value
// with some non-1 values of body zoom, ticket #13543
jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() {
boxSizingVal = div.offsetWidth === 4;
});
// Will be changed later if needed.
boxSizingReliableVal = true;
pixelPositionVal = false;
reliableMarginRightVal = true;
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
boxSizingReliableVal =
( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
}
body.removeChild( container );
// Null elements to avoid leaks in IE.
div = body = null;
}
})();
// A method for quickly swapping in/out CSS properties to get correct calculations.
jQuery.swap = function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
};
var
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.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 showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
} else {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = support.boxSizing() && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": 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 null and NaN values aren't set. See: #7116
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Support: IE
// Swallow errors from 'invalid' CSS values (#5509)
try {
// Support: Chrome, Safari
// Setting style to blank string required to delete "style: x !important;"
style[ name ] = "";
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
support.boxSizing() && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
jQuery.fn.extend({
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
}
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
} ]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween( value, prop, animation ) {
var tween,
collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( (tween = collection[ index ].call( animation, prop, value )) ) {
// we're done with this property
return tween;
}
}
}
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire, display, dDisplay,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = jQuery._data( elem, "fxshow" );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because 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
display = jQuery.css( elem, "display" );
dDisplay = defaultDisplay( elem.nodeName );
if ( display === "none" ) {
display = dDisplay;
}
if ( display === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !support.inlineBlockNeedsLayout || dDisplay === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !support.shrinkWrapBlocks() ) {
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = jQuery._data( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = jQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.timers = [];
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
jQuery.timers.push( timer );
if ( timer() ) {
jQuery.fx.start();
} else {
jQuery.timers.pop();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
};
(function() {
var a, input, select, opt,
div = document.createElement("div" );
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName("a")[ 0 ];
// First batch of tests.
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px";
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
support.getSetAttribute = div.className !== "t";
// Get the style information from getAttribute
// (IE uses .cssText instead)
support.style = /top/.test( a.getAttribute("style") );
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
support.hrefNormalized = a.getAttribute("href") === "/a";
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
support.checkOn = !!input.value;
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
support.optSelected = opt.selected;
// Tests for enctype support on a form (#6743)
support.enctype = !!document.createElement("form").enctype;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE8 only
// Check if we can trust getAttribute("value")
input = document.createElement( "input" );
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
// Null elements to avoid leaks in IE.
a = input = select = opt = div = null;
})();
var rreturn = /\r/g;
jQuery.fn.extend({
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
jQuery.text( elem );
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) {
// Support: IE6
// When new option element is added to select box we need to
// force reflow of newly added node in order to workaround delay
// of initialization properties
try {
option.selected = optionSet = true;
} catch ( _ ) {
// Will be executed only in IE6
option.scrollHeight;
}
} else {
option.selected = false;
}
}
// Force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return options;
}
}
}
});
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = support.getSetAttribute,
getSetInput = support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
}
});
jQuery.extend({
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
}
});
// Hook for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
// Retrieve booleans specially
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
function( elem, name, isXML ) {
var ret, handle;
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ name ];
attrHandle[ name ] = ret;
ret = getter( elem, name, isXML ) != null ?
name.toLowerCase() :
null;
attrHandle[ name ] = handle;
}
return ret;
} :
function( elem, name, isXML ) {
if ( !isXML ) {
return elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
}
};
});
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
if ( name === "value" || value === elem.getAttribute( name ) ) {
return value;
}
}
};
// Some attributes are constructed with empty-string values when not defined
attrHandle.id = attrHandle.name = attrHandle.coords =
function( elem, name, isXML ) {
var ret;
if ( !isXML ) {
return (ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
}
};
// Fixing value retrieval on a button requires this module
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
if ( ret && ret.specified ) {
return ret.value;
}
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
});
}
if ( !support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
var rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i;
jQuery.fn.extend({
prop: function( name, value ) {
return 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 ) {}
});
}
});
jQuery.extend({
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// 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/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
}
});
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
// Support: Safari, IE9+
// mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !support.optSelected ) {
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;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// IE6/7 call enctype encoding
if ( !support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
addClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
classNames = value.match( rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( type === strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
}
});
// Return jQuery for attributes-only inclusion
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
var nonce = jQuery.now();
var rquery = (/\?/);
var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;
jQuery.parseJSON = function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
// Support: Android 2.3
// Workaround failure to string-cast null input
return window.JSON.parse( data + "" );
}
var requireNonComma,
depth = null,
str = jQuery.trim( data + "" );
// Guard against invalid (and possibly dangerous) input by ensuring that nothing remains
// after removing valid tokens
return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) {
// Force termination if we see a misplaced comma
if ( requireNonComma && comma ) {
depth = 0;
}
// Perform no more replacements after returning to outermost depth
if ( depth === 0 ) {
return token;
}
// Commas must not follow "[", "{", or ","
requireNonComma = open || comma;
// Determine new depth
// array/object open ("[" or "{"): depth += true - false (increment)
// array/object close ("]" or "}"): depth += false - true (decrement)
// other cases ("," or primitive): depth += true - true (numeric cast)
depth += !close - !open;
// Remove this token
return "";
}) ) ?
( Function( "return " + str ) )() :
jQuery.error( "Invalid JSON: " + data );
};
// Cross-browser xml parsing
jQuery.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;
};
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType.charAt( 0 ) === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while ( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s[ "throws" ] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) {
jQuery.fn[ type ] = function( fn ) {
return this.on( type, fn );
};
});
jQuery._evalUrl = function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
};
jQuery.fn.extend({
wrapAll: function( html ) {
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();
}
});
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!support.reliableHiddenOffsets() &&
((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function() {
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
})
.map(function( i, elem ) {
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ?
// Support: IE6+
function() {
// XHR cannot access local files, always use ActiveX for that case
return !this.isLocal &&
// Support: IE7-8
// oldIE XHR does not support non-RFC2616 methods (#13240)
// See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx
// and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9
// Although this check for six methods instead of eight
// since IE also does not support "trace" and "connect"
/^(get|post|head|put|delete|options)$/i.test( this.type ) &&
createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
var xhrId = 0,
xhrCallbacks = {},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE<10
// Open requests must be manually aborted on unload (#5280)
if ( window.ActiveXObject ) {
jQuery( window ).on( "unload", function() {
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
});
}
// Determine support properties
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport(function( options ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !options.crossDomain || support.cors ) {
var callback;
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr(),
id = ++xhrId;
// Open the socket
xhr.open( options.type, options.url, options.async, options.username, options.password );
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !options.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
// Support: IE<9
// IE's ActiveXObject throws a 'Type Mismatch' exception when setting
// request header to a null-value.
//
// To keep consistent with other XHR implementations, cast the value
// to string and ignore `undefined`.
if ( headers[ i ] !== undefined ) {
xhr.setRequestHeader( i, headers[ i ] + "" );
}
}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( options.hasContent && options.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, statusText, responses;
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Clean up
delete xhrCallbacks[ id ];
callback = undefined;
xhr.onreadystatechange = jQuery.noop;
// Abort manually if needed
if ( isAbort ) {
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
// Support: IE<10
// Accessing binary-data responseText throws an exception
// (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && options.isLocal && !options.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, xhr.getAllResponseHeaders() );
}
};
if ( !options.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback );
} else {
// Add to the list of active xhr callbacks
xhr.onreadystatechange = xhrCallbacks[ id ] = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
});
}
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || jQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
// Keep a copy of the old load method
var _load = jQuery.fn.load;
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
var docElem = window.document.documentElement;
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
jQuery.inArray("auto", [ curCSSTop, curCSSLeft ] ) > -1;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
offset: function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 0 ];
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return 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 );
};
});
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
});
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
});
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in
// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( typeof noGlobal === strundefined ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
|
src/components/common/Input.js | brianyamasaki/rideshare | import React from 'react';
import { TextInput, View, Text } from 'react-native';
const Input = ({ label, value, onChangeText, placeholder, secureTextEntry }) => {
const { inputStyle, labelStyle, containerStyle } = styles;
return (
<View style={containerStyle}>
<Text style={labelStyle}>
{label}
</Text>
<TextInput
secureTextEntry={secureTextEntry}
placeholder={placeholder}
autoCorrect={false}
value={value}
onChangeText={onChangeText}
style={inputStyle}
/>
</View>
);
};
const styles = {
inputStyle: {
color: '#000',
paddingRight: 5,
paddingLeft: 5,
fontSize: 18,
lineHeight: 23,
flex: 2
},
labelStyle: {
fontSize: 18,
paddingLeft: 20,
flex: 1
},
containerStyle: {
height: 40,
flex: 1,
flexDirection: 'row',
alignItems: 'center'
}
};
export { Input };
|
ajax/libs/bootswatch/2.0.1/js/jquery.js | bootcdn/cdnjs | /*! jQuery v1.7.1 jquery.com | jquery.org/license */
(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.1",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return slice.call( this, 0 );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = this.constructor();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
} else {
jQuery.merge( ret, elems );
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// Add the callback
readyList.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";
},
// A crude way of determining if an object is a window
isWindow: function( obj ) {
return obj && typeof obj === "object" && "setInterval" in obj;
},
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 ) {
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, key, value, exec, fn, pass ) {
var length = elems.length;
// Setting many attributes
if ( typeof key === "object" ) {
for ( var k in key ) {
jQuery.access( elems, k, key[k], exec, fn, value );
}
return elems;
}
// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
for ( var i = 0; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
return elems;
}
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
},
now: function() {
return ( new Date() ).getTime();
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
},
sub: function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
},
browser: {}
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
jQuery.browser[ browserMatch.browser ] = true;
jQuery.browser.version = browserMatch.version;
}
// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
jQuery.browser.safari = true;
}
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
};
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
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 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 ];
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 !!memory;
}
};
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,
marginDiv,
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
};
// 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");
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 );
div.innerHTML = "";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
if ( window.getComputedStyle ) {
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;
}
// 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 = marginDiv = div = input = null;
// Run tests that need a body at doc ready
jQuery(function() {
var container, outer, inner, table, td, offsetSupport,
conMarginTop, ptlm, vb, style, html,
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
conMarginTop = 1;
ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;";
vb = "visibility:hidden;border:0;";
style = "style='" + ptlm + "border:5px solid #000;padding:0;'";
html = "<div " + style + "><div></div></div>" +
"<table " + style + " cellpadding='0' cellspacing='0'>" +
"<tr><td></td></tr></table>";
container = document.createElement("div");
container.style.cssText = vb + "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='padding:0;border: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 );
// Figure out if the W3C box model works as expected
div.innerHTML = "";
div.style.width = div.style.paddingLeft = "1px";
jQuery.boxModel = support.boxModel = div.offsetWidth === 2;
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.style.display = "inline";
div.style.zoom = 1;
support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "";
div.innerHTML = "<div style='width:4px;'></div>";
support.shrinkWrapBlocks = ( div.offsetWidth !== 2 );
}
div.style.cssText = ptlm + vb;
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 );
body.removeChild( container );
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, attr, name,
data = null;
if ( typeof key === "undefined" ) {
if ( this.length ) {
data = jQuery.data( this[0] );
if ( this[0].nodeType === 1 && !jQuery._data( this[0], "parsedAttrs" ) ) {
attr = this[0].attributes;
for ( var i = 0, l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( this[0], name, data[ name ] );
}
}
jQuery._data( this[0], "parsedAttrs", true );
}
}
return data;
} else if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split(".");
parts[1] = parts[1] ? "." + parts[1] : "";
if ( value === undefined ) {
data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
// Try to fetch any internally stored data first
if ( data === undefined && this.length ) {
data = jQuery.data( this[0], key );
data = dataAttr( this[0], key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
} else {
return this.each(function() {
var self = jQuery( this ),
args = [ parts[0], value ];
self.triggerHandler( "setData" + parts[1] + "!", args );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + parts[1] + "!", args );
});
}
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
jQuery.isNumeric( data ) ? parseFloat( data ) :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// 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 ) {
if ( typeof type !== "string" ) {
data = type;
type = "fx";
}
if ( data === undefined ) {
return jQuery.queue( this[0], type );
}
return this.each(function() {
var queue = jQuery.queue( this, type, data );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( 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();
}
});
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, name, value, true, jQuery.attr );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.prop );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
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.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];
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.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, 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,
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;
// See #9699 for explanation of this approach (setting first, then removal)
jQuery.attr( elem, name, "" );
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( rboolean.test( name ) && 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
};
// 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 = /\bhover(\.\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;
}
// 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: 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,
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;
// Determine handlers that should run if there are delegated events
// Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !event.target.disabled && !(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 ) {
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();
}
}
}
}
}
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 ) {
// If form was submitted by the user, bubble the event up the tree
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
});
form._submit_attached = true;
}
});
// return undefined since we don't need an event listener
},
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" ) {
// ( types-Object, 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.call( this, 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.type + "." + handleObj.namespace : handleObj.type,
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 2012, 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 ) {
// 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;
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) );
}
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.POS,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var self = this,
i, l;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
var ret = this.pushStack( "", "find", selector ),
length, n, r;
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var targets = jQuery( target );
return this.filter(function() {
for ( var i = 0, l = targets.length; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// 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|canvas|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 + ")", "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( text ) {
if ( jQuery.isFunction(text) ) {
return this.each(function(i) {
var self = jQuery( this );
self.text( text.call(this, i, self.text()) );
});
}
if ( typeof text !== "object" && text !== undefined ) {
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
}
return jQuery.text( this );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
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 ) {
if ( value === undefined ) {
return this[0] && this[0].nodeType === 1 ?
this[0].innerHTML.replace(rinlinejQuery, "") :
null;
// See if we can take a shortcut and just use innerHTML
} else if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
value = value.replace(rxhtmlTag, "<$1></$2>");
try {
for ( var i = 0, l = this.length; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
if ( this[i].nodeType === 1 ) {
jQuery.cleanData( this[i].getElementsByTagName("*") );
this[i].innerHTML = value;
}
}
// If using innerHTML throws an exception, use the fallback method
} catch(e) {
this.empty().append( value );
}
} else if ( jQuery.isFunction( value ) ) {
this.each(function(i){
var self = jQuery( this );
self.html( value.call(this, i, self.html()) );
});
} else {
this.empty().append( value );
}
return this;
},
replaceWith: function( value ) {
if ( this[0] && this[0].parentNode ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
} else {
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
}
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
var results, first, fragment, parent,
value = args[0],
scripts = [];
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback, true );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call(this, i, table ? self.html() : undefined);
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
parent = value && value.parentNode;
// If we're in a fragment, just use that instead of building a new one
if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
results = { fragment: parent };
} else {
results = jQuery.buildFragment( args, this, scripts );
}
fragment = results.fragment;
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
first = fragment.firstChild;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
// Make sure that we do not leak memory by inadvertently discarding
// the original fragment (which might have attached data) instead of
// using it; in addition, use the original fragment object for the last
// item instead of first because it can end up being emptied incorrectly
// in certain situations (Bug #8070).
// Fragments from the fragment cache must always be cloned and never used
// in place.
results.cacheable || ( l > 1 && i < lastIndex ) ?
jQuery.clone( fragment, true, true ) :
fragment
);
}
}
if ( scripts.length ) {
jQuery.each( scripts, evalScript );
}
}
return this;
}
});
function root( elem, cur ) {
return jQuery.nodeName(elem, "table") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var 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 ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data );
}
}
}
// 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;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults, doc,
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 || !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;
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if ( typeof context.createElement === "undefined" ) {
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
}
var ret = [], j;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Trim whitespace, otherwise indexOf won't work as expected
var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(),
wrap = wrapMap[ tag ] || wrapMap._default,
depth = wrap[0],
div = context.createElement("div");
// 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;
}
}
// Resets defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
var len;
if ( !jQuery.support.appendChecked ) {
if ( elem[0] && typeof (len = elem.length) === "number" ) {
for ( j = 0; j < len; j++ ) {
findInputs( elem[j] );
}
} else {
findInputs( elem );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
ret = jQuery.merge( ret, elem );
}
}
if ( fragment ) {
checkScriptType = function( elem ) {
return !elem.type || rscriptType.test( elem.type );
};
for ( i = 0; ret[i]; i++ ) {
if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
} else {
if ( ret[i].nodeType === 1 ) {
var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType );
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
}
fragment.appendChild( ret[i] );
}
}
}
return ret;
},
cleanData: function( elems ) {
var data, id,
cache = jQuery.cache,
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 ];
}
}
}
});
function evalScript( i, elem ) {
if ( elem.src ) {
jQuery.ajax({
url: elem.src,
async: false,
dataType: "script"
});
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
var ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
// fixed for IE9, see #8346
rupper = /([A-Z]|^ms)/g,
rnumpx = /^-?\d+(?:px)?$/i,
rnum = /^-?\d/,
rrelNum = /^([\-+])=([\-+.\de]+)/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssWidth = [ "Left", "Right" ],
cssHeight = [ "Top", "Bottom" ],
curCSS,
getComputedStyle,
currentStyle;
jQuery.fn.css = function( name, value ) {
// Setting 'undefined' is a no-op
if ( arguments.length === 2 && value === undefined ) {
return this;
}
return jQuery.access( this, name, value, true, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
});
};
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity", "opacity" );
return ret === "" ? "1" : ret;
} else {
return elem.style.opacity;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"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 = {};
// Remember the old values, and insert the new ones
for ( var name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
}
});
// DEPRECATED, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;
jQuery.each(["height", "width"], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
var val;
if ( computed ) {
if ( elem.offsetWidth !== 0 ) {
return getWH( elem, name, extra );
} else {
jQuery.swap( elem, cssShow, function() {
val = getWH( elem, name, extra );
});
}
return val;
}
},
set: function( elem, value ) {
if ( rnumpx.test( value ) ) {
// ignore negative width and height values #1599
value = parseFloat( value );
if ( value >= 0 ) {
return value + "px";
}
} else {
return value;
}
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( parseFloat( RegExp.$1 ) / 100 ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
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
var ret;
jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
ret = curCSS( elem, "margin-right", "marginRight" );
} else {
ret = elem.style.marginRight;
}
});
return ret;
}
};
}
});
if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, name ) {
var ret, defaultView, computedStyle;
name = name.replace( rupper, "-$1" ).toLowerCase();
if ( (defaultView = elem.ownerDocument.defaultView) &&
(computedStyle = defaultView.getComputedStyle( elem, null )) ) {
ret = computedStyle.getPropertyValue( name );
if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
ret = jQuery.style( elem, name );
}
}
return ret;
};
}
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
var left, 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 ( !rnumpx.test( ret ) && rnum.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 || 0 );
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
curCSS = getComputedStyle || currentStyle;
function getWH( elem, name, extra ) {
// Start with offset property
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
which = name === "width" ? cssWidth : cssHeight,
i = 0,
len = which.length;
if ( val > 0 ) {
if ( extra !== "border" ) {
for ( ; i < len; i++ ) {
if ( !extra ) {
val -= parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0;
} else {
val -= parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0;
}
}
}
return val + "px";
}
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ] || 0;
}
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
// Add padding, border, margin
if ( extra ) {
for ( ; i < len; i++ ) {
val += parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0;
if ( extra !== "padding" ) {
val += parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0;
}
}
}
return val + "px";
}
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 );
};
}
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",
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 prefiler, stop there
if ( state === 2 ) {
return false;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #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" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && obj != null && typeof obj === "object" ) {
// Serialize object item.
for ( var name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields,
ct,
type,
finalDataType,
firstDataType;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
var dataTypes = s.dataTypes,
converters = {},
i,
key,
length = dataTypes.length,
tmp,
// Current and previous dataTypes
current = dataTypes[ 0 ],
prev,
// Conversion expression
conversion,
// Conversion function
conv,
// Conversion functions (transitive conversion)
conv1,
conv2;
// For each dataType in the chain
for ( i = 1; i < length; i++ ) {
// Create converters map
// with lowercased keys
if ( i === 1 ) {
for ( key in s.converters ) {
if ( typeof key === "string" ) {
converters[ key.toLowerCase() ] = s.converters[ key ];
}
}
}
// Get the dataTypes
prev = current;
current = dataTypes[ i ];
// If current is auto dataType, update it to prev
if ( current === "*" ) {
current = prev;
// If no auto and dataTypes are actually different
} else if ( prev !== "*" && prev !== current ) {
// Get the converter
conversion = prev + " " + current;
conv = converters[ conversion ] || converters[ "* " + current ];
// If there is no direct converter, search transitively
if ( !conv ) {
conv2 = undefined;
for ( conv1 in converters ) {
tmp = conv1.split( " " );
if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
conv2 = converters[ tmp[1] + " " + current ];
if ( conv2 ) {
conv1 = converters[ conv1 ];
if ( conv1 === true ) {
conv = conv2;
} else if ( conv2 === true ) {
conv = conv1;
}
break;
}
}
}
}
// If we found no converter, dispatch an error
if ( !( conv || conv2 ) ) {
jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
}
// If found converter is not an equivalence
if ( conv !== true ) {
// Convert with 1 or 2 converters accordingly
response = conv ? conv( response ) : conv2( conv1(response) );
}
}
}
return response;
}
var jsc = jQuery.now(),
jsre = /(\=)\?(&|$)|\?\?/i;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
return jQuery.expando + "_" + ( jsc++ );
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var inspectData = s.contentType === "application/x-www-form-urlencoded" &&
( typeof s.data === "string" );
if ( s.dataTypes[ 0 ] === "jsonp" ||
s.jsonp !== false && ( jsre.test( s.url ) ||
inspectData && jsre.test( s.data ) ) ) {
var responseContainer,
jsonpCallback = s.jsonpCallback =
jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
previous = window[ jsonpCallback ],
url = s.url,
data = s.data,
replace = "$1" + jsonpCallback + "$2";
if ( s.jsonp !== false ) {
url = url.replace( jsre, replace );
if ( s.url === url ) {
if ( inspectData ) {
data = data.replace( jsre, replace );
}
if ( s.data === data ) {
// Add callback manually
url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
}
}
}
s.url = url;
s.data = data;
// Install callback
window[ jsonpCallback ] = function( response ) {
responseContainer = [ response ];
};
// Clean-up function
jqXHR.always(function() {
// Set callback back to previous value
window[ jsonpCallback ] = previous;
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( previous ) ) {
window[ jsonpCallback ]( responseContainer[ 0 ] );
}
});
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( jsonpCallback + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var // #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0,
xhrCallbacks;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var xhr = s.xhr(),
handle,
i;
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occured
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
responses.text = xhr.responseText;
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
// if we're in sync mode or it's in cache
// and has been retrieved directly (IE6 & IE7)
// we need to manually fire the callback
if ( !s.async || xhr.readyState === 4 ) {
callback();
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var elemdisplay = {},
iframe, iframeDoc,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
],
fxNow;
jQuery.fn.extend({
show: function( speed, easing, callback ) {
var elem, display;
if ( speed || speed === 0 ) {
return this.animate( genFx("show", 3), speed, easing, callback );
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
elem = this[ i ];
if ( elem.style ) {
display = elem.style.display;
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
display = elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( display === "" && jQuery.css(elem, "display") === "none" ) {
jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
elem = this[ i ];
if ( elem.style ) {
display = elem.style.display;
if ( display === "" || display === "none" ) {
elem.style.display = jQuery._data( elem, "olddisplay" ) || "";
}
}
}
return this;
}
},
hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
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,
parts, start, end, unit,
method;
// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties = {};
for ( p in prop ) {
// property name normalization
name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
}
val = prop[ name ];
// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
if ( jQuery.isArray( val ) ) {
opt.animatedProperties[ name ] = val[ 1 ];
val = prop[ name ] = val[ 0 ];
} else {
opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
}
if ( val === "hide" && hidden || val === "show" && !hidden ) {
return opt.complete.call( this );
}
if ( isElement && ( name === "height" || name === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
// 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, n, firstNum, diff ) {
return firstNum + diff * p;
},
swing: function( p, n, firstNum, diff ) {
return ( ( -Math.cos( p*Math.PI ) / 2 ) + 0.5 ) * diff + firstNum;
}
},
timers: [],
fx: function( elem, options, prop ) {
this.options = options;
this.elem = elem;
this.prop = prop;
options.orig = options.orig || {};
}
});
jQuery.fx.prototype = {
// Simple function for setting a style value
update: function() {
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this );
},
// Get the current size
cur: function() {
if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) {
return this.elem[ this.prop ];
}
var parsed,
r = jQuery.css( this.elem, this.prop );
// Empty strings, null, undefined and "auto" are converted to 0,
// complex values such as "rotate(1rad)" are returned as is,
// simple values such as "10px" are parsed to Float.
return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
},
// Start an animation from one number to another
custom: function( from, to, unit ) {
var self = this,
fx = jQuery.fx;
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 ( self.options.hide && jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) {
jQuery._data( self.elem, "fxshow" + self.prop, self.start );
}
};
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;
}
}
}
});
// Adds width/height step functions
// Do not set anything below 0
jQuery.each([ "width", "height" ], function( i, prop ) {
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( ( document.compatMode === "CSS1Compat" ? "<!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 rtable = /^t(?:able|d|h)$/i,
rroot = /^(?:body|html)$/i;
if ( "getBoundingClientRect" in document.documentElement ) {
jQuery.fn.offset = function( options ) {
var elem = this[0], box;
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
try {
box = elem.getBoundingClientRect();
} catch(e) {}
var doc = elem.ownerDocument,
docElem = doc.documentElement;
// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
}
var body = doc.body,
win = getWindow(doc),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: top, left: left };
};
} else {
jQuery.fn.offset = function( options ) {
var elem = this[0];
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
var computedStyle,
offsetParent = elem.offsetParent,
prevOffsetParent = elem,
doc = elem.ownerDocument,
docElem = doc.documentElement,
body = doc.body,
defaultView = doc.defaultView,
prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
top = elem.offsetTop,
left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
if ( jQuery.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.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( ["Left", "Top"], function( i, name ) {
var method = "scroll" + name;
jQuery.fn[ method ] = function( val ) {
var elem, win;
if ( val === undefined ) {
elem = this[ 0 ];
if ( !elem ) {
return null;
}
win = getWindow( elem );
// Return the scroll offset
return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ method ] :
elem[ method ];
}
// Set the scroll offset
return this.each(function() {
win = getWindow( this );
if ( win ) {
win.scrollTo(
!i ? val : jQuery( win ).scrollLeft(),
i ? val : jQuery( win ).scrollTop()
);
} else {
this[ method ] = val;
}
});
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function( i, name ) {
var type = name.toLowerCase();
// innerHeight and innerWidth
jQuery.fn[ "inner" + name ] = function() {
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( size ) {
// Get window width or height
var elem = this[0];
if ( !elem ) {
return size == null ? null : this;
}
if ( jQuery.isFunction( size ) ) {
return this.each(function( i ) {
var self = jQuery( this );
self[ type ]( size.call( this, i, self[ type ]() ) );
});
}
if ( jQuery.isWindow( elem ) ) {
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
var docElemProp = elem.document.documentElement[ "client" + name ],
body = elem.document.body;
return elem.document.compatMode === "CSS1Compat" && docElemProp ||
body && body[ "client" + name ] || docElemProp;
// Get document width or height
} else if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
return Math.max(
elem.documentElement["client" + name],
elem.body["scroll" + name], elem.documentElement["scroll" + name],
elem.body["offset" + name], elem.documentElement["offset" + name]
);
// Get or set width or height on the element
} else if ( size === undefined ) {
var orig = jQuery.css( elem, type ),
ret = parseFloat( orig );
return jQuery.isNumeric( ret ) ? ret : orig;
// Set the width or height on the element (default to pixels if value is unitless)
} else {
return this.css( type, typeof size === "string" ? size : size + "px" );
}
};
});
// 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 );
|
tests/client/helpers.js | jasonthomas/addons-frontend | import base64url from 'base64url';
import { sprintf } from 'jed';
import moment from 'moment';
import React from 'react';
import { createRenderer } from 'react-addons-test-utils';
import { EXTENSION_TYPE } from 'core/constants';
import { ngettext } from 'core/utils';
/*
* Return a fake authentication token (a JWT) that can be
* at least decoded like a real JWT.
*/
export function userAuthToken(dataOverrides = {}, { tokenData } = {}) {
const data = {
iss: 'some issuer',
exp: 12345,
iat: 12345,
username: 'some-username',
user_id: 102345,
email: '[email protected]',
...dataOverrides,
};
const algo = base64url.encode('{"example": "of JWT algorithms"}');
let encodedToken = tokenData;
if (!encodedToken) {
encodedToken = base64url.encode(JSON.stringify(data));
}
const sig = base64url.encode('pretend this is a signature of the content');
return `${algo}.${encodedToken}.${sig}`;
}
export function shallowRender(stuff) {
const renderer = createRenderer();
renderer.render(stuff);
return renderer.getRenderOutput();
}
export function findAllByTag(root, tag) {
return root.props.children.filter((child) => child.type === tag);
}
export function findByTag(root, tag) {
const matches = findAllByTag(root, tag);
assert.equal(matches.length, 1, 'expected one match');
return matches[0];
}
const enabledExtension = Promise.resolve({ type: EXTENSION_TYPE, isActive: true, isEnabled: true });
export function getFakeAddonManagerWrapper({ getAddon = enabledExtension } = {}) {
return {
addChangeListeners: sinon.stub(),
enable: sinon.stub().returns(Promise.resolve()),
getAddon: sinon.stub().returns(getAddon),
install: sinon.stub().returns(Promise.resolve()),
uninstall: sinon.stub().returns(Promise.resolve()),
};
}
export function unexpectedSuccess() {
return assert.fail(null, null, 'Unexpected success');
}
/*
* Creates a stand-in for a jed instance,
*/
export function getFakeI18nInst() {
return {
gettext: sinon.spy((str) => str),
dgettext: sinon.stub(),
ngettext: sinon.spy(ngettext),
dngettext: sinon.stub(),
pgettext: sinon.stub(),
dpgettext: sinon.stub(),
npgettext: sinon.stub(),
dnpgettext: sinon.stub(),
sprintf: sinon.spy(sprintf),
moment,
};
}
export class MockedSubComponent extends React.Component {
render() {
return <div />;
}
}
|
ProDevForIOS/React-Native-0.21-stable/Examples/UIExplorer/AnimatedGratuitousApp/AnExSet.js | ymcao/TopNewsIOS | /**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @providesModule AnExSet
* @flow
*/
'use strict';
var React = require('react-native');
var {
Animated,
PanResponder,
StyleSheet,
Text,
View,
} = React;
var AnExBobble = require('./AnExBobble');
var AnExChained = require('./AnExChained');
var AnExScroll = require('./AnExScroll');
var AnExTilt = require('./AnExTilt');
class AnExSet extends React.Component {
constructor(props: Object) {
super(props);
function randColor() {
var colors = [0,1,2].map(() => Math.floor(Math.random() * 150 + 100));
return 'rgb(' + colors.join(',') + ')';
}
this.state = {
closeColor: randColor(),
openColor: randColor(),
};
}
render(): ReactElement {
var backgroundColor = this.props.openVal ?
this.props.openVal.interpolate({
inputRange: [0, 1],
outputRange: [
this.state.closeColor, // interpolates color strings
this.state.openColor
],
}) :
this.state.closeColor;
var panelWidth = this.props.containerLayout && this.props.containerLayout.width || 320;
return (
<View style={styles.container}>
<Animated.View
style={[styles.header, { backgroundColor }]}
{...this.state.dismissResponder.panHandlers}>
<Text style={[styles.text, styles.headerText]}>
{this.props.id}
</Text>
</Animated.View>
{this.props.isActive &&
<View style={styles.stream}>
<View style={styles.card}>
<Text style={styles.text}>
July 2nd
</Text>
<AnExTilt isActive={this.props.isActive} />
<AnExBobble />
</View>
<AnExScroll panelWidth={panelWidth}/>
<AnExChained />
</View>
}
</View>
);
}
componentWillMount() {
this.state.dismissY = new Animated.Value(0);
this.state.dismissResponder = PanResponder.create({
onStartShouldSetPanResponder: () => this.props.isActive,
onPanResponderGrant: () => {
Animated.spring(this.props.openVal, { // Animated value passed in.
toValue: this.state.dismissY.interpolate({ // Track dismiss gesture
inputRange: [0, 300], // and interpolate pixel distance
outputRange: [1, 0], // to a fraction.
})
}).start();
},
onPanResponderMove: Animated.event(
[null, {dy: this.state.dismissY}] // track pan gesture
),
onPanResponderRelease: (e, gestureState) => {
if (gestureState.dy > 100) {
this.props.onDismiss(gestureState.vy); // delegates dismiss action to parent
} else {
Animated.spring(this.props.openVal, {
toValue: 1, // animate back open if released early
}).start();
}
},
});
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
},
header: {
alignItems: 'center',
paddingTop: 18,
height: 90,
},
stream: {
flex: 1,
backgroundColor: 'rgb(230, 230, 230)',
},
card: {
margin: 8,
padding: 8,
borderRadius: 6,
backgroundColor: 'white',
shadowRadius: 2,
shadowColor: 'black',
shadowOpacity: 0.2,
shadowOffset: {height: 0.5},
},
text: {
padding: 4,
paddingBottom: 10,
fontWeight: 'bold',
fontSize: 18,
backgroundColor: 'transparent',
},
headerText: {
fontSize: 25,
color: 'white',
shadowRadius: 3,
shadowColor: 'black',
shadowOpacity: 1,
shadowOffset: {height: 1},
},
});
module.exports = AnExSet;
|
packages/material-ui-icons/src/MobileOff.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M2.76 2.49L1.49 3.76 5 7.27V21c0 1.1.9 2 2 2h10c1.02 0 1.85-.77 1.98-1.75l1.72 1.72 1.27-1.27L2.76 2.49zM7 19V9.27L16.73 19H7zM17 5v9.17l2 2V3c0-1.1-.9-2-2-2H7c-.85 0-1.58.54-1.87 1.3L7.83 5H17z" /><path fill="none" d="M0 0h24v24H0z" /></React.Fragment>
, 'MobileOff');
|
src/svg-icons/action/power-settings-new.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionPowerSettingsNew = (props) => (
<SvgIcon {...props}>
<path d="M13 3h-2v10h2V3zm4.83 2.17l-1.42 1.42C17.99 7.86 19 9.81 19 12c0 3.87-3.13 7-7 7s-7-3.13-7-7c0-2.19 1.01-4.14 2.58-5.42L6.17 5.17C4.23 6.82 3 9.26 3 12c0 4.97 4.03 9 9 9s9-4.03 9-9c0-2.74-1.23-5.18-3.17-6.83z"/>
</SvgIcon>
);
ActionPowerSettingsNew = pure(ActionPowerSettingsNew);
ActionPowerSettingsNew.displayName = 'ActionPowerSettingsNew';
ActionPowerSettingsNew.muiName = 'SvgIcon';
export default ActionPowerSettingsNew;
|
src/user/userForm.js | codyloyd/teamup | import React from 'react'
import {Field, reduxForm} from 'redux-form'
const UserForm = props => {
const {handleSubmit} = props
return (
<form onSubmit={handleSubmit}>
<div>
<label>First Name</label>
<div>
<Field
name="firstName"
component="input"
type="text"
placeholder="First Name"
/>
</div>
</div>
</form>
)
}
export default reduxForm({form: 'userForm'})(UserForm)
|
ajax/libs/algoliasearch/3.19.2/algoliasearchLite.js | sufuf3/cdnjs | /*! algoliasearch 3.19.2 | © 2014, 2015 Algolia SAS | github.com/algolia/algoliasearch-client-js */
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.algoliasearch = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],2:[function(require,module,exports){
(function (process){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require(3);
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
return JSON.stringify(v);
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs() {
var args = arguments;
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return args;
var c = 'color: ' + this.color;
args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
return args;
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if ('env' in (typeof process === 'undefined' ? {} : process)) {
r = process.env.DEBUG;
}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage(){
try {
return window.localStorage;
} catch (e) {}
}
}).call(this,require(1))
},{"1":1,"3":3}],3:[function(require,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = debug.debug = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require(4);
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lowercased letter, i.e. "n".
*/
exports.formatters = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function selectColor() {
return exports.colors[prevColor++ % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function debug(namespace) {
// define the `disabled` version
function disabled() {
}
disabled.enabled = false;
// define the `enabled` version
function enabled() {
var self = enabled;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// add the `color` if not set
if (null == self.useColors) self.useColors = exports.useColors();
if (null == self.color && self.useColors) self.color = selectColor();
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %o
args = ['%o'].concat(args);
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting
args = exports.formatArgs.apply(self, args);
var logFn = enabled.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
enabled.enabled = true;
var fn = exports.enabled(namespace) ? enabled : disabled;
fn.namespace = namespace;
return fn;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/[\\^$+?.()|[\]{}]/g, '\\$&').replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
},{"4":4}],4:[function(require,module,exports){
/**
* Helpers.
*/
var s = 1000
var m = s * 60
var h = m * 60
var d = h * 24
var y = d * 365.25
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} options
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function (val, options) {
options = options || {}
var type = typeof val
if (type === 'string' && val.length > 0) {
return parse(val)
} else if (type === 'number' && isNaN(val) === false) {
return options.long ?
fmtLong(val) :
fmtShort(val)
}
throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val))
}
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str)
if (str.length > 10000) {
return
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str)
if (!match) {
return
}
var n = parseFloat(match[1])
var type = (match[2] || 'ms').toLowerCase()
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y
case 'days':
case 'day':
case 'd':
return n * d
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n
default:
return undefined
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd'
}
if (ms >= h) {
return Math.round(ms / h) + 'h'
}
if (ms >= m) {
return Math.round(ms / m) + 'm'
}
if (ms >= s) {
return Math.round(ms / s) + 's'
}
return ms + 'ms'
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms'
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name
}
return Math.ceil(ms / n) + ' ' + name + 's'
}
},{}],5:[function(require,module,exports){
(function (process,global){
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
* @version 3.2.1
*/
(function() {
"use strict";
function lib$es6$promise$utils$$objectOrFunction(x) {
return typeof x === 'function' || (typeof x === 'object' && x !== null);
}
function lib$es6$promise$utils$$isFunction(x) {
return typeof x === 'function';
}
function lib$es6$promise$utils$$isMaybeThenable(x) {
return typeof x === 'object' && x !== null;
}
var lib$es6$promise$utils$$_isArray;
if (!Array.isArray) {
lib$es6$promise$utils$$_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
} else {
lib$es6$promise$utils$$_isArray = Array.isArray;
}
var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
var lib$es6$promise$asap$$len = 0;
var lib$es6$promise$asap$$vertxNext;
var lib$es6$promise$asap$$customSchedulerFn;
var lib$es6$promise$asap$$asap = function asap(callback, arg) {
lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
lib$es6$promise$asap$$len += 2;
if (lib$es6$promise$asap$$len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (lib$es6$promise$asap$$customSchedulerFn) {
lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
} else {
lib$es6$promise$asap$$scheduleFlush();
}
}
}
function lib$es6$promise$asap$$setScheduler(scheduleFn) {
lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
}
function lib$es6$promise$asap$$setAsap(asapFn) {
lib$es6$promise$asap$$asap = asapFn;
}
var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
var lib$es6$promise$asap$$isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
// test for web worker but not in IE10
var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
typeof importScripts !== 'undefined' &&
typeof MessageChannel !== 'undefined';
// node
function lib$es6$promise$asap$$useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return function() {
process.nextTick(lib$es6$promise$asap$$flush);
};
}
// vertx
function lib$es6$promise$asap$$useVertxTimer() {
return function() {
lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
};
}
function lib$es6$promise$asap$$useMutationObserver() {
var iterations = 0;
var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function() {
node.data = (iterations = ++iterations % 2);
};
}
// web worker
function lib$es6$promise$asap$$useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = lib$es6$promise$asap$$flush;
return function () {
channel.port2.postMessage(0);
};
}
function lib$es6$promise$asap$$useSetTimeout() {
return function() {
setTimeout(lib$es6$promise$asap$$flush, 1);
};
}
var lib$es6$promise$asap$$queue = new Array(1000);
function lib$es6$promise$asap$$flush() {
for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
var callback = lib$es6$promise$asap$$queue[i];
var arg = lib$es6$promise$asap$$queue[i+1];
callback(arg);
lib$es6$promise$asap$$queue[i] = undefined;
lib$es6$promise$asap$$queue[i+1] = undefined;
}
lib$es6$promise$asap$$len = 0;
}
function lib$es6$promise$asap$$attemptVertx() {
try {
var r = require;
var vertx = r('vertx');
lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
return lib$es6$promise$asap$$useVertxTimer();
} catch(e) {
return lib$es6$promise$asap$$useSetTimeout();
}
}
var lib$es6$promise$asap$$scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (lib$es6$promise$asap$$isNode) {
lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
} else if (lib$es6$promise$asap$$BrowserMutationObserver) {
lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
} else if (lib$es6$promise$asap$$isWorker) {
lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
} else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
} else {
lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
}
function lib$es6$promise$then$$then(onFulfillment, onRejection) {
var parent = this;
var child = new this.constructor(lib$es6$promise$$internal$$noop);
if (child[lib$es6$promise$$internal$$PROMISE_ID] === undefined) {
lib$es6$promise$$internal$$makePromise(child);
}
var state = parent._state;
if (state) {
var callback = arguments[state - 1];
lib$es6$promise$asap$$asap(function(){
lib$es6$promise$$internal$$invokeCallback(state, child, callback, parent._result);
});
} else {
lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
}
return child;
}
var lib$es6$promise$then$$default = lib$es6$promise$then$$then;
function lib$es6$promise$promise$resolve$$resolve(object) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(lib$es6$promise$$internal$$noop);
lib$es6$promise$$internal$$resolve(promise, object);
return promise;
}
var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
var lib$es6$promise$$internal$$PROMISE_ID = Math.random().toString(36).substring(16);
function lib$es6$promise$$internal$$noop() {}
var lib$es6$promise$$internal$$PENDING = void 0;
var lib$es6$promise$$internal$$FULFILLED = 1;
var lib$es6$promise$$internal$$REJECTED = 2;
var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
function lib$es6$promise$$internal$$selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function lib$es6$promise$$internal$$cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function lib$es6$promise$$internal$$getThen(promise) {
try {
return promise.then;
} catch(error) {
lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
return lib$es6$promise$$internal$$GET_THEN_ERROR;
}
}
function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
} catch(e) {
return e;
}
}
function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
lib$es6$promise$asap$$asap(function(promise) {
var sealed = false;
var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
if (sealed) { return; }
sealed = true;
if (thenable !== value) {
lib$es6$promise$$internal$$resolve(promise, value);
} else {
lib$es6$promise$$internal$$fulfill(promise, value);
}
}, function(reason) {
if (sealed) { return; }
sealed = true;
lib$es6$promise$$internal$$reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
lib$es6$promise$$internal$$reject(promise, error);
}
}, promise);
}
function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
lib$es6$promise$$internal$$fulfill(promise, thenable._result);
} else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
lib$es6$promise$$internal$$reject(promise, thenable._result);
} else {
lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
lib$es6$promise$$internal$$resolve(promise, value);
}, function(reason) {
lib$es6$promise$$internal$$reject(promise, reason);
});
}
}
function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable, then) {
if (maybeThenable.constructor === promise.constructor &&
then === lib$es6$promise$then$$default &&
constructor.resolve === lib$es6$promise$promise$resolve$$default) {
lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
} else {
if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
} else if (then === undefined) {
lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
} else if (lib$es6$promise$utils$$isFunction(then)) {
lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
} else {
lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
}
}
}
function lib$es6$promise$$internal$$resolve(promise, value) {
if (promise === value) {
lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
} else if (lib$es6$promise$utils$$objectOrFunction(value)) {
lib$es6$promise$$internal$$handleMaybeThenable(promise, value, lib$es6$promise$$internal$$getThen(value));
} else {
lib$es6$promise$$internal$$fulfill(promise, value);
}
}
function lib$es6$promise$$internal$$publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
lib$es6$promise$$internal$$publish(promise);
}
function lib$es6$promise$$internal$$fulfill(promise, value) {
if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
promise._result = value;
promise._state = lib$es6$promise$$internal$$FULFILLED;
if (promise._subscribers.length !== 0) {
lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
}
}
function lib$es6$promise$$internal$$reject(promise, reason) {
if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
promise._state = lib$es6$promise$$internal$$REJECTED;
promise._result = reason;
lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
}
function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length;
parent._onerror = null;
subscribers[length] = child;
subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
if (length === 0 && parent._state) {
lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
}
}
function lib$es6$promise$$internal$$publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) { return; }
var child, callback, detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function lib$es6$promise$$internal$$ErrorObject() {
this.error = null;
}
var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
function lib$es6$promise$$internal$$tryCatch(callback, detail) {
try {
return callback(detail);
} catch(e) {
lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
}
}
function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
var hasCallback = lib$es6$promise$utils$$isFunction(callback),
value, error, succeeded, failed;
if (hasCallback) {
value = lib$es6$promise$$internal$$tryCatch(callback, detail);
if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value = null;
} else {
succeeded = true;
}
if (promise === value) {
lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== lib$es6$promise$$internal$$PENDING) {
// noop
} else if (hasCallback && succeeded) {
lib$es6$promise$$internal$$resolve(promise, value);
} else if (failed) {
lib$es6$promise$$internal$$reject(promise, error);
} else if (settled === lib$es6$promise$$internal$$FULFILLED) {
lib$es6$promise$$internal$$fulfill(promise, value);
} else if (settled === lib$es6$promise$$internal$$REJECTED) {
lib$es6$promise$$internal$$reject(promise, value);
}
}
function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value){
lib$es6$promise$$internal$$resolve(promise, value);
}, function rejectPromise(reason) {
lib$es6$promise$$internal$$reject(promise, reason);
});
} catch(e) {
lib$es6$promise$$internal$$reject(promise, e);
}
}
var lib$es6$promise$$internal$$id = 0;
function lib$es6$promise$$internal$$nextId() {
return lib$es6$promise$$internal$$id++;
}
function lib$es6$promise$$internal$$makePromise(promise) {
promise[lib$es6$promise$$internal$$PROMISE_ID] = lib$es6$promise$$internal$$id++;
promise._state = undefined;
promise._result = undefined;
promise._subscribers = [];
}
function lib$es6$promise$promise$all$$all(entries) {
return new lib$es6$promise$enumerator$$default(this, entries).promise;
}
var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
function lib$es6$promise$promise$race$$race(entries) {
/*jshint validthis:true */
var Constructor = this;
if (!lib$es6$promise$utils$$isArray(entries)) {
return new Constructor(function(resolve, reject) {
reject(new TypeError('You must pass an array to race.'));
});
} else {
return new Constructor(function(resolve, reject) {
var length = entries.length;
for (var i = 0; i < length; i++) {
Constructor.resolve(entries[i]).then(resolve, reject);
}
});
}
}
var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
function lib$es6$promise$promise$reject$$reject(reason) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(lib$es6$promise$$internal$$noop);
lib$es6$promise$$internal$$reject(promise, reason);
return promise;
}
var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
function lib$es6$promise$promise$$needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function lib$es6$promise$promise$$needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
var promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {function} resolver
Useful for tooling.
@constructor
*/
function lib$es6$promise$promise$$Promise(resolver) {
this[lib$es6$promise$$internal$$PROMISE_ID] = lib$es6$promise$$internal$$nextId();
this._result = this._state = undefined;
this._subscribers = [];
if (lib$es6$promise$$internal$$noop !== resolver) {
typeof resolver !== 'function' && lib$es6$promise$promise$$needsResolver();
this instanceof lib$es6$promise$promise$$Promise ? lib$es6$promise$$internal$$initializePromise(this, resolver) : lib$es6$promise$promise$$needsNew();
}
}
lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
lib$es6$promise$promise$$Promise.prototype = {
constructor: lib$es6$promise$promise$$Promise,
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
var result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
var author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
then: lib$es6$promise$then$$default,
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
'catch': function(onRejection) {
return this.then(null, onRejection);
}
};
var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(lib$es6$promise$$internal$$noop);
if (!this.promise[lib$es6$promise$$internal$$PROMISE_ID]) {
lib$es6$promise$$internal$$makePromise(this.promise);
}
if (lib$es6$promise$utils$$isArray(input)) {
this._input = input;
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
lib$es6$promise$$internal$$fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate();
if (this._remaining === 0) {
lib$es6$promise$$internal$$fulfill(this.promise, this._result);
}
}
} else {
lib$es6$promise$$internal$$reject(this.promise, lib$es6$promise$enumerator$$validationError());
}
}
function lib$es6$promise$enumerator$$validationError() {
return new Error('Array Methods must be provided an Array');
}
lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
var length = this.length;
var input = this._input;
for (var i = 0; this._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
this._eachEntry(input[i], i);
}
};
lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
var c = this._instanceConstructor;
var resolve = c.resolve;
if (resolve === lib$es6$promise$promise$resolve$$default) {
var then = lib$es6$promise$$internal$$getThen(entry);
if (then === lib$es6$promise$then$$default &&
entry._state !== lib$es6$promise$$internal$$PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === lib$es6$promise$promise$$default) {
var promise = new c(lib$es6$promise$$internal$$noop);
lib$es6$promise$$internal$$handleMaybeThenable(promise, entry, then);
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(function(resolve) { resolve(entry); }), i);
}
} else {
this._willSettleAt(resolve(entry), i);
}
};
lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
var promise = this.promise;
if (promise._state === lib$es6$promise$$internal$$PENDING) {
this._remaining--;
if (state === lib$es6$promise$$internal$$REJECTED) {
lib$es6$promise$$internal$$reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
lib$es6$promise$$internal$$fulfill(promise, this._result);
}
};
lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
var enumerator = this;
lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
}, function(reason) {
enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
});
};
function lib$es6$promise$polyfill$$polyfill() {
var local;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
var P = local.Promise;
if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
return;
}
local.Promise = lib$es6$promise$promise$$default;
}
var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
var lib$es6$promise$umd$$ES6Promise = {
'Promise': lib$es6$promise$promise$$default,
'polyfill': lib$es6$promise$polyfill$$default
};
/* global define:true module:true window: true */
if (typeof define === 'function' && define['amd']) {
define(function() { return lib$es6$promise$umd$$ES6Promise; });
} else if (typeof module !== 'undefined' && module['exports']) {
module['exports'] = lib$es6$promise$umd$$ES6Promise;
} else if (typeof this !== 'undefined') {
this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
}
lib$es6$promise$polyfill$$default();
}).call(this);
}).call(this,require(1),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"1":1}],6:[function(require,module,exports){
var hasOwn = Object.prototype.hasOwnProperty;
var toString = Object.prototype.toString;
module.exports = function forEach (obj, fn, ctx) {
if (toString.call(fn) !== '[object Function]') {
throw new TypeError('iterator must be a function');
}
var l = obj.length;
if (l === +l) {
for (var i = 0; i < l; i++) {
fn.call(ctx, obj[i], i, obj);
}
} else {
for (var k in obj) {
if (hasOwn.call(obj, k)) {
fn.call(ctx, obj[k], k, obj);
}
}
}
};
},{}],7:[function(require,module,exports){
(function (global){
if (typeof window !== "undefined") {
module.exports = window;
} else if (typeof global !== "undefined") {
module.exports = global;
} else if (typeof self !== "undefined"){
module.exports = self;
} else {
module.exports = {};
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],8:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],9:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
},{}],10:[function(require,module,exports){
'use strict';
// modified from https://github.com/es-shims/es5-shim
var has = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var slice = Array.prototype.slice;
var isArgs = require(11);
var isEnumerable = Object.prototype.propertyIsEnumerable;
var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var excludedKeys = {
$console: true,
$external: true,
$frame: true,
$frameElement: true,
$frames: true,
$innerHeight: true,
$innerWidth: true,
$outerHeight: true,
$outerWidth: true,
$pageXOffset: true,
$pageYOffset: true,
$parent: true,
$scrollLeft: true,
$scrollTop: true,
$scrollX: true,
$scrollY: true,
$self: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true,
$window: true
};
var hasAutomationEqualityBug = (function () {
/* global window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
try {
if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
} catch (e) {
return true;
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
var keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr.call(object) === '[object Function]';
var isArguments = isArgs(object);
var isString = isObject && toStr.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
keysShim.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
return (Object.keys(arguments) || '').length === 2;
}(1, 2));
if (!keysWorksWithArguments) {
var originalKeys = Object.keys;
Object.keys = function keys(object) {
if (isArgs(object)) {
return originalKeys(slice.call(object));
} else {
return originalKeys(object);
}
};
}
} else {
Object.keys = keysShim;
}
return Object.keys || keysShim;
};
module.exports = keysShim;
},{"11":11}],11:[function(require,module,exports){
'use strict';
var toStr = Object.prototype.toString;
module.exports = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
},{}],12:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
},{}],13:[function(require,module,exports){
module.exports = AlgoliaSearchCore;
var errors = require(24);
var exitPromise = require(25);
var IndexCore = require(14);
// We will always put the API KEY in the JSON body in case of too long API KEY
var MAX_API_KEY_LENGTH = 500;
/*
* Algolia Search library initialization
* https://www.algolia.com/
*
* @param {string} applicationID - Your applicationID, found in your dashboard
* @param {string} apiKey - Your API key, found in your dashboard
* @param {Object} [opts]
* @param {number} [opts.timeout=2000] - The request timeout set in milliseconds,
* another request will be issued after this timeout
* @param {string} [opts.protocol='http:'] - The protocol used to query Algolia Search API.
* Set to 'https:' to force using https.
* Default to document.location.protocol in browsers
* @param {Object|Array} [opts.hosts={
* read: [this.applicationID + '-dsn.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]),
* write: [this.applicationID + '.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]) - The hosts to use for Algolia Search API.
* If you provide them, you will less benefit from our HA implementation
*/
function AlgoliaSearchCore(applicationID, apiKey, opts) {
var debug = require(2)('algoliasearch');
var clone = require(21);
var isArray = require(9);
var map = require(26);
var usage = 'Usage: algoliasearch(applicationID, apiKey, opts)';
if (opts._allowEmptyCredentials !== true && !applicationID) {
throw new errors.AlgoliaSearchError('Please provide an application ID. ' + usage);
}
if (opts._allowEmptyCredentials !== true && !apiKey) {
throw new errors.AlgoliaSearchError('Please provide an API key. ' + usage);
}
this.applicationID = applicationID;
this.apiKey = apiKey;
var defaultHosts = shuffle([
this.applicationID + '-1.algolianet.com',
this.applicationID + '-2.algolianet.com',
this.applicationID + '-3.algolianet.com'
]);
this.hosts = {
read: [],
write: []
};
this.hostIndex = {
read: 0,
write: 0
};
opts = opts || {};
var protocol = opts.protocol || 'https:';
var timeout = opts.timeout === undefined ? 2000 : opts.timeout;
// while we advocate for colon-at-the-end values: 'http:' for `opts.protocol`
// we also accept `http` and `https`. It's a common error.
if (!/:$/.test(protocol)) {
protocol = protocol + ':';
}
if (opts.protocol !== 'http:' && opts.protocol !== 'https:') {
throw new errors.AlgoliaSearchError('protocol must be `http:` or `https:` (was `' + opts.protocol + '`)');
}
// no hosts given, add defaults
if (!opts.hosts) {
this.hosts.read = [this.applicationID + '-dsn.algolia.net'].concat(defaultHosts);
this.hosts.write = [this.applicationID + '.algolia.net'].concat(defaultHosts);
} else if (isArray(opts.hosts)) {
this.hosts.read = clone(opts.hosts);
this.hosts.write = clone(opts.hosts);
} else {
this.hosts.read = clone(opts.hosts.read);
this.hosts.write = clone(opts.hosts.write);
}
// add protocol and lowercase hosts
this.hosts.read = map(this.hosts.read, prepareHost(protocol));
this.hosts.write = map(this.hosts.write, prepareHost(protocol));
this.requestTimeout = timeout;
this.extraHeaders = [];
// In some situations you might want to warm the cache
this.cache = opts._cache || {};
this._ua = opts._ua;
this._useCache = opts._useCache === undefined || opts._cache ? true : opts._useCache;
this._useFallback = opts.useFallback === undefined ? true : opts.useFallback;
this._setTimeout = opts._setTimeout;
debug('init done, %j', this);
}
/*
* Get the index object initialized
*
* @param indexName the name of index
* @param callback the result callback with one argument (the Index instance)
*/
AlgoliaSearchCore.prototype.initIndex = function(indexName) {
return new IndexCore(this, indexName);
};
/**
* Add an extra field to the HTTP request
*
* @param name the header field name
* @param value the header field value
*/
AlgoliaSearchCore.prototype.setExtraHeader = function(name, value) {
this.extraHeaders.push({
name: name.toLowerCase(), value: value
});
};
/**
* Augment sent x-algolia-agent with more data, each agent part
* is automatically separated from the others by a semicolon;
*
* @param algoliaAgent the agent to add
*/
AlgoliaSearchCore.prototype.addAlgoliaAgent = function(algoliaAgent) {
this._ua += ';' + algoliaAgent;
};
/*
* Wrapper that try all hosts to maximize the quality of service
*/
AlgoliaSearchCore.prototype._jsonRequest = function(initialOpts) {
var requestDebug = require(2)('algoliasearch:' + initialOpts.url);
var body;
var cache = initialOpts.cache;
var client = this;
var tries = 0;
var usingFallback = false;
var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback;
var headers;
if (
this.apiKey.length > MAX_API_KEY_LENGTH &&
initialOpts.body !== undefined &&
(initialOpts.body.params !== undefined || // index.search()
initialOpts.body.requests !== undefined) // client.search()
) {
initialOpts.body.apiKey = this.apiKey;
headers = this._computeRequestHeaders(false);
} else {
headers = this._computeRequestHeaders();
}
if (initialOpts.body !== undefined) {
body = safeJSONStringify(initialOpts.body);
}
requestDebug('request start');
var debugData = [];
function doRequest(requester, reqOpts) {
var startTime = new Date();
var cacheID;
if (client._useCache) {
cacheID = initialOpts.url;
}
// as we sometime use POST requests to pass parameters (like query='aa'),
// the cacheID must also include the body to be different between calls
if (client._useCache && body) {
cacheID += '_body_' + reqOpts.body;
}
// handle cache existence
if (client._useCache && cache && cache[cacheID] !== undefined) {
requestDebug('serving response from cache');
return client._promise.resolve(JSON.parse(cache[cacheID]));
}
// if we reached max tries
if (tries >= client.hosts[initialOpts.hostType].length) {
if (!hasFallback || usingFallback) {
requestDebug('could not get any response');
// then stop
return client._promise.reject(new errors.AlgoliaSearchError(
'Cannot connect to the AlgoliaSearch API.' +
' Send an email to [email protected] to report and resolve the issue.' +
' Application id was: ' + client.applicationID, {debugData: debugData}
));
}
requestDebug('switching to fallback');
// let's try the fallback starting from here
tries = 0;
// method, url and body are fallback dependent
reqOpts.method = initialOpts.fallback.method;
reqOpts.url = initialOpts.fallback.url;
reqOpts.jsonBody = initialOpts.fallback.body;
if (reqOpts.jsonBody) {
reqOpts.body = safeJSONStringify(reqOpts.jsonBody);
}
// re-compute headers, they could be omitting the API KEY
headers = client._computeRequestHeaders();
reqOpts.timeout = client.requestTimeout * (tries + 1);
client.hostIndex[initialOpts.hostType] = 0;
usingFallback = true; // the current request is now using fallback
return doRequest(client._request.fallback, reqOpts);
}
var currentHost = client.hosts[initialOpts.hostType][client.hostIndex[initialOpts.hostType]];
var url = currentHost + reqOpts.url;
var options = {
body: reqOpts.body,
jsonBody: reqOpts.jsonBody,
method: reqOpts.method,
headers: headers,
timeout: reqOpts.timeout,
debug: requestDebug
};
requestDebug('method: %s, url: %s, headers: %j, timeout: %d',
options.method, url, options.headers, options.timeout);
if (requester === client._request.fallback) {
requestDebug('using fallback');
}
// `requester` is any of this._request or this._request.fallback
// thus it needs to be called using the client as context
return requester.call(client, url, options).then(success, tryFallback);
function success(httpResponse) {
// compute the status of the response,
//
// When in browser mode, using XDR or JSONP, we have no statusCode available
// So we rely on our API response `status` property.
// But `waitTask` can set a `status` property which is not the statusCode (it's the task status)
// So we check if there's a `message` along `status` and it means it's an error
//
// That's the only case where we have a response.status that's not the http statusCode
var status = httpResponse && httpResponse.body && httpResponse.body.message && httpResponse.body.status ||
// this is important to check the request statusCode AFTER the body eventual
// statusCode because some implementations (jQuery XDomainRequest transport) may
// send statusCode 200 while we had an error
httpResponse.statusCode ||
// When in browser mode, using XDR or JSONP
// we default to success when no error (no response.status && response.message)
// If there was a JSON.parse() error then body is null and it fails
httpResponse && httpResponse.body && 200;
requestDebug('received response: statusCode: %s, computed statusCode: %d, headers: %j',
httpResponse.statusCode, status, httpResponse.headers);
var httpResponseOk = Math.floor(status / 100) === 2;
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeout: reqOpts.timeout,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime,
statusCode: status
});
if (httpResponseOk) {
if (client._useCache && cache) {
cache[cacheID] = httpResponse.responseText;
}
return httpResponse.body;
}
var shouldRetry = Math.floor(status / 100) !== 4;
if (shouldRetry) {
tries += 1;
return retryRequest();
}
requestDebug('unrecoverable error');
// no success and no retry => fail
var unrecoverableError = new errors.AlgoliaSearchError(
httpResponse.body && httpResponse.body.message, {debugData: debugData, statusCode: status}
);
return client._promise.reject(unrecoverableError);
}
function tryFallback(err) {
// error cases:
// While not in fallback mode:
// - CORS not supported
// - network error
// While in fallback mode:
// - timeout
// - network error
// - badly formatted JSONP (script loaded, did not call our callback)
// In both cases:
// - uncaught exception occurs (TypeError)
requestDebug('error: %s, stack: %s', err.message, err.stack);
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeout: reqOpts.timeout,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime
});
if (!(err instanceof errors.AlgoliaSearchError)) {
err = new errors.Unknown(err && err.message, err);
}
tries += 1;
// stop the request implementation when:
if (
// we did not generate this error,
// it comes from a throw in some other piece of code
err instanceof errors.Unknown ||
// server sent unparsable JSON
err instanceof errors.UnparsableJSON ||
// max tries and already using fallback or no fallback
tries >= client.hosts[initialOpts.hostType].length &&
(usingFallback || !hasFallback)) {
// stop request implementation for this command
err.debugData = debugData;
return client._promise.reject(err);
}
// When a timeout occured, retry by raising timeout
if (err instanceof errors.RequestTimeout) {
return retryRequestWithHigherTimeout();
}
return retryRequest();
}
function retryRequest() {
requestDebug('retrying request');
client.hostIndex[initialOpts.hostType] = (client.hostIndex[initialOpts.hostType] + 1) % client.hosts[initialOpts.hostType].length;
return doRequest(requester, reqOpts);
}
function retryRequestWithHigherTimeout() {
requestDebug('retrying request with higher timeout');
client.hostIndex[initialOpts.hostType] = (client.hostIndex[initialOpts.hostType] + 1) % client.hosts[initialOpts.hostType].length;
reqOpts.timeout = client.requestTimeout * (tries + 1);
return doRequest(requester, reqOpts);
}
}
var promise = doRequest(
client._request, {
url: initialOpts.url,
method: initialOpts.method,
body: body,
jsonBody: initialOpts.body,
timeout: client.requestTimeout * (tries + 1)
}
);
// either we have a callback
// either we are using promises
if (initialOpts.callback) {
promise.then(function okCb(content) {
exitPromise(function() {
initialOpts.callback(null, content);
}, client._setTimeout || setTimeout);
}, function nookCb(err) {
exitPromise(function() {
initialOpts.callback(err);
}, client._setTimeout || setTimeout);
});
} else {
return promise;
}
};
/*
* Transform search param object in query string
*/
AlgoliaSearchCore.prototype._getSearchParams = function(args, params) {
if (args === undefined || args === null) {
return params;
}
for (var key in args) {
if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) {
params += params === '' ? '' : '&';
params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]);
}
}
return params;
};
AlgoliaSearchCore.prototype._computeRequestHeaders = function(withAPIKey) {
var forEach = require(6);
var requestHeaders = {
'x-algolia-agent': this._ua,
'x-algolia-application-id': this.applicationID
};
// browser will inline headers in the url, node.js will use http headers
// but in some situations, the API KEY will be too long (big secured API keys)
// so if the request is a POST and the KEY is very long, we will be asked to not put
// it into headers but in the JSON body
if (withAPIKey !== false) {
requestHeaders['x-algolia-api-key'] = this.apiKey;
}
if (this.userToken) {
requestHeaders['x-algolia-usertoken'] = this.userToken;
}
if (this.securityTags) {
requestHeaders['x-algolia-tagfilters'] = this.securityTags;
}
if (this.extraHeaders) {
forEach(this.extraHeaders, function addToRequestHeaders(header) {
requestHeaders[header.name] = header.value;
});
}
return requestHeaders;
};
/**
* Search through multiple indices at the same time
* @param {Object[]} queries An array of queries you want to run.
* @param {string} queries[].indexName The index name you want to target
* @param {string} [queries[].query] The query to issue on this index. Can also be passed into `params`
* @param {Object} queries[].params Any search param like hitsPerPage, ..
* @param {Function} callback Callback to be called
* @return {Promise|undefined} Returns a promise if no callback given
*/
AlgoliaSearchCore.prototype.search = function(queries, opts, callback) {
var isArray = require(9);
var map = require(26);
var usage = 'Usage: client.search(arrayOfQueries[, callback])';
if (!isArray(queries)) {
throw new Error(usage);
}
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
var client = this;
var postObj = {
requests: map(queries, function prepareRequest(query) {
var params = '';
// allow query.query
// so we are mimicing the index.search(query, params) method
// {indexName:, query:, params:}
if (query.query !== undefined) {
params += 'query=' + encodeURIComponent(query.query);
}
return {
indexName: query.indexName,
params: client._getSearchParams(query.params, params)
};
})
};
var JSONPParams = map(postObj.requests, function prepareJSONPParams(request, requestId) {
return requestId + '=' +
encodeURIComponent(
'/1/indexes/' + encodeURIComponent(request.indexName) + '?' +
request.params
);
}).join('&');
var url = '/1/indexes/*/queries';
if (opts.strategy !== undefined) {
url += '?strategy=' + opts.strategy;
}
return this._jsonRequest({
cache: this.cache,
method: 'POST',
url: url,
body: postObj,
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/*',
body: {
params: JSONPParams
}
},
callback: callback
});
};
/**
* Set the extra security tagFilters header
* @param {string|array} tags The list of tags defining the current security filters
*/
AlgoliaSearchCore.prototype.setSecurityTags = function(tags) {
if (Object.prototype.toString.call(tags) === '[object Array]') {
var strTags = [];
for (var i = 0; i < tags.length; ++i) {
if (Object.prototype.toString.call(tags[i]) === '[object Array]') {
var oredTags = [];
for (var j = 0; j < tags[i].length; ++j) {
oredTags.push(tags[i][j]);
}
strTags.push('(' + oredTags.join(',') + ')');
} else {
strTags.push(tags[i]);
}
}
tags = strTags.join(',');
}
this.securityTags = tags;
};
/**
* Set the extra user token header
* @param {string} userToken The token identifying a uniq user (used to apply rate limits)
*/
AlgoliaSearchCore.prototype.setUserToken = function(userToken) {
this.userToken = userToken;
};
/**
* Clear all queries in client's cache
* @return undefined
*/
AlgoliaSearchCore.prototype.clearCache = function() {
this.cache = {};
};
/**
* Set the number of milliseconds a request can take before automatically being terminated.
*
* @param {Number} milliseconds
*/
AlgoliaSearchCore.prototype.setRequestTimeout = function(milliseconds) {
if (milliseconds) {
this.requestTimeout = parseInt(milliseconds, 10);
}
};
function prepareHost(protocol) {
return function prepare(host) {
return protocol + '//' + host.toLowerCase();
};
}
// Prototype.js < 1.7, a widely used library, defines a weird
// Array.prototype.toJSON function that will fail to stringify our content
// appropriately
// refs:
// - https://groups.google.com/forum/#!topic/prototype-core/E-SAVvV_V9Q
// - https://github.com/sstephenson/prototype/commit/038a2985a70593c1a86c230fadbdfe2e4898a48c
// - http://stackoverflow.com/a/3148441/147079
function safeJSONStringify(obj) {
/* eslint no-extend-native:0 */
if (Array.prototype.toJSON === undefined) {
return JSON.stringify(obj);
}
var toJSON = Array.prototype.toJSON;
delete Array.prototype.toJSON;
var out = JSON.stringify(obj);
Array.prototype.toJSON = toJSON;
return out;
}
function shuffle(array) {
var currentIndex = array.length;
var temporaryValue;
var randomIndex;
// While there remain elements to shuffle...
while (currentIndex !== 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function removeCredentials(headers) {
var newHeaders = {};
for (var headerName in headers) {
if (Object.prototype.hasOwnProperty.call(headers, headerName)) {
var value;
if (headerName === 'x-algolia-api-key' || headerName === 'x-algolia-application-id') {
value = '**hidden for security purposes**';
} else {
value = headers[headerName];
}
newHeaders[headerName] = value;
}
}
return newHeaders;
}
},{"14":14,"2":2,"21":21,"24":24,"25":25,"26":26,"6":6,"9":9}],14:[function(require,module,exports){
var buildSearchMethod = require(20);
var deprecate = require(22);
var deprecatedMessage = require(23);
module.exports = IndexCore;
/*
* Index class constructor.
* You should not use this method directly but use initIndex() function
*/
function IndexCore(algoliasearch, indexName) {
this.indexName = indexName;
this.as = algoliasearch;
this.typeAheadArgs = null;
this.typeAheadValueOption = null;
// make sure every index instance has it's own cache
this.cache = {};
}
/*
* Clear all queries in cache
*/
IndexCore.prototype.clearCache = function() {
this.cache = {};
};
/*
* Search inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param query the full text query
* @param args (optional) if set, contains an object with query parameters:
* - page: (integer) Pagination parameter used to select the page to retrieve.
* Page is zero-based and defaults to 0. Thus,
* to retrieve the 10th page you need to set page=9
* - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20.
* - attributesToRetrieve: a string that contains the list of object attributes
* you want to retrieve (let you minimize the answer size).
* Attributes are separated with a comma (for example "name,address").
* You can also use an array (for example ["name","address"]).
* By default, all attributes are retrieved. You can also use '*' to retrieve all
* values when an attributesToRetrieve setting is specified for your index.
* - attributesToHighlight: a string that contains the list of attributes you
* want to highlight according to the query.
* Attributes are separated by a comma. You can also use an array (for example ["name","address"]).
* If an attribute has no match for the query, the raw value is returned.
* By default all indexed text attributes are highlighted.
* You can use `*` if you want to highlight all textual attributes.
* Numerical attributes are not highlighted.
* A matchLevel is returned for each highlighted attribute and can contain:
* - full: if all the query terms were found in the attribute,
* - partial: if only some of the query terms were found,
* - none: if none of the query terms were found.
* - attributesToSnippet: a string that contains the list of attributes to snippet alongside
* the number of words to return (syntax is `attributeName:nbWords`).
* Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10).
* You can also use an array (Example: attributesToSnippet: ['name:10','content:10']).
* By default no snippet is computed.
* - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word.
* Defaults to 3.
* - minWordSizefor2Typos: the minimum number of characters in a query word
* to accept two typos in this word. Defaults to 7.
* - getRankingInfo: if set to 1, the result hits will contain ranking
* information in _rankingInfo attribute.
* - aroundLatLng: search for entries around a given
* latitude/longitude (specified as two floats separated by a comma).
* For example aroundLatLng=47.316669,5.016670).
* You can specify the maximum distance in meters with the aroundRadius parameter (in meters)
* and the precision for ranking with aroundPrecision
* (for example if you set aroundPrecision=100, two objects that are distant of
* less than 100m will be considered as identical for "geo" ranking parameter).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - insideBoundingBox: search entries inside a given area defined by the two extreme points
* of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng).
* For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - numericFilters: a string that contains the list of numeric filters you want to
* apply separated by a comma.
* The syntax of one filter is `attributeName` followed by `operand` followed by `value`.
* Supported operands are `<`, `<=`, `=`, `>` and `>=`.
* You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000.
* You can also use an array (for example numericFilters: ["price>100","price<1000"]).
* - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas.
* To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3).
* You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]]
* means tag1 AND (tag2 OR tag3).
* At indexing, tags should be added in the _tags** attribute
* of objects (for example {"_tags":["tag1","tag2"]}).
* - facetFilters: filter the query by a list of facets.
* Facets are separated by commas and each facet is encoded as `attributeName:value`.
* For example: `facetFilters=category:Book,author:John%20Doe`.
* You can also use an array (for example `["category:Book","author:John%20Doe"]`).
* - facets: List of object attributes that you want to use for faceting.
* Comma separated list: `"category,author"` or array `['category','author']`
* Only attributes that have been added in **attributesForFaceting** index setting
* can be used in this parameter.
* You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**.
* - queryType: select how the query words are interpreted, it can be one of the following value:
* - prefixAll: all query words are interpreted as prefixes,
* - prefixLast: only the last word is interpreted as a prefix (default behavior),
* - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
* - optionalWords: a string that contains the list of words that should
* be considered as optional when found in the query.
* Comma separated and array are accepted.
* - distinct: If set to 1, enable the distinct feature (disabled by default)
* if the attributeForDistinct index setting is set.
* This feature is similar to the SQL "distinct" keyword: when enabled
* in a query with the distinct=1 parameter,
* all hits containing a duplicate value for the attributeForDistinct attribute are removed from results.
* For example, if the chosen attribute is show_name and several hits have
* the same value for show_name, then only the best
* one is kept and others are removed.
* - restrictSearchableAttributes: List of attributes you want to use for
* textual search (must be a subset of the attributesToIndex index setting)
* either comma separated or as an array
* @param callback the result callback called with two arguments:
* error: null or Error('message'). If false, the content contains the error.
* content: the server answer that contains the list of results.
*/
IndexCore.prototype.search = buildSearchMethod('query');
/*
* -- BETA --
* Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param query the similar query
* @param args (optional) if set, contains an object with query parameters.
* All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters
* are the two most useful to restrict the similar results and get more relevant content
*/
IndexCore.prototype.similarSearch = buildSearchMethod('similarQuery');
/*
* Browse index content. The response content will have a `cursor` property that you can use
* to browse subsequent pages for this query. Use `index.browseFrom(cursor)` when you want.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browse('cool songs', {
* tagFilters: 'public,comments',
* hitsPerPage: 500
* }, callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browse = function(query, queryParameters, callback) {
var merge = require(27);
var indexObj = this;
var page;
var hitsPerPage;
// we check variadic calls that are not the one defined
// .browse()/.browse(fn)
// => page = 0
if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') {
page = 0;
callback = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'number') {
// .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn)
page = arguments[0];
if (typeof arguments[1] === 'number') {
hitsPerPage = arguments[1];
} else if (typeof arguments[1] === 'function') {
callback = arguments[1];
hitsPerPage = undefined;
}
query = undefined;
queryParameters = undefined;
} else if (typeof arguments[0] === 'object') {
// .browse(queryParameters)/.browse(queryParameters, cb)
if (typeof arguments[1] === 'function') {
callback = arguments[1];
}
queryParameters = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') {
// .browse(query, cb)
callback = arguments[1];
queryParameters = undefined;
}
// otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb)
// get search query parameters combining various possible calls
// to .browse();
queryParameters = merge({}, queryParameters || {}, {
page: page,
hitsPerPage: hitsPerPage,
query: query
});
var params = this.as._getSearchParams(queryParameters, '');
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse?' + params,
hostType: 'read',
callback: callback
});
};
/*
* Continue browsing from a previous position (cursor), obtained via a call to `.browse()`.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browseFrom('14lkfsakl32', callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browseFrom = function(cursor, callback) {
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse?cursor=' + encodeURIComponent(cursor),
hostType: 'read',
callback: callback
});
};
/*
* Search for facet values
* https://www.algolia.com/doc/rest-api/search#search-for-facet-values
*
* @param {string} params.facetName Facet name, name of the attribute to search for values in.
* Must be declared as a facet
* @param {string} params.facetQuery Query for the facet search
* @param {string} [params.*] Any search parameter of Algolia,
* see https://www.algolia.com/doc/api-client/javascript/search#search-parameters
* Pagination is not supported. The page and hitsPerPage parameters will be ignored.
* @param callback (optional)
*/
IndexCore.prototype.searchForFacetValues = function(params, callback) {
var clone = require(21);
var omit = require(28);
var usage = 'Usage: index.searchForFacetValues({facetName, facetQuery, ...params}[, callback])';
if (params.facetName === undefined || params.facetQuery === undefined) {
throw new Error(usage);
}
var facetName = params.facetName;
var filteredParams = omit(clone(params), function(keyName) {
return keyName === 'facetName';
});
var searchParameters = this.as._getSearchParams(filteredParams, '');
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' +
encodeURIComponent(this.indexName) + '/facets/' + encodeURIComponent(facetName) + '/query',
hostType: 'read',
body: {params: searchParameters},
callback: callback
});
};
IndexCore.prototype.searchFacet = deprecate(function(params, callback) {
return this.searchForFacetValues(params, callback);
}, deprecatedMessage(
'index.searchFacet(params[, callback])',
'index.searchForFacetValues(params[, callback])'
));
IndexCore.prototype._search = function(params, url, callback) {
return this.as._jsonRequest({
cache: this.cache,
method: 'POST',
url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query',
body: {params: params},
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName),
body: {params: params}
},
callback: callback
});
};
/*
* Get an object from this index
*
* @param objectID the unique identifier of the object to retrieve
* @param attrs (optional) if set, contains the array of attribute names to retrieve
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the object to retrieve or the error message if a failure occured
*/
IndexCore.prototype.getObject = function(objectID, attrs, callback) {
var indexObj = this;
if (arguments.length === 1 || typeof attrs === 'function') {
callback = attrs;
attrs = undefined;
}
var params = '';
if (attrs !== undefined) {
params = '?attributes=';
for (var i = 0; i < attrs.length; ++i) {
if (i !== 0) {
params += ',';
}
params += attrs[i];
}
}
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params,
hostType: 'read',
callback: callback
});
};
/*
* Get several objects from this index
*
* @param objectIDs the array of unique identifier of objects to retrieve
*/
IndexCore.prototype.getObjects = function(objectIDs, attributesToRetrieve, callback) {
var isArray = require(9);
var map = require(26);
var usage = 'Usage: index.getObjects(arrayOfObjectIDs[, callback])';
if (!isArray(objectIDs)) {
throw new Error(usage);
}
var indexObj = this;
if (arguments.length === 1 || typeof attributesToRetrieve === 'function') {
callback = attributesToRetrieve;
attributesToRetrieve = undefined;
}
var body = {
requests: map(objectIDs, function prepareRequest(objectID) {
var request = {
indexName: indexObj.indexName,
objectID: objectID
};
if (attributesToRetrieve) {
request.attributesToRetrieve = attributesToRetrieve.join(',');
}
return request;
})
};
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/*/objects',
hostType: 'read',
body: body,
callback: callback
});
};
IndexCore.prototype.as = null;
IndexCore.prototype.indexName = null;
IndexCore.prototype.typeAheadArgs = null;
IndexCore.prototype.typeAheadValueOption = null;
},{"20":20,"21":21,"22":22,"23":23,"26":26,"27":27,"28":28,"9":9}],15:[function(require,module,exports){
'use strict';
var AlgoliaSearchCore = require(13);
var createAlgoliasearch = require(16);
module.exports = createAlgoliasearch(AlgoliaSearchCore, '(lite) ');
},{"13":13,"16":16}],16:[function(require,module,exports){
(function (process){
'use strict';
var global = require(7);
var Promise = global.Promise || require(5).Promise;
// This is the standalone browser build entry point
// Browser implementation of the Algolia Search JavaScript client,
// using XMLHttpRequest, XDomainRequest and JSONP as fallback
module.exports = function createAlgoliasearch(AlgoliaSearch, uaSuffix) {
var inherits = require(8);
var errors = require(24);
var inlineHeaders = require(18);
var jsonpRequest = require(19);
var places = require(29);
uaSuffix = uaSuffix || '';
if (process.env.NODE_ENV === 'debug') {
require(2).enable('algoliasearch*');
}
function algoliasearch(applicationID, apiKey, opts) {
var cloneDeep = require(21);
var getDocumentProtocol = require(17);
opts = cloneDeep(opts || {});
if (opts.protocol === undefined) {
opts.protocol = getDocumentProtocol();
}
opts._ua = opts._ua || algoliasearch.ua;
return new AlgoliaSearchBrowser(applicationID, apiKey, opts);
}
algoliasearch.version = require(30);
algoliasearch.ua = 'Algolia for vanilla JavaScript ' + uaSuffix + algoliasearch.version;
algoliasearch.initPlaces = places(algoliasearch);
// we expose into window no matter how we are used, this will allow
// us to easily debug any website running algolia
global.__algolia = {
debug: require(2),
algoliasearch: algoliasearch
};
var support = {
hasXMLHttpRequest: 'XMLHttpRequest' in global,
hasXDomainRequest: 'XDomainRequest' in global
};
if (support.hasXMLHttpRequest) {
support.cors = 'withCredentials' in new XMLHttpRequest();
support.timeout = 'timeout' in new XMLHttpRequest();
}
function AlgoliaSearchBrowser() {
// call AlgoliaSearch constructor
AlgoliaSearch.apply(this, arguments);
}
inherits(AlgoliaSearchBrowser, AlgoliaSearch);
AlgoliaSearchBrowser.prototype._request = function request(url, opts) {
return new Promise(function wrapRequest(resolve, reject) {
// no cors or XDomainRequest, no request
if (!support.cors && !support.hasXDomainRequest) {
// very old browser, not supported
reject(new errors.Network('CORS not supported'));
return;
}
url = inlineHeaders(url, opts.headers);
var body = opts.body;
var req = support.cors ? new XMLHttpRequest() : new XDomainRequest();
var ontimeout;
var timedOut;
// do not rely on default XHR async flag, as some analytics code like hotjar
// breaks it and set it to false by default
if (req instanceof XMLHttpRequest) {
req.open(opts.method, url, true);
} else {
req.open(opts.method, url);
}
if (support.cors) {
if (body) {
if (opts.method === 'POST') {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests
req.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
} else {
req.setRequestHeader('content-type', 'application/json');
}
}
req.setRequestHeader('accept', 'application/json');
}
// we set an empty onprogress listener
// so that XDomainRequest on IE9 is not aborted
// refs:
// - https://github.com/algolia/algoliasearch-client-js/issues/76
// - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment
req.onprogress = function noop() {};
req.onload = load;
req.onerror = error;
if (support.timeout) {
// .timeout supported by both XHR and XDR,
// we do receive timeout event, tested
req.timeout = opts.timeout;
req.ontimeout = timeout;
} else {
ontimeout = setTimeout(timeout, opts.timeout);
}
req.send(body);
// event object not received in IE8, at least
// but we do not use it, still important to note
function load(/* event */) {
// When browser does not supports req.timeout, we can
// have both a load and timeout event, since handled by a dumb setTimeout
if (timedOut) {
return;
}
if (!support.timeout) {
clearTimeout(ontimeout);
}
var out;
try {
out = {
body: JSON.parse(req.responseText),
responseText: req.responseText,
statusCode: req.status,
// XDomainRequest does not have any response headers
headers: req.getAllResponseHeaders && req.getAllResponseHeaders() || {}
};
} catch (e) {
out = new errors.UnparsableJSON({
more: req.responseText
});
}
if (out instanceof errors.UnparsableJSON) {
reject(out);
} else {
resolve(out);
}
}
function error(event) {
if (timedOut) {
return;
}
if (!support.timeout) {
clearTimeout(ontimeout);
}
// error event is trigerred both with XDR/XHR on:
// - DNS error
// - unallowed cross domain request
reject(
new errors.Network({
more: event
})
);
}
function timeout() {
if (!support.timeout) {
timedOut = true;
req.abort();
}
reject(new errors.RequestTimeout());
}
});
};
AlgoliaSearchBrowser.prototype._request.fallback = function requestFallback(url, opts) {
url = inlineHeaders(url, opts.headers);
return new Promise(function wrapJsonpRequest(resolve, reject) {
jsonpRequest(url, opts, function jsonpRequestDone(err, content) {
if (err) {
reject(err);
return;
}
resolve(content);
});
});
};
AlgoliaSearchBrowser.prototype._promise = {
reject: function rejectPromise(val) {
return Promise.reject(val);
},
resolve: function resolvePromise(val) {
return Promise.resolve(val);
},
delay: function delayPromise(ms) {
return new Promise(function resolveOnTimeout(resolve/* , reject*/) {
setTimeout(resolve, ms);
});
}
};
return algoliasearch;
};
}).call(this,require(1))
},{"1":1,"17":17,"18":18,"19":19,"2":2,"21":21,"24":24,"29":29,"30":30,"5":5,"7":7,"8":8}],17:[function(require,module,exports){
'use strict';
module.exports = getDocumentProtocol;
function getDocumentProtocol() {
var protocol = window.document.location.protocol;
// when in `file:` mode (local html file), default to `http:`
if (protocol !== 'http:' && protocol !== 'https:') {
protocol = 'http:';
}
return protocol;
}
},{}],18:[function(require,module,exports){
'use strict';
module.exports = inlineHeaders;
var encode = require(12);
function inlineHeaders(url, headers) {
if (/\?/.test(url)) {
url += '&';
} else {
url += '?';
}
return url + encode(headers);
}
},{"12":12}],19:[function(require,module,exports){
'use strict';
module.exports = jsonpRequest;
var errors = require(24);
var JSONPCounter = 0;
function jsonpRequest(url, opts, cb) {
if (opts.method !== 'GET') {
cb(new Error('Method ' + opts.method + ' ' + url + ' is not supported by JSONP.'));
return;
}
opts.debug('JSONP: start');
var cbCalled = false;
var timedOut = false;
JSONPCounter += 1;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
var cbName = 'algoliaJSONP_' + JSONPCounter;
var done = false;
window[cbName] = function(data) {
removeGlobals();
if (timedOut) {
opts.debug('JSONP: Late answer, ignoring');
return;
}
cbCalled = true;
clean();
cb(null, {
body: data/* ,
// We do not send the statusCode, there's no statusCode in JSONP, it will be
// computed using data.status && data.message like with XDR
statusCode*/
});
};
// add callback by hand
url += '&callback=' + cbName;
// add body params manually
if (opts.jsonBody && opts.jsonBody.params) {
url += '&' + opts.jsonBody.params;
}
var ontimeout = setTimeout(timeout, opts.timeout);
// script onreadystatechange needed only for
// <= IE8
// https://github.com/angular/angular.js/issues/4523
script.onreadystatechange = readystatechange;
script.onload = success;
script.onerror = error;
script.async = true;
script.defer = true;
script.src = url;
head.appendChild(script);
function success() {
opts.debug('JSONP: success');
if (done || timedOut) {
return;
}
done = true;
// script loaded but did not call the fn => script loading error
if (!cbCalled) {
opts.debug('JSONP: Fail. Script loaded but did not call the callback');
clean();
cb(new errors.JSONPScriptFail());
}
}
function readystatechange() {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
success();
}
}
function clean() {
clearTimeout(ontimeout);
script.onload = null;
script.onreadystatechange = null;
script.onerror = null;
head.removeChild(script);
}
function removeGlobals() {
try {
delete window[cbName];
delete window[cbName + '_loaded'];
} catch (e) {
window[cbName] = window[cbName + '_loaded'] = undefined;
}
}
function timeout() {
opts.debug('JSONP: Script timeout');
timedOut = true;
clean();
cb(new errors.RequestTimeout());
}
function error() {
opts.debug('JSONP: Script error');
if (done || timedOut) {
return;
}
clean();
cb(new errors.JSONPScriptError());
}
}
},{"24":24}],20:[function(require,module,exports){
module.exports = buildSearchMethod;
var errors = require(24);
function buildSearchMethod(queryParam, url) {
return function search(query, args, callback) {
// warn V2 users on how to search
if (typeof query === 'function' && typeof args === 'object' ||
typeof callback === 'object') {
// .search(query, params, cb)
// .search(cb, params)
throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)');
}
if (arguments.length === 0 || typeof query === 'function') {
// .search(), .search(cb)
callback = query;
query = '';
} else if (arguments.length === 1 || typeof args === 'function') {
// .search(query/args), .search(query, cb)
callback = args;
args = undefined;
}
// .search(args), careful: typeof null === 'object'
if (typeof query === 'object' && query !== null) {
args = query;
query = undefined;
} else if (query === undefined || query === null) { // .search(undefined/null)
query = '';
}
var params = '';
if (query !== undefined) {
params += queryParam + '=' + encodeURIComponent(query);
}
if (args !== undefined) {
// `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if
params = this.as._getSearchParams(args, params);
}
return this._search(params, url, callback);
};
}
},{"24":24}],21:[function(require,module,exports){
module.exports = function clone(obj) {
return JSON.parse(JSON.stringify(obj));
};
},{}],22:[function(require,module,exports){
module.exports = function deprecate(fn, message) {
var warned = false;
function deprecated() {
if (!warned) {
/* eslint no-console:0 */
console.log(message);
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
},{}],23:[function(require,module,exports){
module.exports = function deprecatedMessage(previousUsage, newUsage) {
var githubAnchorLink = previousUsage.toLowerCase()
.replace('.', '')
.replace('()', '');
return 'algoliasearch: `' + previousUsage + '` was replaced by `' + newUsage +
'`. Please see https://github.com/algolia/algoliasearch-client-js/wiki/Deprecated#' + githubAnchorLink;
};
},{}],24:[function(require,module,exports){
'use strict';
// This file hosts our error definitions
// We use custom error "types" so that we can act on them when we need it
// e.g.: if error instanceof errors.UnparsableJSON then..
var inherits = require(8);
function AlgoliaSearchError(message, extraProperties) {
var forEach = require(6);
var error = this;
// try to get a stacktrace
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
error.stack = (new Error()).stack || 'Cannot get a stacktrace, browser is too old';
}
this.name = 'AlgoliaSearchError';
this.message = message || 'Unknown error';
if (extraProperties) {
forEach(extraProperties, function addToErrorObject(value, key) {
error[key] = value;
});
}
}
inherits(AlgoliaSearchError, Error);
function createCustomError(name, message) {
function AlgoliaSearchCustomError() {
var args = Array.prototype.slice.call(arguments, 0);
// custom message not set, use default
if (typeof args[0] !== 'string') {
args.unshift(message);
}
AlgoliaSearchError.apply(this, args);
this.name = 'AlgoliaSearch' + name + 'Error';
}
inherits(AlgoliaSearchCustomError, AlgoliaSearchError);
return AlgoliaSearchCustomError;
}
// late exports to let various fn defs and inherits take place
module.exports = {
AlgoliaSearchError: AlgoliaSearchError,
UnparsableJSON: createCustomError(
'UnparsableJSON',
'Could not parse the incoming response as JSON, see err.more for details'
),
RequestTimeout: createCustomError(
'RequestTimeout',
'Request timedout before getting a response'
),
Network: createCustomError(
'Network',
'Network issue, see err.more for details'
),
JSONPScriptFail: createCustomError(
'JSONPScriptFail',
'<script> was loaded but did not call our provided callback'
),
JSONPScriptError: createCustomError(
'JSONPScriptError',
'<script> unable to load due to an `error` event on it'
),
Unknown: createCustomError(
'Unknown',
'Unknown error occured'
)
};
},{"6":6,"8":8}],25:[function(require,module,exports){
// Parse cloud does not supports setTimeout
// We do not store a setTimeout reference in the client everytime
// We only fallback to a fake setTimeout when not available
// setTimeout cannot be override globally sadly
module.exports = function exitPromise(fn, _setTimeout) {
_setTimeout(fn, 0);
};
},{}],26:[function(require,module,exports){
var foreach = require(6);
module.exports = function map(arr, fn) {
var newArr = [];
foreach(arr, function(item, itemIndex) {
newArr.push(fn(item, itemIndex, arr));
});
return newArr;
};
},{"6":6}],27:[function(require,module,exports){
var foreach = require(6);
module.exports = function merge(destination/* , sources */) {
var sources = Array.prototype.slice.call(arguments);
foreach(sources, function(source) {
for (var keyName in source) {
if (source.hasOwnProperty(keyName)) {
if (typeof destination[keyName] === 'object' && typeof source[keyName] === 'object') {
destination[keyName] = merge({}, destination[keyName], source[keyName]);
} else if (source[keyName] !== undefined) {
destination[keyName] = source[keyName];
}
}
}
});
return destination;
};
},{"6":6}],28:[function(require,module,exports){
module.exports = function omit(obj, test) {
var keys = require(10);
var foreach = require(6);
var filtered = {};
foreach(keys(obj), function doFilter(keyName) {
if (test(keyName) !== true) {
filtered[keyName] = obj[keyName];
}
});
return filtered;
};
},{"10":10,"6":6}],29:[function(require,module,exports){
module.exports = createPlacesClient;
var buildSearchMethod = require(20);
function createPlacesClient(algoliasearch) {
return function places(appID, apiKey, opts) {
var cloneDeep = require(21);
opts = opts && cloneDeep(opts) || {};
opts.hosts = opts.hosts || [
'places-dsn.algolia.net',
'places-1.algolianet.com',
'places-2.algolianet.com',
'places-3.algolianet.com'
];
// allow initPlaces() no arguments => community rate limited
if (arguments.length === 0 || typeof appID === 'object' || appID === undefined) {
appID = '';
apiKey = '';
opts._allowEmptyCredentials = true;
}
var client = algoliasearch(appID, apiKey, opts);
var index = client.initIndex('places');
index.search = buildSearchMethod('query', '/1/places/query');
return index;
};
}
},{"20":20,"21":21}],30:[function(require,module,exports){
'use strict';
module.exports = '3.19.2';
},{}]},{},[15])(15)
}); |
webpack/scenes/RedHatRepositories/components/SearchBar.js | adamruzicka/katello | /* eslint-disable import/no-extraneous-dependencies */
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Form, FormGroup } from 'react-bootstrap';
import { translate as __ } from 'foremanReact/common/I18n';
import { selectOrganizationProducts }
from '../../../redux/OrganizationProducts/OrganizationProductsSelectors';
import { loadOrganizationProducts }
from '../../../redux/OrganizationProducts/OrganizationProductsActions';
import { loadEnabledRepos } from '../../../redux/actions/RedHatRepositories/enabled';
import { loadRepositorySets } from '../../../redux/actions/RedHatRepositories/sets';
import Search from './Search';
import MultiSelect from '../../../components/MultiSelect/index';
const filterOptions = [
{ value: 'rpm', label: __('RPM') },
{ value: 'sourceRpm', label: __('Source RPM') },
{ value: 'debugRpm', label: __('Debug RPM') },
{ value: 'kickstart', label: __('Kickstart') },
{ value: 'ostree', label: __('OSTree') },
{ value: 'beta', label: __('Beta') },
{ value: 'other', label: __('Other') },
];
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = {
query: '',
searchList: 'available',
filters: ['rpm'],
};
this.onSearch = this.onSearch.bind(this);
this.onSelectSearchList = this.onSelectSearchList.bind(this);
}
componentDidMount() {
// load all products until we use filtering and pagination
this.props.loadOrganizationProducts({ per_page: 1000, redhat_only: true });
}
onSearch(query) {
this.updateSearch({ query });
}
onSelectSearchList(searchList) {
this.updateSearch({ searchList });
}
onSelectFilterType(filters) {
this.updateSearch({ filters });
}
onSelectProduct(products) {
this.updateSearch({ products });
}
updateSearch(stateUpdate = {}) {
const newState = {
...this.state,
...stateUpdate,
};
this.setState(stateUpdate);
const clearSearch = stateUpdate.searchList ? {} : null;
if (newState.searchList === 'available') {
this.reloadRepos(newState, clearSearch);
} else if (newState.searchList === 'enabled') {
this.reloadRepos(clearSearch, newState);
} else {
this.reloadRepos(newState, newState);
}
}
reloadRepos(repoSetsSearch, enabledSearch) {
if (repoSetsSearch !== null) {
const setsParams = {
perPage: this.props.repositorySets.pagination.perPage,
search: repoSetsSearch,
};
this.props.loadRepositorySets(setsParams);
}
if (enabledSearch !== null) {
const enabledParams = {
perPage: this.props.enabledRepositories.pagination.perPage,
search: enabledSearch,
};
this.props.loadEnabledRepos(enabledParams);
}
}
render() {
const { organizationProducts } = this.props;
const getMultiSelectValuesFromEvent = e => [...e.target.options]
.filter(({ selected }) => selected)
.map(({ value }) => value);
return (
<Form className="toolbar-pf-actions">
<div className="search-bar-row">
<FormGroup className="toolbar-pf-filter">
<Search onSearch={this.onSearch} onSelectSearchList={this.onSelectSearchList} />
</FormGroup>
</div>
<div className="search-bar-row search-bar-selects-row">
<MultiSelect
className="product-select"
value="product"
options={organizationProducts.map(product => ({
value: product.id, label: product.name,
}))}
defaultValues={[]}
noneSelectedText={__('Filter by Product')}
maxItemsCountForFullLabel={2}
onChange={(e) => {
const values = getMultiSelectValuesFromEvent(e);
this.onSelectProduct(values);
}}
/>
<MultiSelect
value={this.state.filters}
options={filterOptions}
defaultValues={['rpm']}
noneSelectedText={__('Filter by type')}
onChange={(e) => {
const values = [...e.target.options]
.filter(({ selected }) => selected)
.map(({ value }) => value);
this.onSelectFilterType(values);
}}
/>
</div>
</Form>
);
}
}
SearchBar.propTypes = {
loadEnabledRepos: PropTypes.func.isRequired,
loadRepositorySets: PropTypes.func.isRequired,
loadOrganizationProducts: PropTypes.func.isRequired,
organizationProducts: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
name: PropTypes.string,
})).isRequired,
enabledRepositories: PropTypes.shape({
pagination: PropTypes.shape({
perPage: PropTypes.number,
}),
}).isRequired,
repositorySets: PropTypes.shape({
pagination: PropTypes.shape({
perPage: PropTypes.number,
}),
}).isRequired,
};
const mapStateToProps = (state) => {
const { katello: { redHatRepositories: { enabled, sets } } } = state;
return {
enabledRepositories: enabled,
repositorySets: sets,
organizationProducts: selectOrganizationProducts(state),
};
};
export default connect(mapStateToProps, {
loadEnabledRepos,
loadRepositorySets,
loadOrganizationProducts,
})(SearchBar);
|
frontend/app/js/components/settings/user/edit.js | serverboards/serverboards | import React from 'react'
import Modal from 'app/components/modal'
import store from 'app/utils/store'
import i18n from 'app/utils/i18n'
import PropTypes from 'prop-types'
import {has_perm} from 'app/utils/perms'
class EditUser extends React.Component{
handleEditUser(ev){
ev.preventDefault()
const props=this.props
const show_is_active = props.user.email != store.getState().auth.user.email
let is_active = props.user.is_active
if (show_is_active)
is_active = $(this.refs.is_active).find('input').is(':checked') ? true : false
let $form = $(this.refs.form)
let changes = {
name: $form.find('[name=name]').val(),
is_active,
}
if (has_perm("auth.modify_any"))
changes.email = $form.find('[name=email]').val()
props.onUpdateUser( props.user.email, changes )
props.onClose()
}
componentDidMount(){
let $form = $(this.refs.form)
$form.form({
on:'blur',
fields:{
email: 'email'
}
})
$(this.refs.is_active).checkbox()
}
render(){
const props=this.props
// Only show if not current user
const show_is_active = props.user.email != store.getState().auth.user.email
return (
<Modal onClose={props.onClose}>
<div className="ui top secondary menu">
<h2 className="ui header">Edit {props.user.name}</h2>
<div className="right menu" style={{alignItems: "center"}}>
{show_is_active ? (
<div className="field">
<div ref="is_active" className="ui toggle checkbox">
<label>Is active</label>
<input type="checkbox" name="is_active" defaultChecked={props.user.is_active}/>
</div>
</div>
) : []}
</div>
</div>
<div className="content">
<div ref="form" className="ui form" onSubmit={this.handleEditUser.bind(this)}>
<div className="field">
<label>{i18n("Email")}</label>
<input disabled={!has_perm("auth.modify_any")} type="email" name="email" defaultValue={props.user.email} placeholder={i18n("This will be used as the user identifier")}/>
</div>
<div className="field">
<label>{i18n("First Name")}</label>
<input type="text" name="name" defaultValue={props.user.name}/>
</div>
</div>
<div className="actions">
<button className="ui accept teal button" onClick={this.handleEditUser.bind(this)}>{i18n("Update user")}</button>
</div>
</div>
</Modal>
)
}
}
EditUser.PropTypes = {
onUpdateUser: PropTypes.func.isRequired,
user: PropTypes.object.isRequired
}
export default EditUser
|
theme/src/components/checkoutForm/paymentForm/LiqPay.js | cezerin/cezerin | import React from 'react';
let scriptAdded = false;
export default class PayPalButton extends React.Component {
constructor(props) {
super(props);
}
addScript = () => {
if (scriptAdded) {
this.executeScript();
return;
}
const SCRIPT_URL = 'https://static.liqpay.ua/libjs/checkout.js';
const container = document.body || document.head;
const script = document.createElement('script');
script.src = SCRIPT_URL;
script.onload = () => {
this.executeScript();
};
container.appendChild(script);
scriptAdded = true;
};
executeScript = () => {
const { formSettings, shopSettings, onPayment } = this.props;
LiqPayCheckout.init({
data: formSettings.data,
signature: formSettings.signature,
language: formSettings.language,
embedTo: '#liqpay_checkout',
mode: 'embed'
})
.on('liqpay.callback', function(data) {
if (data.status === 'success') {
onPayment();
}
})
.on('liqpay.ready', function(data) {
// ready
})
.on('liqpay.close', function(data) {
// close
});
};
componentDidMount() {
this.addScript();
}
componentDidUpdate() {
this.executeScript();
}
render() {
const { formSettings, shopSettings, onPayment } = this.props;
return (
<div>
<div id="liqpay_checkout" />
</div>
);
}
}
|
src/assets/icons/camera.js | HackArdennes2017/Project06 | import React from 'react'
export default props =>
<svg viewBox="0 0 100 125" {...props}>
<path
fill="#fff"
d="M38 14c-.517.01-.729.273-.875.469L30.406 26H16c-5.523 0-10 4.478-10 10v40c0 5.523 4.477 10 10 10h68c5.523 0 10-4.477 10-10V36c0-5.522-4.477-10-10-10H69.594L62.875 14.47A1.02 1.02 0 0 0 62 14H38zm.594 2h22.812l5.844 10h-34.5l5.844-10zM16 28h68c4.45 0 8 3.55 8 8v40c0 4.45-3.55 8-8 8H16c-4.45 0-8-3.55-8-8V36c0-4.45 3.55-8 8-8zm34 6c-12.138 0-22 9.862-22 22 0 12.139 9.862 22 22 22s22-9.861 22-22c0-12.138-9.862-22-22-22zm0 2c11.058 0 20 8.943 20 20 0 11.058-8.942 20-20 20s-20-8.942-20-20c0-11.057 8.942-20 20-20zm29 0c-2.197 0-4 1.803-4 4 0 2.198 1.803 4 4 4s4-1.802 4-4c0-2.197-1.803-4-4-4zm0 2c1.116 0 2 .884 2 2 0 1.117-.884 2-2 2s-2-.883-2-2c0-1.116.884-2 2-2zm-29 6c-6.615 0-12 5.385-12 12 0 6.616 5.385 12 12 12s12-5.384 12-12c0-6.615-5.385-12-12-12zm0 2c5.535 0 10 4.466 10 10 0 5.535-4.465 10-10 10s-10-4.465-10-10c0-5.534 4.465-10 10-10z"
overflow="visible"
style={{
textIndent: '0',
textTransform: 'none',
direction: 'ltr',
blockProgression: 'tb',
baselineShift: 'baseline',
color: '#000',
enableBackground: 'accumulate',
}}
/>
</svg>
|
src/svg-icons/action/visibility.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionVisibility = (props) => (
<SvgIcon {...props}>
<path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
</SvgIcon>
);
ActionVisibility = pure(ActionVisibility);
ActionVisibility.displayName = 'ActionVisibility';
ActionVisibility.muiName = 'SvgIcon';
export default ActionVisibility;
|
src/parser/monk/windwalker/CONFIG.js | FaideWW/WoWAnalyzer | import React from 'react';
import { Juko8 } from 'CONTRIBUTORS';
import retryingPromise from 'common/retryingPromise';
import SPECS from 'game/SPECS';
import CHANGELOG from './CHANGELOG';
export default {
// The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion.
contributors: [Juko8],
// The WoW client patch this spec was last updated to be fully compatible with.
patchCompatibility: '8.0',
// If set to false`, the spec will show up as unsupported.
isSupported: true,
// Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more.
// If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component.
description: (
<>
Hello! We have been working hard to make the Windwalker analyzer good, but there is always stuff to add or improve. We hope that the suggestions and statistics will be helpful in improving your overall performance. It takes time to learn the Windwalker resource and cooldown management, so be patient with yourself while getting used to it. <br /> <br />
If you have any questions about the analyzer or Windwalker monks in general, join us in the <a href="https://discord.gg/0dkfBMAxzTkWj21F" target="_blank" rel="noopener noreferrer">Peak of Serenity discord server</a> and talk to us. You can reach me there as Juko8. Make sure to also check out our resources on the <a href="http://peakofserenity.com/windwalker/">Peak of Serenity website</a> as well, it has pretty much everything you need to know.
</>
),
// A recent example report to see interesting parts of the spec. Will be shown on the homepage.
exampleReport: '/report/Bg96KMa72x4kY8nV/16-Heroic+Vectis+-+Kill+(6:44)/3-Boeboe',
// Don't change anything below this line;
// The current spec identifier. This is the only place (in code) that specifies which spec this parser is about.
spec: SPECS.WINDWALKER_MONK,
// The contents of your changelog.
changelog: CHANGELOG,
// The CombatLogParser class for your spec.
parser: () => retryingPromise(() => import('./CombatLogParser' /* webpackChunkName: "WindwalkerMonk" */).then(exports => exports.default)),
// The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code.
path: __dirname,
};
|
ajax/libs/yasqe/2.3.7/yasqe.bundled.min.js | danut007ro/cdnjs | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.YASQE=e()}}(function(){var e;return function t(e,i,r){function n(s,a){if(!i[s]){if(!e[s]){var l="function"==typeof require&&require;if(!a&&l)return l(s,!0);if(o)return o(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var p=i[s]={exports:{}};e[s][0].call(p.exports,function(t){var i=e[s][1][t];return n(i?i:t)},p,p.exports,t,e,i,r)}return i[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)n(r[s]);return n}({1:[function(e,t){t.exports=e("./main.js")},{"./main.js":30}],2:[function(e){"use strict";var t=e("jquery");t.deparam=function(e,i){var r={},n={"true":!0,"false":!1,"null":null};t.each(e.replace(/\+/g," ").split("&"),function(e,o){var s,a=o.split("="),l=decodeURIComponent(a[0]),u=r,p=0,c=l.split("]["),d=c.length-1;if(/\[/.test(c[0])&&/\]$/.test(c[d])){c[d]=c[d].replace(/\]$/,"");c=c.shift().split("[").concat(c);d=c.length-1}else d=0;if(2===a.length){s=decodeURIComponent(a[1]);i&&(s=s&&!isNaN(s)?+s:"undefined"===s?void 0:void 0!==n[s]?n[s]:s);if(d)for(;d>=p;p++){l=""===c[p]?u.length:c[p];u=u[l]=d>p?u[l]||(c[p+1]&&isNaN(c[p+1])?{}:[]):s}else t.isArray(r[l])?r[l].push(s):r[l]=void 0!==r[l]?[r[l],s]:s}else l&&(r[l]=i?void 0:"")});return r}},{jquery:15}],3:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("codemirror")):"function"==typeof e&&e.amd?e(["codemirror"],n):n(CodeMirror)})(function(e){"use strict";e.defineMode("sparql11",function(e){function t(){var e,t,i="<[^<>\"'|{}^\\\x00- ]*>",r="[A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]",n=r+"|_",o="("+n+"|-|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])",s="("+n+"|[0-9])("+n+"|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])*",a="\\?"+s,l="\\$"+s,p="("+r+")((("+o+")|\\.)*("+o+"))?",c="[0-9A-Fa-f]",d="(%"+c+c+")",f="(\\\\[_~\\.\\-!\\$&'\\(\\)\\*\\+,;=/\\?#@%])",h="("+d+"|"+f+")";if("sparql11"==u){e="("+n+"|:|[0-9]|"+h+")(("+o+"|\\.|:|"+h+")*("+o+"|:|"+h+"))?";t="_:("+n+"|[0-9])(("+o+"|\\.)*"+o+")?"}else{e="("+n+"|[0-9])((("+o+")|\\.)*("+o+"))?";t="_:"+e}var E="("+p+")?:",m=E+e,g="@[a-zA-Z]+(-[a-zA-Z0-9]+)*",v="[eE][\\+-]?[0-9]+",x="[0-9]+",N="(([0-9]+\\.[0-9]*)|(\\.[0-9]+))",T="(([0-9]+\\.[0-9]*"+v+")|(\\.[0-9]+"+v+")|([0-9]+"+v+"))",L="\\+"+x,I="\\+"+N,y="\\+"+T,A="-"+x,S="-"+N,C="-"+T,R="\\\\[tbnrf\\\\\"']",b=c+"{4}",O="(\\\\u"+b+"|\\\\U00(10|0"+c+")"+b+")",P="'(([^\\x27\\x5C\\x0A\\x0D])|"+R+"|"+O+")*'",D='"(([^\\x22\\x5C\\x0A\\x0D])|'+R+"|"+O+')*"',w="'''(('|'')?([^'\\\\]|"+R+"|"+O+"))*'''",_='"""(("|"")?([^"\\\\]|'+R+"|"+O+'))*"""',M="[\\x20\\x09\\x0D\\x0A]",k="#([^\\n\\r]*[\\n\\r]|[^\\n\\r]*$)",G="("+M+"|("+k+"))*",B="\\("+G+"\\)",U="\\["+G+"\\]",V={terminal:[{name:"WS",regex:new RegExp("^"+M+"+"),style:"ws"},{name:"COMMENT",regex:new RegExp("^"+k),style:"comment"},{name:"IRI_REF",regex:new RegExp("^"+i),style:"variable-3"},{name:"VAR1",regex:new RegExp("^"+a),style:"atom"},{name:"VAR2",regex:new RegExp("^"+l),style:"atom"},{name:"LANGTAG",regex:new RegExp("^"+g),style:"meta"},{name:"DOUBLE",regex:new RegExp("^"+T),style:"number"},{name:"DECIMAL",regex:new RegExp("^"+N),style:"number"},{name:"INTEGER",regex:new RegExp("^"+x),style:"number"},{name:"DOUBLE_POSITIVE",regex:new RegExp("^"+y),style:"number"},{name:"DECIMAL_POSITIVE",regex:new RegExp("^"+I),style:"number"},{name:"INTEGER_POSITIVE",regex:new RegExp("^"+L),style:"number"},{name:"DOUBLE_NEGATIVE",regex:new RegExp("^"+C),style:"number"},{name:"DECIMAL_NEGATIVE",regex:new RegExp("^"+S),style:"number"},{name:"INTEGER_NEGATIVE",regex:new RegExp("^"+A),style:"number"},{name:"STRING_LITERAL_LONG1",regex:new RegExp("^"+w),style:"string"},{name:"STRING_LITERAL_LONG2",regex:new RegExp("^"+_),style:"string"},{name:"STRING_LITERAL1",regex:new RegExp("^"+P),style:"string"},{name:"STRING_LITERAL2",regex:new RegExp("^"+D),style:"string"},{name:"NIL",regex:new RegExp("^"+B),style:"punc"},{name:"ANON",regex:new RegExp("^"+U),style:"punc"},{name:"PNAME_LN",regex:new RegExp("^"+m),style:"string-2"},{name:"PNAME_NS",regex:new RegExp("^"+E),style:"string-2"},{name:"BLANK_NODE_LABEL",regex:new RegExp("^"+t),style:"string-2"}]};return V}function i(e){var t=[],i=o[e];if(void 0!=i)for(var r in i)t.push(r.toString());else t.push(e);return t}function r(e,t){function r(){for(var t=null,i=0;i<f.length;++i){t=e.match(f[i].regex,!0,!1);if(t)return{cat:f[i].name,style:f[i].style,text:t[0]}}t=e.match(s,!0,!1);if(t)return{cat:e.current().toUpperCase(),style:"keyword",text:t[0]};t=e.match(a,!0,!1);if(t)return{cat:e.current(),style:"punc",text:t[0]};t=e.match(/^.[A-Za-z0-9]*/,!0,!1);return{cat:"<invalid_token>",style:"error",text:t[0]}}function n(){var i=e.column();t.errorStartPos=i;t.errorEndPos=i+c.text.length}function l(e){null==t.queryType&&("SELECT"==e||"CONSTRUCT"==e||"ASK"==e||"DESCRIBE"==e||"INSERT"==e||"DELETE"==e||"LOAD"==e||"CLEAR"==e||"CREATE"==e||"DROP"==e||"COPY"==e||"MOVE"==e||"ADD"==e)&&(t.queryType=e)}function u(e){"disallowVars"==e?t.allowVars=!1:"allowVars"==e?t.allowVars=!0:"disallowBnodes"==e?t.allowBnodes=!1:"allowBnodes"==e?t.allowBnodes=!0:"storeProperty"==e&&(t.storeProperty=!0)}function p(e){return(t.allowVars||"var"!=e)&&(t.allowBnodes||"blankNode"!=e&&"blankNodePropertyList"!=e&&"blankNodePropertyListPath"!=e)}0==e.pos&&(t.possibleCurrent=t.possibleNext);var c=r();if("<invalid_token>"==c.cat){if(1==t.OK){t.OK=!1;n()}t.complete=!1;return c.style}if("WS"==c.cat||"COMMENT"==c.cat){t.possibleCurrent=t.possibleNext;return c.style}for(var d,h=!1,E=c.cat;t.stack.length>0&&E&&t.OK&&!h;){d=t.stack.pop();if(o[d]){var m=o[d][E];if(void 0!=m&&p(d)){for(var g=m.length-1;g>=0;--g)t.stack.push(m[g]);u(d)}else{t.OK=!1;t.complete=!1;n();t.stack.push(d)}}else if(d==E){h=!0;l(d);for(var v=!0,x=t.stack.length;x>0;--x){var N=o[t.stack[x-1]];N&&N.$||(v=!1)}t.complete=v;if(t.storeProperty&&"punc"!=E.cat){t.lastProperty=c.text;t.storeProperty=!1}}else{t.OK=!1;t.complete=!1;n()}}if(!h&&t.OK){t.OK=!1;t.complete=!1;n()}t.possibleCurrent=t.possibleNext;t.possibleNext=i(t.stack[t.stack.length-1]);return c.style}function n(t,i){var r=0,n=t.stack.length-1;if(/^[\}\]\)]/.test(i)){for(var o=i.substr(0,1);n>=0;--n)if(t.stack[n]==o){--n;break}}else{var s=h[t.stack[n]];if(s){r+=s;--n}}for(;n>=0;--n){var s=E[t.stack[n]];s&&(r+=s)}return r*e.indentUnit}var o=(e.indentUnit,{"*[&&,valueLogical]":{"&&":["[&&,valueLogical]","*[&&,valueLogical]"],AS:[],")":[],",":[],"||":[],";":[]},"*[,,expression]":{",":["[,,expression]","*[,,expression]"],")":[]},"*[,,objectPath]":{",":["[,,objectPath]","*[,,objectPath]"],".":[],";":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[,,object]":{",":["[,,object]","*[,,object]"],".":[],";":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[/,pathEltOrInverse]":{"/":["[/,pathEltOrInverse]","*[/,pathEltOrInverse]"],"|":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[;,?[or([verbPath,verbSimple]),objectList]]":{";":["[;,?[or([verbPath,verbSimple]),objectList]]","*[;,?[or([verbPath,verbSimple]),objectList]]"],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[;,?[verb,objectList]]":{";":["[;,?[verb,objectList]]","*[;,?[verb,objectList]]"],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[UNION,groupGraphPattern]":{UNION:["[UNION,groupGraphPattern]","*[UNION,groupGraphPattern]"],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[graphPatternNotTriples,?.,?triplesBlock]":{"{":["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":[]},"*[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["[quadsNotTriples,?.,?triplesTemplate]","*[quadsNotTriples,?.,?triplesTemplate]"],"}":[]},"*[|,pathOneInPropertySet]":{"|":["[|,pathOneInPropertySet]","*[|,pathOneInPropertySet]"],")":[]},"*[|,pathSequence]":{"|":["[|,pathSequence]","*[|,pathSequence]"],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[||,conditionalAndExpression]":{"||":["[||,conditionalAndExpression]","*[||,conditionalAndExpression]"],AS:[],")":[],",":[],";":[]},"*dataBlockValue":{UNDEF:["dataBlockValue","*dataBlockValue"],IRI_REF:["dataBlockValue","*dataBlockValue"],TRUE:["dataBlockValue","*dataBlockValue"],FALSE:["dataBlockValue","*dataBlockValue"],PNAME_LN:["dataBlockValue","*dataBlockValue"],PNAME_NS:["dataBlockValue","*dataBlockValue"],STRING_LITERAL1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL2:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG2:["dataBlockValue","*dataBlockValue"],INTEGER:["dataBlockValue","*dataBlockValue"],DECIMAL:["dataBlockValue","*dataBlockValue"],DOUBLE:["dataBlockValue","*dataBlockValue"],INTEGER_POSITIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_POSITIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_POSITIVE:["dataBlockValue","*dataBlockValue"],INTEGER_NEGATIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_NEGATIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_NEGATIVE:["dataBlockValue","*dataBlockValue"],"}":[],")":[]},"*datasetClause":{FROM:["datasetClause","*datasetClause"],WHERE:[],"{":[]},"*describeDatasetClause":{FROM:["describeDatasetClause","*describeDatasetClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],VALUES:[],$:[]},"*graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"],")":[]},"*graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"],")":[]},"*groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"*havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"*or([[ (,*dataBlockValue,)],NIL])":{"(":["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],NIL:["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],"}":[]},"*or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],";":[]},"*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"*or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],WHERE:[],"{":[],FROM:[]},"*orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"*prefixDecl":{PREFIX:["prefixDecl","*prefixDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[]},"*usingClause":{USING:["usingClause","*usingClause"],WHERE:[]},"*var":{VAR1:["var","*var"],VAR2:["var","*var"],")":[]},"*varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],FROM:[],VALUES:[],$:[]},"+graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"]},"+graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"]},"+groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"]},"+havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"]},"+or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"]},"+orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"]},"+varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"]},"?.":{".":["."],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?DISTINCT":{DISTINCT:["DISTINCT"],"!":[],"+":[],"-":[],VAR1:[],VAR2:[],"(":[],STR:[],LANG:[],LANGMATCHES:[],DATATYPE:[],BOUND:[],IRI:[],URI:[],BNODE:[],RAND:[],ABS:[],CEIL:[],FLOOR:[],ROUND:[],CONCAT:[],STRLEN:[],UCASE:[],LCASE:[],ENCODE_FOR_URI:[],CONTAINS:[],STRSTARTS:[],STRENDS:[],STRBEFORE:[],STRAFTER:[],YEAR:[],MONTH:[],DAY:[],HOURS:[],MINUTES:[],SECONDS:[],TIMEZONE:[],TZ:[],NOW:[],UUID:[],STRUUID:[],MD5:[],SHA1:[],SHA256:[],SHA384:[],SHA512:[],COALESCE:[],IF:[],STRLANG:[],STRDT:[],SAMETERM:[],ISIRI:[],ISURI:[],ISBLANK:[],ISLITERAL:[],ISNUMERIC:[],TRUE:[],FALSE:[],COUNT:[],SUM:[],MIN:[],MAX:[],AVG:[],SAMPLE:[],GROUP_CONCAT:[],SUBSTR:[],REPLACE:[],REGEX:[],EXISTS:[],NOT:[],IRI_REF:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],PNAME_LN:[],PNAME_NS:[],"*":[]},"?GRAPH":{GRAPH:["GRAPH"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT":{SILENT:["SILENT"],VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_1":{SILENT:["SILENT"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_2":{SILENT:["SILENT"],GRAPH:[],DEFAULT:[],NAMED:[],ALL:[]},"?SILENT_3":{SILENT:["SILENT"],GRAPH:[]},"?SILENT_4":{SILENT:["SILENT"],DEFAULT:[],GRAPH:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?WHERE":{WHERE:["WHERE"],"{":[]},"?[,,expression]":{",":["[,,expression]"],")":[]},"?[.,?constructTriples]":{".":["[.,?constructTriples]"],"}":[]},"?[.,?triplesBlock]":{".":["[.,?triplesBlock]"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[.,?triplesTemplate]":{".":["[.,?triplesTemplate]"],"}":[],GRAPH:[]},"?[;,SEPARATOR,=,string]":{";":["[;,SEPARATOR,=,string]"],")":[]},"?[;,update]":{";":["[;,update]"],$:[]},"?[AS,var]":{AS:["[AS,var]"],")":[]},"?[INTO,graphRef]":{INTO:["[INTO,graphRef]"],";":[],$:[]},"?[or([verbPath,verbSimple]),objectList]":{VAR1:["[or([verbPath,verbSimple]),objectList]"],VAR2:["[or([verbPath,verbSimple]),objectList]"],"^":["[or([verbPath,verbSimple]),objectList]"],a:["[or([verbPath,verbSimple]),objectList]"],"!":["[or([verbPath,verbSimple]),objectList]"],"(":["[or([verbPath,verbSimple]),objectList]"],IRI_REF:["[or([verbPath,verbSimple]),objectList]"],PNAME_LN:["[or([verbPath,verbSimple]),objectList]"],PNAME_NS:["[or([verbPath,verbSimple]),objectList]"],";":[],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],"^":["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],IRI_REF:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_LN:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_NS:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],")":[]},"?[update1,?[;,update]]":{INSERT:["[update1,?[;,update]]"],DELETE:["[update1,?[;,update]]"],LOAD:["[update1,?[;,update]]"],CLEAR:["[update1,?[;,update]]"],DROP:["[update1,?[;,update]]"],ADD:["[update1,?[;,update]]"],MOVE:["[update1,?[;,update]]"],COPY:["[update1,?[;,update]]"],CREATE:["[update1,?[;,update]]"],WITH:["[update1,?[;,update]]"],$:[]},"?[verb,objectList]":{a:["[verb,objectList]"],VAR1:["[verb,objectList]"],VAR2:["[verb,objectList]"],IRI_REF:["[verb,objectList]"],PNAME_LN:["[verb,objectList]"],PNAME_NS:["[verb,objectList]"],";":[],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?argList":{NIL:["argList"],"(":["argList"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],"*":[],"/":[],";":[]},"?baseDecl":{BASE:["baseDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[],PREFIX:[]},"?constructTriples":{VAR1:["constructTriples"],VAR2:["constructTriples"],NIL:["constructTriples"],"(":["constructTriples"],"[":["constructTriples"],IRI_REF:["constructTriples"],TRUE:["constructTriples"],FALSE:["constructTriples"],BLANK_NODE_LABEL:["constructTriples"],ANON:["constructTriples"],PNAME_LN:["constructTriples"],PNAME_NS:["constructTriples"],STRING_LITERAL1:["constructTriples"],STRING_LITERAL2:["constructTriples"],STRING_LITERAL_LONG1:["constructTriples"],STRING_LITERAL_LONG2:["constructTriples"],INTEGER:["constructTriples"],DECIMAL:["constructTriples"],DOUBLE:["constructTriples"],INTEGER_POSITIVE:["constructTriples"],DECIMAL_POSITIVE:["constructTriples"],DOUBLE_POSITIVE:["constructTriples"],INTEGER_NEGATIVE:["constructTriples"],DECIMAL_NEGATIVE:["constructTriples"],DOUBLE_NEGATIVE:["constructTriples"],"}":[]},"?groupClause":{GROUP:["groupClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"?havingClause":{HAVING:["havingClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"?insertClause":{INSERT:["insertClause"],WHERE:[],USING:[]},"?limitClause":{LIMIT:["limitClause"],VALUES:[],$:[],"}":[]},"?limitOffsetClauses":{LIMIT:["limitOffsetClauses"],OFFSET:["limitOffsetClauses"],VALUES:[],$:[],"}":[]},"?offsetClause":{OFFSET:["offsetClause"],VALUES:[],$:[],"}":[]},"?or([DISTINCT,REDUCED])":{DISTINCT:["or([DISTINCT,REDUCED])"],REDUCED:["or([DISTINCT,REDUCED])"],"*":[],"(":[],VAR1:[],VAR2:[]},"?or([LANGTAG,[^^,iriRef]])":{LANGTAG:["or([LANGTAG,[^^,iriRef]])"],"^^":["or([LANGTAG,[^^,iriRef]])"],UNDEF:[],IRI_REF:[],TRUE:[],FALSE:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],a:[],VAR1:[],VAR2:[],"^":[],"!":[],"(":[],".":[],";":[],",":[],AS:[],")":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],"*":[],"/":[],"}":[],"[":[],NIL:[],BLANK_NODE_LABEL:[],ANON:[],"]":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])"],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"!=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IN:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AS:[],")":[],",":[],"||":[],"&&":[],";":[]},"?orderClause":{ORDER:["orderClause"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"?pathMod":{"*":["pathMod"],"?":["pathMod"],"+":["pathMod"],"{":["pathMod"],"|":[],"/":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"?triplesBlock":{VAR1:["triplesBlock"],VAR2:["triplesBlock"],NIL:["triplesBlock"],"(":["triplesBlock"],"[":["triplesBlock"],IRI_REF:["triplesBlock"],TRUE:["triplesBlock"],FALSE:["triplesBlock"],BLANK_NODE_LABEL:["triplesBlock"],ANON:["triplesBlock"],PNAME_LN:["triplesBlock"],PNAME_NS:["triplesBlock"],STRING_LITERAL1:["triplesBlock"],STRING_LITERAL2:["triplesBlock"],STRING_LITERAL_LONG1:["triplesBlock"],STRING_LITERAL_LONG2:["triplesBlock"],INTEGER:["triplesBlock"],DECIMAL:["triplesBlock"],DOUBLE:["triplesBlock"],INTEGER_POSITIVE:["triplesBlock"],DECIMAL_POSITIVE:["triplesBlock"],DOUBLE_POSITIVE:["triplesBlock"],INTEGER_NEGATIVE:["triplesBlock"],DECIMAL_NEGATIVE:["triplesBlock"],DOUBLE_NEGATIVE:["triplesBlock"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?triplesTemplate":{VAR1:["triplesTemplate"],VAR2:["triplesTemplate"],NIL:["triplesTemplate"],"(":["triplesTemplate"],"[":["triplesTemplate"],IRI_REF:["triplesTemplate"],TRUE:["triplesTemplate"],FALSE:["triplesTemplate"],BLANK_NODE_LABEL:["triplesTemplate"],ANON:["triplesTemplate"],PNAME_LN:["triplesTemplate"],PNAME_NS:["triplesTemplate"],STRING_LITERAL1:["triplesTemplate"],STRING_LITERAL2:["triplesTemplate"],STRING_LITERAL_LONG1:["triplesTemplate"],STRING_LITERAL_LONG2:["triplesTemplate"],INTEGER:["triplesTemplate"],DECIMAL:["triplesTemplate"],DOUBLE:["triplesTemplate"],INTEGER_POSITIVE:["triplesTemplate"],DECIMAL_POSITIVE:["triplesTemplate"],DOUBLE_POSITIVE:["triplesTemplate"],INTEGER_NEGATIVE:["triplesTemplate"],DECIMAL_NEGATIVE:["triplesTemplate"],DOUBLE_NEGATIVE:["triplesTemplate"],"}":[],GRAPH:[]},"?whereClause":{WHERE:["whereClause"],"{":["whereClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],VALUES:[],$:[]},"[ (,*dataBlockValue,)]":{"(":["(","*dataBlockValue",")"]},"[ (,*var,)]":{"(":["(","*var",")"]},"[ (,expression,)]":{"(":["(","expression",")"]},"[ (,expression,AS,var,)]":{"(":["(","expression","AS","var",")"]},"[!=,numericExpression]":{"!=":["!=","numericExpression"]},"[&&,valueLogical]":{"&&":["&&","valueLogical"]},"[*,unaryExpression]":{"*":["*","unaryExpression"]},"[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]":{WHERE:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"],FROM:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"]},"[+,multiplicativeExpression]":{"+":["+","multiplicativeExpression"]},"[,,expression]":{",":[",","expression"]},"[,,integer,}]":{",":[",","integer","}"]},"[,,objectPath]":{",":[",","objectPath"]},"[,,object]":{",":[",","object"]},"[,,or([},[integer,}]])]":{",":[",","or([},[integer,}]])"]},"[-,multiplicativeExpression]":{"-":["-","multiplicativeExpression"]},"[.,?constructTriples]":{".":[".","?constructTriples"]},"[.,?triplesBlock]":{".":[".","?triplesBlock"]},"[.,?triplesTemplate]":{".":[".","?triplesTemplate"]},"[/,pathEltOrInverse]":{"/":["/","pathEltOrInverse"]},"[/,unaryExpression]":{"/":["/","unaryExpression"]},"[;,?[or([verbPath,verbSimple]),objectList]]":{";":[";","?[or([verbPath,verbSimple]),objectList]"]},"[;,?[verb,objectList]]":{";":[";","?[verb,objectList]"]},"[;,SEPARATOR,=,string]":{";":[";","SEPARATOR","=","string"]},"[;,update]":{";":[";","update"]},"[<,numericExpression]":{"<":["<","numericExpression"]},"[<=,numericExpression]":{"<=":["<=","numericExpression"]},"[=,numericExpression]":{"=":["=","numericExpression"]},"[>,numericExpression]":{">":[">","numericExpression"]},"[>=,numericExpression]":{">=":[">=","numericExpression"]},"[AS,var]":{AS:["AS","var"]},"[IN,expressionList]":{IN:["IN","expressionList"]},"[INTO,graphRef]":{INTO:["INTO","graphRef"]},"[NAMED,iriRef]":{NAMED:["NAMED","iriRef"]},"[NOT,IN,expressionList]":{NOT:["NOT","IN","expressionList"]},"[UNION,groupGraphPattern]":{UNION:["UNION","groupGraphPattern"]},"[^^,iriRef]":{"^^":["^^","iriRef"]},"[constructTemplate,*datasetClause,whereClause,solutionModifier]":{"{":["constructTemplate","*datasetClause","whereClause","solutionModifier"]},"[deleteClause,?insertClause]":{DELETE:["deleteClause","?insertClause"]},"[graphPatternNotTriples,?.,?triplesBlock]":{"{":["graphPatternNotTriples","?.","?triplesBlock"],OPTIONAL:["graphPatternNotTriples","?.","?triplesBlock"],MINUS:["graphPatternNotTriples","?.","?triplesBlock"],GRAPH:["graphPatternNotTriples","?.","?triplesBlock"],SERVICE:["graphPatternNotTriples","?.","?triplesBlock"],FILTER:["graphPatternNotTriples","?.","?triplesBlock"],BIND:["graphPatternNotTriples","?.","?triplesBlock"],VALUES:["graphPatternNotTriples","?.","?triplesBlock"]},"[integer,or([[,,or([},[integer,}]])],}])]":{INTEGER:["integer","or([[,,or([},[integer,}]])],}])"]},"[integer,}]":{INTEGER:["integer","}"]},"[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]":{INTEGER_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"]},"[or([verbPath,verbSimple]),objectList]":{VAR1:["or([verbPath,verbSimple])","objectList"],VAR2:["or([verbPath,verbSimple])","objectList"],"^":["or([verbPath,verbSimple])","objectList"],a:["or([verbPath,verbSimple])","objectList"],"!":["or([verbPath,verbSimple])","objectList"],"(":["or([verbPath,verbSimple])","objectList"],IRI_REF:["or([verbPath,verbSimple])","objectList"],PNAME_LN:["or([verbPath,verbSimple])","objectList"],PNAME_NS:["or([verbPath,verbSimple])","objectList"]},"[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],"^":["pathOneInPropertySet","*[|,pathOneInPropertySet]"],IRI_REF:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_LN:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_NS:["pathOneInPropertySet","*[|,pathOneInPropertySet]"]},"[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["quadsNotTriples","?.","?triplesTemplate"]},"[update1,?[;,update]]":{INSERT:["update1","?[;,update]"],DELETE:["update1","?[;,update]"],LOAD:["update1","?[;,update]"],CLEAR:["update1","?[;,update]"],DROP:["update1","?[;,update]"],ADD:["update1","?[;,update]"],MOVE:["update1","?[;,update]"],COPY:["update1","?[;,update]"],CREATE:["update1","?[;,update]"],WITH:["update1","?[;,update]"]},"[verb,objectList]":{a:["verb","objectList"],VAR1:["verb","objectList"],VAR2:["verb","objectList"],IRI_REF:["verb","objectList"],PNAME_LN:["verb","objectList"],PNAME_NS:["verb","objectList"]},"[|,pathOneInPropertySet]":{"|":["|","pathOneInPropertySet"]},"[|,pathSequence]":{"|":["|","pathSequence"]},"[||,conditionalAndExpression]":{"||":["||","conditionalAndExpression"]},add:{ADD:["ADD","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},additiveExpression:{"!":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"+":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"(":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANGMATCHES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DATATYPE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BOUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BNODE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],RAND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ABS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CEIL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FLOOR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ROUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLEN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ENCODE_FOR_URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONTAINS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRSTARTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRENDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRBEFORE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRAFTER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],YEAR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MONTH:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DAY:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],HOURS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MINUTES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SECONDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TIMEZONE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TZ:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOW:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRUUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MD5:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA256:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA384:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA512:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COALESCE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRDT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMETERM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISIRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISURI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISBLANK:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISLITERAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISNUMERIC:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TRUE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FALSE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COUNT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MIN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MAX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AVG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMPLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],GROUP_CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUBSTR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REPLACE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REGEX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],EXISTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI_REF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_LN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_NS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"]},aggregate:{COUNT:["COUNT","(","?DISTINCT","or([*,expression])",")"],SUM:["SUM","(","?DISTINCT","expression",")"],MIN:["MIN","(","?DISTINCT","expression",")"],MAX:["MAX","(","?DISTINCT","expression",")"],AVG:["AVG","(","?DISTINCT","expression",")"],SAMPLE:["SAMPLE","(","?DISTINCT","expression",")"],GROUP_CONCAT:["GROUP_CONCAT","(","?DISTINCT","expression","?[;,SEPARATOR,=,string]",")"]},allowBnodes:{"}":[]},allowVars:{"}":[]},argList:{NIL:["NIL"],"(":["(","?DISTINCT","expression","*[,,expression]",")"]},askQuery:{ASK:["ASK","*datasetClause","whereClause","solutionModifier"]},baseDecl:{BASE:["BASE","IRI_REF"]},bind:{BIND:["BIND","(","expression","AS","var",")"]},blankNode:{BLANK_NODE_LABEL:["BLANK_NODE_LABEL"],ANON:["ANON"]},blankNodePropertyList:{"[":["[","propertyListNotEmpty","]"]},blankNodePropertyListPath:{"[":["[","propertyListPathNotEmpty","]"]},booleanLiteral:{TRUE:["TRUE"],FALSE:["FALSE"]},brackettedExpression:{"(":["(","expression",")"]},builtInCall:{STR:["STR","(","expression",")"],LANG:["LANG","(","expression",")"],LANGMATCHES:["LANGMATCHES","(","expression",",","expression",")"],DATATYPE:["DATATYPE","(","expression",")"],BOUND:["BOUND","(","var",")"],IRI:["IRI","(","expression",")"],URI:["URI","(","expression",")"],BNODE:["BNODE","or([[ (,expression,)],NIL])"],RAND:["RAND","NIL"],ABS:["ABS","(","expression",")"],CEIL:["CEIL","(","expression",")"],FLOOR:["FLOOR","(","expression",")"],ROUND:["ROUND","(","expression",")"],CONCAT:["CONCAT","expressionList"],SUBSTR:["substringExpression"],STRLEN:["STRLEN","(","expression",")"],REPLACE:["strReplaceExpression"],UCASE:["UCASE","(","expression",")"],LCASE:["LCASE","(","expression",")"],ENCODE_FOR_URI:["ENCODE_FOR_URI","(","expression",")"],CONTAINS:["CONTAINS","(","expression",",","expression",")"],STRSTARTS:["STRSTARTS","(","expression",",","expression",")"],STRENDS:["STRENDS","(","expression",",","expression",")"],STRBEFORE:["STRBEFORE","(","expression",",","expression",")"],STRAFTER:["STRAFTER","(","expression",",","expression",")"],YEAR:["YEAR","(","expression",")"],MONTH:["MONTH","(","expression",")"],DAY:["DAY","(","expression",")"],HOURS:["HOURS","(","expression",")"],MINUTES:["MINUTES","(","expression",")"],SECONDS:["SECONDS","(","expression",")"],TIMEZONE:["TIMEZONE","(","expression",")"],TZ:["TZ","(","expression",")"],NOW:["NOW","NIL"],UUID:["UUID","NIL"],STRUUID:["STRUUID","NIL"],MD5:["MD5","(","expression",")"],SHA1:["SHA1","(","expression",")"],SHA256:["SHA256","(","expression",")"],SHA384:["SHA384","(","expression",")"],SHA512:["SHA512","(","expression",")"],COALESCE:["COALESCE","expressionList"],IF:["IF","(","expression",",","expression",",","expression",")"],STRLANG:["STRLANG","(","expression",",","expression",")"],STRDT:["STRDT","(","expression",",","expression",")"],SAMETERM:["SAMETERM","(","expression",",","expression",")"],ISIRI:["ISIRI","(","expression",")"],ISURI:["ISURI","(","expression",")"],ISBLANK:["ISBLANK","(","expression",")"],ISLITERAL:["ISLITERAL","(","expression",")"],ISNUMERIC:["ISNUMERIC","(","expression",")"],REGEX:["regexExpression"],EXISTS:["existsFunc"],NOT:["notExistsFunc"]},clear:{CLEAR:["CLEAR","?SILENT_2","graphRefAll"]},collection:{"(":["(","+graphNode",")"]},collectionPath:{"(":["(","+graphNodePath",")"]},conditionalAndExpression:{"!":["valueLogical","*[&&,valueLogical]"],"+":["valueLogical","*[&&,valueLogical]"],"-":["valueLogical","*[&&,valueLogical]"],VAR1:["valueLogical","*[&&,valueLogical]"],VAR2:["valueLogical","*[&&,valueLogical]"],"(":["valueLogical","*[&&,valueLogical]"],STR:["valueLogical","*[&&,valueLogical]"],LANG:["valueLogical","*[&&,valueLogical]"],LANGMATCHES:["valueLogical","*[&&,valueLogical]"],DATATYPE:["valueLogical","*[&&,valueLogical]"],BOUND:["valueLogical","*[&&,valueLogical]"],IRI:["valueLogical","*[&&,valueLogical]"],URI:["valueLogical","*[&&,valueLogical]"],BNODE:["valueLogical","*[&&,valueLogical]"],RAND:["valueLogical","*[&&,valueLogical]"],ABS:["valueLogical","*[&&,valueLogical]"],CEIL:["valueLogical","*[&&,valueLogical]"],FLOOR:["valueLogical","*[&&,valueLogical]"],ROUND:["valueLogical","*[&&,valueLogical]"],CONCAT:["valueLogical","*[&&,valueLogical]"],STRLEN:["valueLogical","*[&&,valueLogical]"],UCASE:["valueLogical","*[&&,valueLogical]"],LCASE:["valueLogical","*[&&,valueLogical]"],ENCODE_FOR_URI:["valueLogical","*[&&,valueLogical]"],CONTAINS:["valueLogical","*[&&,valueLogical]"],STRSTARTS:["valueLogical","*[&&,valueLogical]"],STRENDS:["valueLogical","*[&&,valueLogical]"],STRBEFORE:["valueLogical","*[&&,valueLogical]"],STRAFTER:["valueLogical","*[&&,valueLogical]"],YEAR:["valueLogical","*[&&,valueLogical]"],MONTH:["valueLogical","*[&&,valueLogical]"],DAY:["valueLogical","*[&&,valueLogical]"],HOURS:["valueLogical","*[&&,valueLogical]"],MINUTES:["valueLogical","*[&&,valueLogical]"],SECONDS:["valueLogical","*[&&,valueLogical]"],TIMEZONE:["valueLogical","*[&&,valueLogical]"],TZ:["valueLogical","*[&&,valueLogical]"],NOW:["valueLogical","*[&&,valueLogical]"],UUID:["valueLogical","*[&&,valueLogical]"],STRUUID:["valueLogical","*[&&,valueLogical]"],MD5:["valueLogical","*[&&,valueLogical]"],SHA1:["valueLogical","*[&&,valueLogical]"],SHA256:["valueLogical","*[&&,valueLogical]"],SHA384:["valueLogical","*[&&,valueLogical]"],SHA512:["valueLogical","*[&&,valueLogical]"],COALESCE:["valueLogical","*[&&,valueLogical]"],IF:["valueLogical","*[&&,valueLogical]"],STRLANG:["valueLogical","*[&&,valueLogical]"],STRDT:["valueLogical","*[&&,valueLogical]"],SAMETERM:["valueLogical","*[&&,valueLogical]"],ISIRI:["valueLogical","*[&&,valueLogical]"],ISURI:["valueLogical","*[&&,valueLogical]"],ISBLANK:["valueLogical","*[&&,valueLogical]"],ISLITERAL:["valueLogical","*[&&,valueLogical]"],ISNUMERIC:["valueLogical","*[&&,valueLogical]"],TRUE:["valueLogical","*[&&,valueLogical]"],FALSE:["valueLogical","*[&&,valueLogical]"],COUNT:["valueLogical","*[&&,valueLogical]"],SUM:["valueLogical","*[&&,valueLogical]"],MIN:["valueLogical","*[&&,valueLogical]"],MAX:["valueLogical","*[&&,valueLogical]"],AVG:["valueLogical","*[&&,valueLogical]"],SAMPLE:["valueLogical","*[&&,valueLogical]"],GROUP_CONCAT:["valueLogical","*[&&,valueLogical]"],SUBSTR:["valueLogical","*[&&,valueLogical]"],REPLACE:["valueLogical","*[&&,valueLogical]"],REGEX:["valueLogical","*[&&,valueLogical]"],EXISTS:["valueLogical","*[&&,valueLogical]"],NOT:["valueLogical","*[&&,valueLogical]"],IRI_REF:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL2:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG2:["valueLogical","*[&&,valueLogical]"],INTEGER:["valueLogical","*[&&,valueLogical]"],DECIMAL:["valueLogical","*[&&,valueLogical]"],DOUBLE:["valueLogical","*[&&,valueLogical]"],INTEGER_POSITIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_POSITIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_POSITIVE:["valueLogical","*[&&,valueLogical]"],INTEGER_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_NEGATIVE:["valueLogical","*[&&,valueLogical]"],PNAME_LN:["valueLogical","*[&&,valueLogical]"],PNAME_NS:["valueLogical","*[&&,valueLogical]"]},conditionalOrExpression:{"!":["conditionalAndExpression","*[||,conditionalAndExpression]"],"+":["conditionalAndExpression","*[||,conditionalAndExpression]"],"-":["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR1:["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR2:["conditionalAndExpression","*[||,conditionalAndExpression]"],"(":["conditionalAndExpression","*[||,conditionalAndExpression]"],STR:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANGMATCHES:["conditionalAndExpression","*[||,conditionalAndExpression]"],DATATYPE:["conditionalAndExpression","*[||,conditionalAndExpression]"],BOUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],BNODE:["conditionalAndExpression","*[||,conditionalAndExpression]"],RAND:["conditionalAndExpression","*[||,conditionalAndExpression]"],ABS:["conditionalAndExpression","*[||,conditionalAndExpression]"],CEIL:["conditionalAndExpression","*[||,conditionalAndExpression]"],FLOOR:["conditionalAndExpression","*[||,conditionalAndExpression]"],ROUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLEN:["conditionalAndExpression","*[||,conditionalAndExpression]"],UCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],LCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],ENCODE_FOR_URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONTAINS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRSTARTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRENDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRBEFORE:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRAFTER:["conditionalAndExpression","*[||,conditionalAndExpression]"],YEAR:["conditionalAndExpression","*[||,conditionalAndExpression]"],MONTH:["conditionalAndExpression","*[||,conditionalAndExpression]"],DAY:["conditionalAndExpression","*[||,conditionalAndExpression]"],HOURS:["conditionalAndExpression","*[||,conditionalAndExpression]"],MINUTES:["conditionalAndExpression","*[||,conditionalAndExpression]"],SECONDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],TIMEZONE:["conditionalAndExpression","*[||,conditionalAndExpression]"],TZ:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOW:["conditionalAndExpression","*[||,conditionalAndExpression]"],UUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRUUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],MD5:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA1:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA256:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA384:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA512:["conditionalAndExpression","*[||,conditionalAndExpression]"],COALESCE:["conditionalAndExpression","*[||,conditionalAndExpression]"],IF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRDT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMETERM:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISIRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISURI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISBLANK:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISLITERAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISNUMERIC:["conditionalAndExpression","*[||,conditionalAndExpression]"],TRUE:["conditionalAndExpression","*[||,conditionalAndExpression]"],FALSE:["conditionalAndExpression","*[||,conditionalAndExpression]"],COUNT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUM:["conditionalAndExpression","*[||,conditionalAndExpression]"],MIN:["conditionalAndExpression","*[||,conditionalAndExpression]"],MAX:["conditionalAndExpression","*[||,conditionalAndExpression]"],AVG:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMPLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],GROUP_CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUBSTR:["conditionalAndExpression","*[||,conditionalAndExpression]"],REPLACE:["conditionalAndExpression","*[||,conditionalAndExpression]"],REGEX:["conditionalAndExpression","*[||,conditionalAndExpression]"],EXISTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOT:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI_REF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL2:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG2:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_LN:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_NS:["conditionalAndExpression","*[||,conditionalAndExpression]"]},constraint:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"]},constructQuery:{CONSTRUCT:["CONSTRUCT","or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])"]},constructTemplate:{"{":["{","?constructTriples","}"]},constructTriples:{VAR1:["triplesSameSubject","?[.,?constructTriples]"],VAR2:["triplesSameSubject","?[.,?constructTriples]"],NIL:["triplesSameSubject","?[.,?constructTriples]"],"(":["triplesSameSubject","?[.,?constructTriples]"],"[":["triplesSameSubject","?[.,?constructTriples]"],IRI_REF:["triplesSameSubject","?[.,?constructTriples]"],TRUE:["triplesSameSubject","?[.,?constructTriples]"],FALSE:["triplesSameSubject","?[.,?constructTriples]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?constructTriples]"],ANON:["triplesSameSubject","?[.,?constructTriples]"],PNAME_LN:["triplesSameSubject","?[.,?constructTriples]"],PNAME_NS:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL2:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?constructTriples]"],INTEGER:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"]},copy:{COPY:["COPY","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},create:{CREATE:["CREATE","?SILENT_3","graphRef"]},dataBlock:{NIL:["or([inlineDataOneVar,inlineDataFull])"],"(":["or([inlineDataOneVar,inlineDataFull])"],VAR1:["or([inlineDataOneVar,inlineDataFull])"],VAR2:["or([inlineDataOneVar,inlineDataFull])"]},dataBlockValue:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],UNDEF:["UNDEF"]},datasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},defaultGraphClause:{IRI_REF:["sourceSelector"],PNAME_LN:["sourceSelector"],PNAME_NS:["sourceSelector"]},delete1:{DATA:["DATA","quadDataNoBnodes"],WHERE:["WHERE","quadPatternNoBnodes"],"{":["quadPatternNoBnodes","?insertClause","*usingClause","WHERE","groupGraphPattern"]},deleteClause:{DELETE:["DELETE","quadPattern"]},describeDatasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},describeQuery:{DESCRIBE:["DESCRIBE","or([+varOrIRIref,*])","*describeDatasetClause","?whereClause","solutionModifier"]},disallowBnodes:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},disallowVars:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},drop:{DROP:["DROP","?SILENT_2","graphRefAll"]},existsFunc:{EXISTS:["EXISTS","groupGraphPattern"]},expression:{"!":["conditionalOrExpression"],"+":["conditionalOrExpression"],"-":["conditionalOrExpression"],VAR1:["conditionalOrExpression"],VAR2:["conditionalOrExpression"],"(":["conditionalOrExpression"],STR:["conditionalOrExpression"],LANG:["conditionalOrExpression"],LANGMATCHES:["conditionalOrExpression"],DATATYPE:["conditionalOrExpression"],BOUND:["conditionalOrExpression"],IRI:["conditionalOrExpression"],URI:["conditionalOrExpression"],BNODE:["conditionalOrExpression"],RAND:["conditionalOrExpression"],ABS:["conditionalOrExpression"],CEIL:["conditionalOrExpression"],FLOOR:["conditionalOrExpression"],ROUND:["conditionalOrExpression"],CONCAT:["conditionalOrExpression"],STRLEN:["conditionalOrExpression"],UCASE:["conditionalOrExpression"],LCASE:["conditionalOrExpression"],ENCODE_FOR_URI:["conditionalOrExpression"],CONTAINS:["conditionalOrExpression"],STRSTARTS:["conditionalOrExpression"],STRENDS:["conditionalOrExpression"],STRBEFORE:["conditionalOrExpression"],STRAFTER:["conditionalOrExpression"],YEAR:["conditionalOrExpression"],MONTH:["conditionalOrExpression"],DAY:["conditionalOrExpression"],HOURS:["conditionalOrExpression"],MINUTES:["conditionalOrExpression"],SECONDS:["conditionalOrExpression"],TIMEZONE:["conditionalOrExpression"],TZ:["conditionalOrExpression"],NOW:["conditionalOrExpression"],UUID:["conditionalOrExpression"],STRUUID:["conditionalOrExpression"],MD5:["conditionalOrExpression"],SHA1:["conditionalOrExpression"],SHA256:["conditionalOrExpression"],SHA384:["conditionalOrExpression"],SHA512:["conditionalOrExpression"],COALESCE:["conditionalOrExpression"],IF:["conditionalOrExpression"],STRLANG:["conditionalOrExpression"],STRDT:["conditionalOrExpression"],SAMETERM:["conditionalOrExpression"],ISIRI:["conditionalOrExpression"],ISURI:["conditionalOrExpression"],ISBLANK:["conditionalOrExpression"],ISLITERAL:["conditionalOrExpression"],ISNUMERIC:["conditionalOrExpression"],TRUE:["conditionalOrExpression"],FALSE:["conditionalOrExpression"],COUNT:["conditionalOrExpression"],SUM:["conditionalOrExpression"],MIN:["conditionalOrExpression"],MAX:["conditionalOrExpression"],AVG:["conditionalOrExpression"],SAMPLE:["conditionalOrExpression"],GROUP_CONCAT:["conditionalOrExpression"],SUBSTR:["conditionalOrExpression"],REPLACE:["conditionalOrExpression"],REGEX:["conditionalOrExpression"],EXISTS:["conditionalOrExpression"],NOT:["conditionalOrExpression"],IRI_REF:["conditionalOrExpression"],STRING_LITERAL1:["conditionalOrExpression"],STRING_LITERAL2:["conditionalOrExpression"],STRING_LITERAL_LONG1:["conditionalOrExpression"],STRING_LITERAL_LONG2:["conditionalOrExpression"],INTEGER:["conditionalOrExpression"],DECIMAL:["conditionalOrExpression"],DOUBLE:["conditionalOrExpression"],INTEGER_POSITIVE:["conditionalOrExpression"],DECIMAL_POSITIVE:["conditionalOrExpression"],DOUBLE_POSITIVE:["conditionalOrExpression"],INTEGER_NEGATIVE:["conditionalOrExpression"],DECIMAL_NEGATIVE:["conditionalOrExpression"],DOUBLE_NEGATIVE:["conditionalOrExpression"],PNAME_LN:["conditionalOrExpression"],PNAME_NS:["conditionalOrExpression"]},expressionList:{NIL:["NIL"],"(":["(","expression","*[,,expression]",")"]},filter:{FILTER:["FILTER","constraint"]},functionCall:{IRI_REF:["iriRef","argList"],PNAME_LN:["iriRef","argList"],PNAME_NS:["iriRef","argList"]},graphGraphPattern:{GRAPH:["GRAPH","varOrIRIref","groupGraphPattern"]},graphNode:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNode"],"[":["triplesNode"]},graphNodePath:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNodePath"],"[":["triplesNodePath"]},graphOrDefault:{DEFAULT:["DEFAULT"],IRI_REF:["?GRAPH","iriRef"],PNAME_LN:["?GRAPH","iriRef"],PNAME_NS:["?GRAPH","iriRef"],GRAPH:["?GRAPH","iriRef"]},graphPatternNotTriples:{"{":["groupOrUnionGraphPattern"],OPTIONAL:["optionalGraphPattern"],MINUS:["minusGraphPattern"],GRAPH:["graphGraphPattern"],SERVICE:["serviceGraphPattern"],FILTER:["filter"],BIND:["bind"],VALUES:["inlineData"]},graphRef:{GRAPH:["GRAPH","iriRef"]},graphRefAll:{GRAPH:["graphRef"],DEFAULT:["DEFAULT"],NAMED:["NAMED"],ALL:["ALL"]},graphTerm:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],BLANK_NODE_LABEL:["blankNode"],ANON:["blankNode"],NIL:["NIL"]},groupClause:{GROUP:["GROUP","BY","+groupCondition"]},groupCondition:{STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"],"(":["(","expression","?[AS,var]",")"],VAR1:["var"],VAR2:["var"]},groupGraphPattern:{"{":["{","or([subSelect,groupGraphPatternSub])","}"]},groupGraphPatternSub:{"{":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],NIL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"(":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"[":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],IRI_REF:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],TRUE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FALSE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BLANK_NODE_LABEL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],ANON:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_LN:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_NS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"]},groupOrUnionGraphPattern:{"{":["groupGraphPattern","*[UNION,groupGraphPattern]"]},havingClause:{HAVING:["HAVING","+havingCondition"]},havingCondition:{"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"]},inlineData:{VALUES:["VALUES","dataBlock"]},inlineDataFull:{NIL:["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"],"(":["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"]},inlineDataOneVar:{VAR1:["var","{","*dataBlockValue","}"],VAR2:["var","{","*dataBlockValue","}"]},insert1:{DATA:["DATA","quadData"],"{":["quadPattern","*usingClause","WHERE","groupGraphPattern"]},insertClause:{INSERT:["INSERT","quadPattern"]},integer:{INTEGER:["INTEGER"]},iriRef:{IRI_REF:["IRI_REF"],PNAME_LN:["prefixedName"],PNAME_NS:["prefixedName"]},iriRefOrFunction:{IRI_REF:["iriRef","?argList"],PNAME_LN:["iriRef","?argList"],PNAME_NS:["iriRef","?argList"]},limitClause:{LIMIT:["LIMIT","INTEGER"]},limitOffsetClauses:{LIMIT:["limitClause","?offsetClause"],OFFSET:["offsetClause","?limitClause"]},load:{LOAD:["LOAD","?SILENT_1","iriRef","?[INTO,graphRef]"]},minusGraphPattern:{MINUS:["MINUS","groupGraphPattern"]},modify:{WITH:["WITH","iriRef","or([[deleteClause,?insertClause],insertClause])","*usingClause","WHERE","groupGraphPattern"]},move:{MOVE:["MOVE","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},multiplicativeExpression:{"!":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"+":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"-":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"(":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANGMATCHES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DATATYPE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BOUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BNODE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],RAND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ABS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CEIL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FLOOR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ROUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLEN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ENCODE_FOR_URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONTAINS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRSTARTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRENDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRBEFORE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRAFTER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],YEAR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MONTH:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DAY:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],HOURS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MINUTES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SECONDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TIMEZONE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TZ:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOW:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRUUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MD5:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA256:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA384:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA512:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COALESCE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRDT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMETERM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISIRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISURI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISBLANK:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISLITERAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISNUMERIC:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TRUE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FALSE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COUNT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MIN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MAX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],AVG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMPLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],GROUP_CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUBSTR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REPLACE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REGEX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],EXISTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI_REF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_LN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_NS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"]},namedGraphClause:{NAMED:["NAMED","sourceSelector"]},notExistsFunc:{NOT:["NOT","EXISTS","groupGraphPattern"]},numericExpression:{"!":["additiveExpression"],"+":["additiveExpression"],"-":["additiveExpression"],VAR1:["additiveExpression"],VAR2:["additiveExpression"],"(":["additiveExpression"],STR:["additiveExpression"],LANG:["additiveExpression"],LANGMATCHES:["additiveExpression"],DATATYPE:["additiveExpression"],BOUND:["additiveExpression"],IRI:["additiveExpression"],URI:["additiveExpression"],BNODE:["additiveExpression"],RAND:["additiveExpression"],ABS:["additiveExpression"],CEIL:["additiveExpression"],FLOOR:["additiveExpression"],ROUND:["additiveExpression"],CONCAT:["additiveExpression"],STRLEN:["additiveExpression"],UCASE:["additiveExpression"],LCASE:["additiveExpression"],ENCODE_FOR_URI:["additiveExpression"],CONTAINS:["additiveExpression"],STRSTARTS:["additiveExpression"],STRENDS:["additiveExpression"],STRBEFORE:["additiveExpression"],STRAFTER:["additiveExpression"],YEAR:["additiveExpression"],MONTH:["additiveExpression"],DAY:["additiveExpression"],HOURS:["additiveExpression"],MINUTES:["additiveExpression"],SECONDS:["additiveExpression"],TIMEZONE:["additiveExpression"],TZ:["additiveExpression"],NOW:["additiveExpression"],UUID:["additiveExpression"],STRUUID:["additiveExpression"],MD5:["additiveExpression"],SHA1:["additiveExpression"],SHA256:["additiveExpression"],SHA384:["additiveExpression"],SHA512:["additiveExpression"],COALESCE:["additiveExpression"],IF:["additiveExpression"],STRLANG:["additiveExpression"],STRDT:["additiveExpression"],SAMETERM:["additiveExpression"],ISIRI:["additiveExpression"],ISURI:["additiveExpression"],ISBLANK:["additiveExpression"],ISLITERAL:["additiveExpression"],ISNUMERIC:["additiveExpression"],TRUE:["additiveExpression"],FALSE:["additiveExpression"],COUNT:["additiveExpression"],SUM:["additiveExpression"],MIN:["additiveExpression"],MAX:["additiveExpression"],AVG:["additiveExpression"],SAMPLE:["additiveExpression"],GROUP_CONCAT:["additiveExpression"],SUBSTR:["additiveExpression"],REPLACE:["additiveExpression"],REGEX:["additiveExpression"],EXISTS:["additiveExpression"],NOT:["additiveExpression"],IRI_REF:["additiveExpression"],STRING_LITERAL1:["additiveExpression"],STRING_LITERAL2:["additiveExpression"],STRING_LITERAL_LONG1:["additiveExpression"],STRING_LITERAL_LONG2:["additiveExpression"],INTEGER:["additiveExpression"],DECIMAL:["additiveExpression"],DOUBLE:["additiveExpression"],INTEGER_POSITIVE:["additiveExpression"],DECIMAL_POSITIVE:["additiveExpression"],DOUBLE_POSITIVE:["additiveExpression"],INTEGER_NEGATIVE:["additiveExpression"],DECIMAL_NEGATIVE:["additiveExpression"],DOUBLE_NEGATIVE:["additiveExpression"],PNAME_LN:["additiveExpression"],PNAME_NS:["additiveExpression"]},numericLiteral:{INTEGER:["numericLiteralUnsigned"],DECIMAL:["numericLiteralUnsigned"],DOUBLE:["numericLiteralUnsigned"],INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},numericLiteralNegative:{INTEGER_NEGATIVE:["INTEGER_NEGATIVE"],DECIMAL_NEGATIVE:["DECIMAL_NEGATIVE"],DOUBLE_NEGATIVE:["DOUBLE_NEGATIVE"]},numericLiteralPositive:{INTEGER_POSITIVE:["INTEGER_POSITIVE"],DECIMAL_POSITIVE:["DECIMAL_POSITIVE"],DOUBLE_POSITIVE:["DOUBLE_POSITIVE"]},numericLiteralUnsigned:{INTEGER:["INTEGER"],DECIMAL:["DECIMAL"],DOUBLE:["DOUBLE"]},object:{"(":["graphNode"],"[":["graphNode"],VAR1:["graphNode"],VAR2:["graphNode"],NIL:["graphNode"],IRI_REF:["graphNode"],TRUE:["graphNode"],FALSE:["graphNode"],BLANK_NODE_LABEL:["graphNode"],ANON:["graphNode"],PNAME_LN:["graphNode"],PNAME_NS:["graphNode"],STRING_LITERAL1:["graphNode"],STRING_LITERAL2:["graphNode"],STRING_LITERAL_LONG1:["graphNode"],STRING_LITERAL_LONG2:["graphNode"],INTEGER:["graphNode"],DECIMAL:["graphNode"],DOUBLE:["graphNode"],INTEGER_POSITIVE:["graphNode"],DECIMAL_POSITIVE:["graphNode"],DOUBLE_POSITIVE:["graphNode"],INTEGER_NEGATIVE:["graphNode"],DECIMAL_NEGATIVE:["graphNode"],DOUBLE_NEGATIVE:["graphNode"]},objectList:{"(":["object","*[,,object]"],"[":["object","*[,,object]"],VAR1:["object","*[,,object]"],VAR2:["object","*[,,object]"],NIL:["object","*[,,object]"],IRI_REF:["object","*[,,object]"],TRUE:["object","*[,,object]"],FALSE:["object","*[,,object]"],BLANK_NODE_LABEL:["object","*[,,object]"],ANON:["object","*[,,object]"],PNAME_LN:["object","*[,,object]"],PNAME_NS:["object","*[,,object]"],STRING_LITERAL1:["object","*[,,object]"],STRING_LITERAL2:["object","*[,,object]"],STRING_LITERAL_LONG1:["object","*[,,object]"],STRING_LITERAL_LONG2:["object","*[,,object]"],INTEGER:["object","*[,,object]"],DECIMAL:["object","*[,,object]"],DOUBLE:["object","*[,,object]"],INTEGER_POSITIVE:["object","*[,,object]"],DECIMAL_POSITIVE:["object","*[,,object]"],DOUBLE_POSITIVE:["object","*[,,object]"],INTEGER_NEGATIVE:["object","*[,,object]"],DECIMAL_NEGATIVE:["object","*[,,object]"],DOUBLE_NEGATIVE:["object","*[,,object]"]},objectListPath:{"(":["objectPath","*[,,objectPath]"],"[":["objectPath","*[,,objectPath]"],VAR1:["objectPath","*[,,objectPath]"],VAR2:["objectPath","*[,,objectPath]"],NIL:["objectPath","*[,,objectPath]"],IRI_REF:["objectPath","*[,,objectPath]"],TRUE:["objectPath","*[,,objectPath]"],FALSE:["objectPath","*[,,objectPath]"],BLANK_NODE_LABEL:["objectPath","*[,,objectPath]"],ANON:["objectPath","*[,,objectPath]"],PNAME_LN:["objectPath","*[,,objectPath]"],PNAME_NS:["objectPath","*[,,objectPath]"],STRING_LITERAL1:["objectPath","*[,,objectPath]"],STRING_LITERAL2:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG1:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG2:["objectPath","*[,,objectPath]"],INTEGER:["objectPath","*[,,objectPath]"],DECIMAL:["objectPath","*[,,objectPath]"],DOUBLE:["objectPath","*[,,objectPath]"],INTEGER_POSITIVE:["objectPath","*[,,objectPath]"],DECIMAL_POSITIVE:["objectPath","*[,,objectPath]"],DOUBLE_POSITIVE:["objectPath","*[,,objectPath]"],INTEGER_NEGATIVE:["objectPath","*[,,objectPath]"],DECIMAL_NEGATIVE:["objectPath","*[,,objectPath]"],DOUBLE_NEGATIVE:["objectPath","*[,,objectPath]"]},objectPath:{"(":["graphNodePath"],"[":["graphNodePath"],VAR1:["graphNodePath"],VAR2:["graphNodePath"],NIL:["graphNodePath"],IRI_REF:["graphNodePath"],TRUE:["graphNodePath"],FALSE:["graphNodePath"],BLANK_NODE_LABEL:["graphNodePath"],ANON:["graphNodePath"],PNAME_LN:["graphNodePath"],PNAME_NS:["graphNodePath"],STRING_LITERAL1:["graphNodePath"],STRING_LITERAL2:["graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath"],INTEGER:["graphNodePath"],DECIMAL:["graphNodePath"],DOUBLE:["graphNodePath"],INTEGER_POSITIVE:["graphNodePath"],DECIMAL_POSITIVE:["graphNodePath"],DOUBLE_POSITIVE:["graphNodePath"],INTEGER_NEGATIVE:["graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath"]},offsetClause:{OFFSET:["OFFSET","INTEGER"]},optionalGraphPattern:{OPTIONAL:["OPTIONAL","groupGraphPattern"]},"or([*,expression])":{"*":["*"],"!":["expression"],"+":["expression"],"-":["expression"],VAR1:["expression"],VAR2:["expression"],"(":["expression"],STR:["expression"],LANG:["expression"],LANGMATCHES:["expression"],DATATYPE:["expression"],BOUND:["expression"],IRI:["expression"],URI:["expression"],BNODE:["expression"],RAND:["expression"],ABS:["expression"],CEIL:["expression"],FLOOR:["expression"],ROUND:["expression"],CONCAT:["expression"],STRLEN:["expression"],UCASE:["expression"],LCASE:["expression"],ENCODE_FOR_URI:["expression"],CONTAINS:["expression"],STRSTARTS:["expression"],STRENDS:["expression"],STRBEFORE:["expression"],STRAFTER:["expression"],YEAR:["expression"],MONTH:["expression"],DAY:["expression"],HOURS:["expression"],MINUTES:["expression"],SECONDS:["expression"],TIMEZONE:["expression"],TZ:["expression"],NOW:["expression"],UUID:["expression"],STRUUID:["expression"],MD5:["expression"],SHA1:["expression"],SHA256:["expression"],SHA384:["expression"],SHA512:["expression"],COALESCE:["expression"],IF:["expression"],STRLANG:["expression"],STRDT:["expression"],SAMETERM:["expression"],ISIRI:["expression"],ISURI:["expression"],ISBLANK:["expression"],ISLITERAL:["expression"],ISNUMERIC:["expression"],TRUE:["expression"],FALSE:["expression"],COUNT:["expression"],SUM:["expression"],MIN:["expression"],MAX:["expression"],AVG:["expression"],SAMPLE:["expression"],GROUP_CONCAT:["expression"],SUBSTR:["expression"],REPLACE:["expression"],REGEX:["expression"],EXISTS:["expression"],NOT:["expression"],IRI_REF:["expression"],STRING_LITERAL1:["expression"],STRING_LITERAL2:["expression"],STRING_LITERAL_LONG1:["expression"],STRING_LITERAL_LONG2:["expression"],INTEGER:["expression"],DECIMAL:["expression"],DOUBLE:["expression"],INTEGER_POSITIVE:["expression"],DECIMAL_POSITIVE:["expression"],DOUBLE_POSITIVE:["expression"],INTEGER_NEGATIVE:["expression"],DECIMAL_NEGATIVE:["expression"],DOUBLE_NEGATIVE:["expression"],PNAME_LN:["expression"],PNAME_NS:["expression"]},"or([+or([var,[ (,expression,AS,var,)]]),*])":{"(":["+or([var,[ (,expression,AS,var,)]])"],VAR1:["+or([var,[ (,expression,AS,var,)]])"],VAR2:["+or([var,[ (,expression,AS,var,)]])"],"*":["*"]},"or([+varOrIRIref,*])":{VAR1:["+varOrIRIref"],VAR2:["+varOrIRIref"],IRI_REF:["+varOrIRIref"],PNAME_LN:["+varOrIRIref"],PNAME_NS:["+varOrIRIref"],"*":["*"]},"or([ASC,DESC])":{ASC:["ASC"],DESC:["DESC"]},"or([DISTINCT,REDUCED])":{DISTINCT:["DISTINCT"],REDUCED:["REDUCED"]},"or([LANGTAG,[^^,iriRef]])":{LANGTAG:["LANGTAG"],"^^":["[^^,iriRef]"]},"or([NIL,[ (,*var,)]])":{NIL:["NIL"],"(":["[ (,*var,)]"]},"or([[ (,*dataBlockValue,)],NIL])":{"(":["[ (,*dataBlockValue,)]"],NIL:["NIL"]},"or([[ (,expression,)],NIL])":{"(":["[ (,expression,)]"],NIL:["NIL"]},"or([[*,unaryExpression],[/,unaryExpression]])":{"*":["[*,unaryExpression]"],"/":["[/,unaryExpression]"]},"or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["[+,multiplicativeExpression]"],"-":["[-,multiplicativeExpression]"],INTEGER_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],INTEGER_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"]},"or([[,,or([},[integer,}]])],}])":{",":["[,,or([},[integer,}]])]"],"}":["}"]},"or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["[=,numericExpression]"],"!=":["[!=,numericExpression]"],"<":["[<,numericExpression]"],">":["[>,numericExpression]"],"<=":["[<=,numericExpression]"],">=":["[>=,numericExpression]"],IN:["[IN,expressionList]"],NOT:["[NOT,IN,expressionList]"]},"or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])":{"{":["[constructTemplate,*datasetClause,whereClause,solutionModifier]"],WHERE:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"],FROM:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"]},"or([[deleteClause,?insertClause],insertClause])":{DELETE:["[deleteClause,?insertClause]"],INSERT:["insertClause"]},"or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])":{INTEGER:["[integer,or([[,,or([},[integer,}]])],}])]"],",":["[,,integer,}]"]},"or([defaultGraphClause,namedGraphClause])":{IRI_REF:["defaultGraphClause"],PNAME_LN:["defaultGraphClause"],PNAME_NS:["defaultGraphClause"],NAMED:["namedGraphClause"]},"or([inlineDataOneVar,inlineDataFull])":{VAR1:["inlineDataOneVar"],VAR2:["inlineDataOneVar"],NIL:["inlineDataFull"],"(":["inlineDataFull"]},"or([iriRef,[NAMED,iriRef]])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],NAMED:["[NAMED,iriRef]"]},"or([iriRef,a])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"]},"or([numericLiteralPositive,numericLiteralNegative])":{INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},"or([queryAll,updateAll])":{CONSTRUCT:["queryAll"],DESCRIBE:["queryAll"],ASK:["queryAll"],SELECT:["queryAll"],INSERT:["updateAll"],DELETE:["updateAll"],LOAD:["updateAll"],CLEAR:["updateAll"],DROP:["updateAll"],ADD:["updateAll"],MOVE:["updateAll"],COPY:["updateAll"],CREATE:["updateAll"],WITH:["updateAll"],$:["updateAll"]},"or([selectQuery,constructQuery,describeQuery,askQuery])":{SELECT:["selectQuery"],CONSTRUCT:["constructQuery"],DESCRIBE:["describeQuery"],ASK:["askQuery"]},"or([subSelect,groupGraphPatternSub])":{SELECT:["subSelect"],"{":["groupGraphPatternSub"],OPTIONAL:["groupGraphPatternSub"],MINUS:["groupGraphPatternSub"],GRAPH:["groupGraphPatternSub"],SERVICE:["groupGraphPatternSub"],FILTER:["groupGraphPatternSub"],BIND:["groupGraphPatternSub"],VALUES:["groupGraphPatternSub"],VAR1:["groupGraphPatternSub"],VAR2:["groupGraphPatternSub"],NIL:["groupGraphPatternSub"],"(":["groupGraphPatternSub"],"[":["groupGraphPatternSub"],IRI_REF:["groupGraphPatternSub"],TRUE:["groupGraphPatternSub"],FALSE:["groupGraphPatternSub"],BLANK_NODE_LABEL:["groupGraphPatternSub"],ANON:["groupGraphPatternSub"],PNAME_LN:["groupGraphPatternSub"],PNAME_NS:["groupGraphPatternSub"],STRING_LITERAL1:["groupGraphPatternSub"],STRING_LITERAL2:["groupGraphPatternSub"],STRING_LITERAL_LONG1:["groupGraphPatternSub"],STRING_LITERAL_LONG2:["groupGraphPatternSub"],INTEGER:["groupGraphPatternSub"],DECIMAL:["groupGraphPatternSub"],DOUBLE:["groupGraphPatternSub"],INTEGER_POSITIVE:["groupGraphPatternSub"],DECIMAL_POSITIVE:["groupGraphPatternSub"],DOUBLE_POSITIVE:["groupGraphPatternSub"],INTEGER_NEGATIVE:["groupGraphPatternSub"],DECIMAL_NEGATIVE:["groupGraphPatternSub"],DOUBLE_NEGATIVE:["groupGraphPatternSub"],"}":["groupGraphPatternSub"]},"or([var,[ (,expression,AS,var,)]])":{VAR1:["var"],VAR2:["var"],"(":["[ (,expression,AS,var,)]"]},"or([verbPath,verbSimple])":{"^":["verbPath"],a:["verbPath"],"!":["verbPath"],"(":["verbPath"],IRI_REF:["verbPath"],PNAME_LN:["verbPath"],PNAME_NS:["verbPath"],VAR1:["verbSimple"],VAR2:["verbSimple"]},"or([},[integer,}]])":{"}":["}"],INTEGER:["[integer,}]"]},orderClause:{ORDER:["ORDER","BY","+orderCondition"]},orderCondition:{ASC:["or([ASC,DESC])","brackettedExpression"],DESC:["or([ASC,DESC])","brackettedExpression"],"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"],VAR1:["var"],VAR2:["var"]},path:{"^":["pathAlternative"],a:["pathAlternative"],"!":["pathAlternative"],"(":["pathAlternative"],IRI_REF:["pathAlternative"],PNAME_LN:["pathAlternative"],PNAME_NS:["pathAlternative"]},pathAlternative:{"^":["pathSequence","*[|,pathSequence]"],a:["pathSequence","*[|,pathSequence]"],"!":["pathSequence","*[|,pathSequence]"],"(":["pathSequence","*[|,pathSequence]"],IRI_REF:["pathSequence","*[|,pathSequence]"],PNAME_LN:["pathSequence","*[|,pathSequence]"],PNAME_NS:["pathSequence","*[|,pathSequence]"]},pathElt:{a:["pathPrimary","?pathMod"],"!":["pathPrimary","?pathMod"],"(":["pathPrimary","?pathMod"],IRI_REF:["pathPrimary","?pathMod"],PNAME_LN:["pathPrimary","?pathMod"],PNAME_NS:["pathPrimary","?pathMod"]},pathEltOrInverse:{a:["pathElt"],"!":["pathElt"],"(":["pathElt"],IRI_REF:["pathElt"],PNAME_LN:["pathElt"],PNAME_NS:["pathElt"],"^":["^","pathElt"]},pathMod:{"*":["*"],"?":["?"],"+":["+"],"{":["{","or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])"]},pathNegatedPropertySet:{a:["pathOneInPropertySet"],"^":["pathOneInPropertySet"],IRI_REF:["pathOneInPropertySet"],PNAME_LN:["pathOneInPropertySet"],PNAME_NS:["pathOneInPropertySet"],"(":["(","?[pathOneInPropertySet,*[|,pathOneInPropertySet]]",")"]},pathOneInPropertySet:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"],"^":["^","or([iriRef,a])"]},pathPrimary:{IRI_REF:["storeProperty","iriRef"],PNAME_LN:["storeProperty","iriRef"],PNAME_NS:["storeProperty","iriRef"],a:["storeProperty","a"],"!":["!","pathNegatedPropertySet"],"(":["(","path",")"]},pathSequence:{"^":["pathEltOrInverse","*[/,pathEltOrInverse]"],a:["pathEltOrInverse","*[/,pathEltOrInverse]"],"!":["pathEltOrInverse","*[/,pathEltOrInverse]"],"(":["pathEltOrInverse","*[/,pathEltOrInverse]"],IRI_REF:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_LN:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_NS:["pathEltOrInverse","*[/,pathEltOrInverse]"]},prefixDecl:{PREFIX:["PREFIX","PNAME_NS","IRI_REF"]},prefixedName:{PNAME_LN:["PNAME_LN"],PNAME_NS:["PNAME_NS"]},primaryExpression:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["iriRefOrFunction"],PNAME_LN:["iriRefOrFunction"],PNAME_NS:["iriRefOrFunction"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],VAR1:["var"],VAR2:["var"],COUNT:["aggregate"],SUM:["aggregate"],MIN:["aggregate"],MAX:["aggregate"],AVG:["aggregate"],SAMPLE:["aggregate"],GROUP_CONCAT:["aggregate"]},prologue:{PREFIX:["?baseDecl","*prefixDecl"],BASE:["?baseDecl","*prefixDecl"],$:["?baseDecl","*prefixDecl"],CONSTRUCT:["?baseDecl","*prefixDecl"],DESCRIBE:["?baseDecl","*prefixDecl"],ASK:["?baseDecl","*prefixDecl"],INSERT:["?baseDecl","*prefixDecl"],DELETE:["?baseDecl","*prefixDecl"],SELECT:["?baseDecl","*prefixDecl"],LOAD:["?baseDecl","*prefixDecl"],CLEAR:["?baseDecl","*prefixDecl"],DROP:["?baseDecl","*prefixDecl"],ADD:["?baseDecl","*prefixDecl"],MOVE:["?baseDecl","*prefixDecl"],COPY:["?baseDecl","*prefixDecl"],CREATE:["?baseDecl","*prefixDecl"],WITH:["?baseDecl","*prefixDecl"]},propertyList:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"}":[],GRAPH:[]},propertyListNotEmpty:{a:["verb","objectList","*[;,?[verb,objectList]]"],VAR1:["verb","objectList","*[;,?[verb,objectList]]"],VAR2:["verb","objectList","*[;,?[verb,objectList]]"],IRI_REF:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_LN:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_NS:["verb","objectList","*[;,?[verb,objectList]]"]},propertyListPath:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},propertyListPathNotEmpty:{VAR1:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],VAR2:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"^":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],a:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"!":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"(":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],IRI_REF:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_LN:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_NS:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"]},quadData:{"{":["{","disallowVars","quads","allowVars","}"]},quadDataNoBnodes:{"{":["{","disallowBnodes","disallowVars","quads","allowVars","allowBnodes","}"]},quadPattern:{"{":["{","quads","}"]},quadPatternNoBnodes:{"{":["{","disallowBnodes","quads","allowBnodes","}"]},quads:{GRAPH:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],NIL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"(":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"[":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],IRI_REF:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],TRUE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],FALSE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],BLANK_NODE_LABEL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],ANON:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_LN:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_NS:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"}":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"]},quadsNotTriples:{GRAPH:["GRAPH","varOrIRIref","{","?triplesTemplate","}"]},queryAll:{CONSTRUCT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],DESCRIBE:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],ASK:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],SELECT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"]},rdfLiteral:{STRING_LITERAL1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL2:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG2:["string","?or([LANGTAG,[^^,iriRef]])"]},regexExpression:{REGEX:["REGEX","(","expression",",","expression","?[,,expression]",")"]},relationalExpression:{"!":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"+":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"-":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"(":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANGMATCHES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DATATYPE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BOUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BNODE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],RAND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ABS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CEIL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FLOOR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ROUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLEN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ENCODE_FOR_URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONTAINS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRSTARTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRENDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRBEFORE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRAFTER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],YEAR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MONTH:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DAY:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],HOURS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MINUTES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SECONDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TIMEZONE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TZ:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOW:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRUUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MD5:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA256:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA384:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA512:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COALESCE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRDT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMETERM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISIRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISURI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISBLANK:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISLITERAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISNUMERIC:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TRUE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FALSE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COUNT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MIN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MAX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AVG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMPLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],GROUP_CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUBSTR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REPLACE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REGEX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],EXISTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI_REF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_LN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_NS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"]},selectClause:{SELECT:["SELECT","?or([DISTINCT,REDUCED])","or([+or([var,[ (,expression,AS,var,)]]),*])"]},selectQuery:{SELECT:["selectClause","*datasetClause","whereClause","solutionModifier"]},serviceGraphPattern:{SERVICE:["SERVICE","?SILENT","varOrIRIref","groupGraphPattern"]},solutionModifier:{LIMIT:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],OFFSET:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],ORDER:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],HAVING:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],GROUP:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],VALUES:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],$:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],"}":["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"]},sourceSelector:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},sparql11:{$:["prologue","or([queryAll,updateAll])","$"],CONSTRUCT:["prologue","or([queryAll,updateAll])","$"],DESCRIBE:["prologue","or([queryAll,updateAll])","$"],ASK:["prologue","or([queryAll,updateAll])","$"],INSERT:["prologue","or([queryAll,updateAll])","$"],DELETE:["prologue","or([queryAll,updateAll])","$"],SELECT:["prologue","or([queryAll,updateAll])","$"],LOAD:["prologue","or([queryAll,updateAll])","$"],CLEAR:["prologue","or([queryAll,updateAll])","$"],DROP:["prologue","or([queryAll,updateAll])","$"],ADD:["prologue","or([queryAll,updateAll])","$"],MOVE:["prologue","or([queryAll,updateAll])","$"],COPY:["prologue","or([queryAll,updateAll])","$"],CREATE:["prologue","or([queryAll,updateAll])","$"],WITH:["prologue","or([queryAll,updateAll])","$"],PREFIX:["prologue","or([queryAll,updateAll])","$"],BASE:["prologue","or([queryAll,updateAll])","$"]},storeProperty:{VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[],a:[]},strReplaceExpression:{REPLACE:["REPLACE","(","expression",",","expression",",","expression","?[,,expression]",")"]},string:{STRING_LITERAL1:["STRING_LITERAL1"],STRING_LITERAL2:["STRING_LITERAL2"],STRING_LITERAL_LONG1:["STRING_LITERAL_LONG1"],STRING_LITERAL_LONG2:["STRING_LITERAL_LONG2"]},subSelect:{SELECT:["selectClause","whereClause","solutionModifier","valuesClause"]},substringExpression:{SUBSTR:["SUBSTR","(","expression",",","expression","?[,,expression]",")"]},triplesBlock:{VAR1:["triplesSameSubjectPath","?[.,?triplesBlock]"],VAR2:["triplesSameSubjectPath","?[.,?triplesBlock]"],NIL:["triplesSameSubjectPath","?[.,?triplesBlock]"],"(":["triplesSameSubjectPath","?[.,?triplesBlock]"],"[":["triplesSameSubjectPath","?[.,?triplesBlock]"],IRI_REF:["triplesSameSubjectPath","?[.,?triplesBlock]"],TRUE:["triplesSameSubjectPath","?[.,?triplesBlock]"],FALSE:["triplesSameSubjectPath","?[.,?triplesBlock]"],BLANK_NODE_LABEL:["triplesSameSubjectPath","?[.,?triplesBlock]"],ANON:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_LN:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_NS:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL2:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG2:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"]},triplesNode:{"(":["collection"],"[":["blankNodePropertyList"]},triplesNodePath:{"(":["collectionPath"],"[":["blankNodePropertyListPath"]},triplesSameSubject:{VAR1:["varOrTerm","propertyListNotEmpty"],VAR2:["varOrTerm","propertyListNotEmpty"],NIL:["varOrTerm","propertyListNotEmpty"],IRI_REF:["varOrTerm","propertyListNotEmpty"],TRUE:["varOrTerm","propertyListNotEmpty"],FALSE:["varOrTerm","propertyListNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListNotEmpty"],ANON:["varOrTerm","propertyListNotEmpty"],PNAME_LN:["varOrTerm","propertyListNotEmpty"],PNAME_NS:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListNotEmpty"],INTEGER:["varOrTerm","propertyListNotEmpty"],DECIMAL:["varOrTerm","propertyListNotEmpty"],DOUBLE:["varOrTerm","propertyListNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListNotEmpty"],"(":["triplesNode","propertyList"],"[":["triplesNode","propertyList"]},triplesSameSubjectPath:{VAR1:["varOrTerm","propertyListPathNotEmpty"],VAR2:["varOrTerm","propertyListPathNotEmpty"],NIL:["varOrTerm","propertyListPathNotEmpty"],IRI_REF:["varOrTerm","propertyListPathNotEmpty"],TRUE:["varOrTerm","propertyListPathNotEmpty"],FALSE:["varOrTerm","propertyListPathNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListPathNotEmpty"],ANON:["varOrTerm","propertyListPathNotEmpty"],PNAME_LN:["varOrTerm","propertyListPathNotEmpty"],PNAME_NS:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListPathNotEmpty"],INTEGER:["varOrTerm","propertyListPathNotEmpty"],DECIMAL:["varOrTerm","propertyListPathNotEmpty"],DOUBLE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],"(":["triplesNodePath","propertyListPath"],"[":["triplesNodePath","propertyListPath"]},triplesTemplate:{VAR1:["triplesSameSubject","?[.,?triplesTemplate]"],VAR2:["triplesSameSubject","?[.,?triplesTemplate]"],NIL:["triplesSameSubject","?[.,?triplesTemplate]"],"(":["triplesSameSubject","?[.,?triplesTemplate]"],"[":["triplesSameSubject","?[.,?triplesTemplate]"],IRI_REF:["triplesSameSubject","?[.,?triplesTemplate]"],TRUE:["triplesSameSubject","?[.,?triplesTemplate]"],FALSE:["triplesSameSubject","?[.,?triplesTemplate]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?triplesTemplate]"],ANON:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_LN:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_NS:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL2:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"]},unaryExpression:{"!":["!","primaryExpression"],"+":["+","primaryExpression"],"-":["-","primaryExpression"],VAR1:["primaryExpression"],VAR2:["primaryExpression"],"(":["primaryExpression"],STR:["primaryExpression"],LANG:["primaryExpression"],LANGMATCHES:["primaryExpression"],DATATYPE:["primaryExpression"],BOUND:["primaryExpression"],IRI:["primaryExpression"],URI:["primaryExpression"],BNODE:["primaryExpression"],RAND:["primaryExpression"],ABS:["primaryExpression"],CEIL:["primaryExpression"],FLOOR:["primaryExpression"],ROUND:["primaryExpression"],CONCAT:["primaryExpression"],STRLEN:["primaryExpression"],UCASE:["primaryExpression"],LCASE:["primaryExpression"],ENCODE_FOR_URI:["primaryExpression"],CONTAINS:["primaryExpression"],STRSTARTS:["primaryExpression"],STRENDS:["primaryExpression"],STRBEFORE:["primaryExpression"],STRAFTER:["primaryExpression"],YEAR:["primaryExpression"],MONTH:["primaryExpression"],DAY:["primaryExpression"],HOURS:["primaryExpression"],MINUTES:["primaryExpression"],SECONDS:["primaryExpression"],TIMEZONE:["primaryExpression"],TZ:["primaryExpression"],NOW:["primaryExpression"],UUID:["primaryExpression"],STRUUID:["primaryExpression"],MD5:["primaryExpression"],SHA1:["primaryExpression"],SHA256:["primaryExpression"],SHA384:["primaryExpression"],SHA512:["primaryExpression"],COALESCE:["primaryExpression"],IF:["primaryExpression"],STRLANG:["primaryExpression"],STRDT:["primaryExpression"],SAMETERM:["primaryExpression"],ISIRI:["primaryExpression"],ISURI:["primaryExpression"],ISBLANK:["primaryExpression"],ISLITERAL:["primaryExpression"],ISNUMERIC:["primaryExpression"],TRUE:["primaryExpression"],FALSE:["primaryExpression"],COUNT:["primaryExpression"],SUM:["primaryExpression"],MIN:["primaryExpression"],MAX:["primaryExpression"],AVG:["primaryExpression"],SAMPLE:["primaryExpression"],GROUP_CONCAT:["primaryExpression"],SUBSTR:["primaryExpression"],REPLACE:["primaryExpression"],REGEX:["primaryExpression"],EXISTS:["primaryExpression"],NOT:["primaryExpression"],IRI_REF:["primaryExpression"],STRING_LITERAL1:["primaryExpression"],STRING_LITERAL2:["primaryExpression"],STRING_LITERAL_LONG1:["primaryExpression"],STRING_LITERAL_LONG2:["primaryExpression"],INTEGER:["primaryExpression"],DECIMAL:["primaryExpression"],DOUBLE:["primaryExpression"],INTEGER_POSITIVE:["primaryExpression"],DECIMAL_POSITIVE:["primaryExpression"],DOUBLE_POSITIVE:["primaryExpression"],INTEGER_NEGATIVE:["primaryExpression"],DECIMAL_NEGATIVE:["primaryExpression"],DOUBLE_NEGATIVE:["primaryExpression"],PNAME_LN:["primaryExpression"],PNAME_NS:["primaryExpression"]},update:{INSERT:["prologue","?[update1,?[;,update]]"],DELETE:["prologue","?[update1,?[;,update]]"],LOAD:["prologue","?[update1,?[;,update]]"],CLEAR:["prologue","?[update1,?[;,update]]"],DROP:["prologue","?[update1,?[;,update]]"],ADD:["prologue","?[update1,?[;,update]]"],MOVE:["prologue","?[update1,?[;,update]]"],COPY:["prologue","?[update1,?[;,update]]"],CREATE:["prologue","?[update1,?[;,update]]"],WITH:["prologue","?[update1,?[;,update]]"],PREFIX:["prologue","?[update1,?[;,update]]"],BASE:["prologue","?[update1,?[;,update]]"],$:["prologue","?[update1,?[;,update]]"]},update1:{LOAD:["load"],CLEAR:["clear"],DROP:["drop"],ADD:["add"],MOVE:["move"],COPY:["copy"],CREATE:["create"],INSERT:["INSERT","insert1"],DELETE:["DELETE","delete1"],WITH:["modify"]},updateAll:{INSERT:["?[update1,?[;,update]]"],DELETE:["?[update1,?[;,update]]"],LOAD:["?[update1,?[;,update]]"],CLEAR:["?[update1,?[;,update]]"],DROP:["?[update1,?[;,update]]"],ADD:["?[update1,?[;,update]]"],MOVE:["?[update1,?[;,update]]"],COPY:["?[update1,?[;,update]]"],CREATE:["?[update1,?[;,update]]"],WITH:["?[update1,?[;,update]]"],$:["?[update1,?[;,update]]"]},usingClause:{USING:["USING","or([iriRef,[NAMED,iriRef]])"]},valueLogical:{"!":["relationalExpression"],"+":["relationalExpression"],"-":["relationalExpression"],VAR1:["relationalExpression"],VAR2:["relationalExpression"],"(":["relationalExpression"],STR:["relationalExpression"],LANG:["relationalExpression"],LANGMATCHES:["relationalExpression"],DATATYPE:["relationalExpression"],BOUND:["relationalExpression"],IRI:["relationalExpression"],URI:["relationalExpression"],BNODE:["relationalExpression"],RAND:["relationalExpression"],ABS:["relationalExpression"],CEIL:["relationalExpression"],FLOOR:["relationalExpression"],ROUND:["relationalExpression"],CONCAT:["relationalExpression"],STRLEN:["relationalExpression"],UCASE:["relationalExpression"],LCASE:["relationalExpression"],ENCODE_FOR_URI:["relationalExpression"],CONTAINS:["relationalExpression"],STRSTARTS:["relationalExpression"],STRENDS:["relationalExpression"],STRBEFORE:["relationalExpression"],STRAFTER:["relationalExpression"],YEAR:["relationalExpression"],MONTH:["relationalExpression"],DAY:["relationalExpression"],HOURS:["relationalExpression"],MINUTES:["relationalExpression"],SECONDS:["relationalExpression"],TIMEZONE:["relationalExpression"],TZ:["relationalExpression"],NOW:["relationalExpression"],UUID:["relationalExpression"],STRUUID:["relationalExpression"],MD5:["relationalExpression"],SHA1:["relationalExpression"],SHA256:["relationalExpression"],SHA384:["relationalExpression"],SHA512:["relationalExpression"],COALESCE:["relationalExpression"],IF:["relationalExpression"],STRLANG:["relationalExpression"],STRDT:["relationalExpression"],SAMETERM:["relationalExpression"],ISIRI:["relationalExpression"],ISURI:["relationalExpression"],ISBLANK:["relationalExpression"],ISLITERAL:["relationalExpression"],ISNUMERIC:["relationalExpression"],TRUE:["relationalExpression"],FALSE:["relationalExpression"],COUNT:["relationalExpression"],SUM:["relationalExpression"],MIN:["relationalExpression"],MAX:["relationalExpression"],AVG:["relationalExpression"],SAMPLE:["relationalExpression"],GROUP_CONCAT:["relationalExpression"],SUBSTR:["relationalExpression"],REPLACE:["relationalExpression"],REGEX:["relationalExpression"],EXISTS:["relationalExpression"],NOT:["relationalExpression"],IRI_REF:["relationalExpression"],STRING_LITERAL1:["relationalExpression"],STRING_LITERAL2:["relationalExpression"],STRING_LITERAL_LONG1:["relationalExpression"],STRING_LITERAL_LONG2:["relationalExpression"],INTEGER:["relationalExpression"],DECIMAL:["relationalExpression"],DOUBLE:["relationalExpression"],INTEGER_POSITIVE:["relationalExpression"],DECIMAL_POSITIVE:["relationalExpression"],DOUBLE_POSITIVE:["relationalExpression"],INTEGER_NEGATIVE:["relationalExpression"],DECIMAL_NEGATIVE:["relationalExpression"],DOUBLE_NEGATIVE:["relationalExpression"],PNAME_LN:["relationalExpression"],PNAME_NS:["relationalExpression"]},valuesClause:{VALUES:["VALUES","dataBlock"],$:[],"}":[]},"var":{VAR1:["VAR1"],VAR2:["VAR2"]},varOrIRIref:{VAR1:["var"],VAR2:["var"],IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},varOrTerm:{VAR1:["var"],VAR2:["var"],NIL:["graphTerm"],IRI_REF:["graphTerm"],TRUE:["graphTerm"],FALSE:["graphTerm"],BLANK_NODE_LABEL:["graphTerm"],ANON:["graphTerm"],PNAME_LN:["graphTerm"],PNAME_NS:["graphTerm"],STRING_LITERAL1:["graphTerm"],STRING_LITERAL2:["graphTerm"],STRING_LITERAL_LONG1:["graphTerm"],STRING_LITERAL_LONG2:["graphTerm"],INTEGER:["graphTerm"],DECIMAL:["graphTerm"],DOUBLE:["graphTerm"],INTEGER_POSITIVE:["graphTerm"],DECIMAL_POSITIVE:["graphTerm"],DOUBLE_POSITIVE:["graphTerm"],INTEGER_NEGATIVE:["graphTerm"],DECIMAL_NEGATIVE:["graphTerm"],DOUBLE_NEGATIVE:["graphTerm"]},verb:{VAR1:["storeProperty","varOrIRIref"],VAR2:["storeProperty","varOrIRIref"],IRI_REF:["storeProperty","varOrIRIref"],PNAME_LN:["storeProperty","varOrIRIref"],PNAME_NS:["storeProperty","varOrIRIref"],a:["storeProperty","a"]},verbPath:{"^":["path"],a:["path"],"!":["path"],"(":["path"],IRI_REF:["path"],PNAME_LN:["path"],PNAME_NS:["path"]},verbSimple:{VAR1:["var"],VAR2:["var"]},whereClause:{"{":["?WHERE","groupGraphPattern"],WHERE:["?WHERE","groupGraphPattern"]}}),s=/^(GROUP_CONCAT|DATATYPE|BASE|PREFIX|SELECT|CONSTRUCT|DESCRIBE|ASK|FROM|NAMED|ORDER|BY|LIMIT|ASC|DESC|OFFSET|DISTINCT|REDUCED|WHERE|GRAPH|OPTIONAL|UNION|FILTER|GROUP|HAVING|AS|VALUES|LOAD|CLEAR|DROP|CREATE|MOVE|COPY|SILENT|INSERT|DELETE|DATA|WITH|TO|USING|NAMED|MINUS|BIND|LANGMATCHES|LANG|BOUND|SAMETERM|ISIRI|ISURI|ISBLANK|ISLITERAL|REGEX|TRUE|FALSE|UNDEF|ADD|DEFAULT|ALL|SERVICE|INTO|IN|NOT|IRI|URI|BNODE|RAND|ABS|CEIL|FLOOR|ROUND|CONCAT|STRLEN|UCASE|LCASE|ENCODE_FOR_URI|CONTAINS|STRSTARTS|STRENDS|STRBEFORE|STRAFTER|YEAR|MONTH|DAY|HOURS|MINUTES|SECONDS|TIMEZONE|TZ|NOW|UUID|STRUUID|MD5|SHA1|SHA256|SHA384|SHA512|COALESCE|IF|STRLANG|STRDT|ISNUMERIC|SUBSTR|REPLACE|EXISTS|COUNT|SUM|MIN|MAX|AVG|SAMPLE|SEPARATOR|STR)/i,a=/^(\*|a|\.|\{|\}|,|\(|\)|;|\[|\]|\|\||&&|=|!=|!|<=|>=|<|>|\+|-|\/|\^\^|\?|\||\^)/,l=null,u="sparql11",p="sparql11",c=!0,d=t(),f=d.terminal,h={"*[,, object]":3,"*[(,),object]":3,"*[(,),objectPath]":3,"*[/,pathEltOrInverse]":2,object:2,objectPath:2,objectList:2,objectListPath:2,storeProperty:2,pathMod:2,"?pathMod":2,propertyListNotEmpty:1,propertyList:1,propertyListPath:1,propertyListPathNotEmpty:1,"?[verb,objectList]":1,"?[or([verbPath, verbSimple]),objectList]":1},E={"}":1,"]":0,")":1,"{":-1,"(":-1,"*[;,?[or([verbPath,verbSimple]),objectList]]":1};
return{token:r,startState:function(){return{tokenize:r,OK:!0,complete:c,errorStartPos:null,errorEndPos:null,queryType:l,possibleCurrent:i(p),possibleNext:i(p),allowVars:!0,allowBnodes:!0,storeProperty:!1,lastProperty:"",stack:[p]}},indent:n,electricChars:"}])"}});e.defineMIME("application/x-sparql-query","sparql11")})},{codemirror:14}],4:[function(e,t){var i=t.exports=function(){this.words=0;this.prefixes=0;this.children=[]};i.prototype={insert:function(e,t){if(0!=e.length){var r,n,o=this;void 0===t&&(t=0);if(t!==e.length){o.prefixes++;r=e[t];void 0===o.children[r]&&(o.children[r]=new i);n=o.children[r];n.insert(e,t+1)}else o.words++}},remove:function(e,t){if(0!=e.length){var i,r,n=this;void 0===t&&(t=0);if(void 0!==n)if(t!==e.length){n.prefixes--;i=e[t];r=n.children[i];r.remove(e,t+1)}else n.words--}},update:function(e,t){if(0!=e.length&&0!=t.length){this.remove(e);this.insert(t)}},countWord:function(e,t){if(0==e.length)return 0;var i,r,n=this,o=0;void 0===t&&(t=0);if(t===e.length)return n.words;i=e[t];r=n.children[i];void 0!==r&&(o=r.countWord(e,t+1));return o},countPrefix:function(e,t){if(0==e.length)return 0;var i,r,n=this,o=0;void 0===t&&(t=0);if(t===e.length)return n.prefixes;var i=e[t];r=n.children[i];void 0!==r&&(o=r.countPrefix(e,t+1));return o},find:function(e){return 0==e.length?!1:this.countWord(e)>0?!0:!1},getAllWords:function(e){var t,i,r=this,n=[];void 0===e&&(e="");if(void 0===r)return[];r.words>0&&n.push(e);for(t in r.children){i=r.children[t];n=n.concat(i.getAllWords(e+t))}return n},autoComplete:function(e,t){var i,r,n=this;if(0==e.length)return void 0===t?n.getAllWords(e):[];void 0===t&&(t=0);i=e[t];r=n.children[i];return void 0===r?[]:t===e.length-1?r.getAllWords(e):r.autoComplete(e,t+1)}}},{}],5:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e){var t=e.getWrapperElement();e.state.fullScreenRestore={scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset,width:t.style.width,height:t.style.height};t.style.width="";t.style.height="auto";t.className+=" CodeMirror-fullscreen";document.documentElement.style.overflow="hidden";e.refresh()}function i(e){var t=e.getWrapperElement();t.className=t.className.replace(/\s*CodeMirror-fullscreen\b/,"");document.documentElement.style.overflow="";var i=e.state.fullScreenRestore;t.style.width=i.width;t.style.height=i.height;window.scrollTo(i.scrollLeft,i.scrollTop);e.refresh()}e.defineOption("fullScreen",!1,function(r,n,o){o==e.Init&&(o=!1);!o!=!n&&(n?t(r):i(r))})})},{"../../lib/codemirror":14}],6:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){function t(e,t,r,n){var o=e.getLineHandle(t.line),l=t.ch-1,u=l>=0&&a[o.text.charAt(l)]||a[o.text.charAt(++l)];if(!u)return null;var p=">"==u.charAt(1)?1:-1;if(r&&p>0!=(l==t.ch))return null;var c=e.getTokenTypeAt(s(t.line,l+1)),d=i(e,s(t.line,l+(p>0?1:0)),p,c||null,n);return null==d?null:{from:s(t.line,l),to:d&&d.pos,match:d&&d.ch==u.charAt(0),forward:p>0}}function i(e,t,i,r,n){for(var o=n&&n.maxScanLineLength||1e4,l=n&&n.maxScanLines||1e3,u=[],p=n&&n.bracketRegex?n.bracketRegex:/[(){}[\]]/,c=i>0?Math.min(t.line+l,e.lastLine()+1):Math.max(e.firstLine()-1,t.line-l),d=t.line;d!=c;d+=i){var f=e.getLine(d);if(f){var h=i>0?0:f.length-1,E=i>0?f.length:-1;if(!(f.length>o)){d==t.line&&(h=t.ch-(0>i?1:0));for(;h!=E;h+=i){var m=f.charAt(h);if(p.test(m)&&(void 0===r||e.getTokenTypeAt(s(d,h+1))==r)){var g=a[m];if(">"==g.charAt(1)==i>0)u.push(m);else{if(!u.length)return{pos:s(d,h),ch:m};u.pop()}}}}}}return d-i==(i>0?e.lastLine():e.firstLine())?!1:null}function r(e,i,r){for(var n=e.state.matchBrackets.maxHighlightLineLength||1e3,a=[],l=e.listSelections(),u=0;u<l.length;u++){var p=l[u].empty()&&t(e,l[u].head,!1,r);if(p&&e.getLine(p.from.line).length<=n){var c=p.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";a.push(e.markText(p.from,s(p.from.line,p.from.ch+1),{className:c}));p.to&&e.getLine(p.to.line).length<=n&&a.push(e.markText(p.to,s(p.to.line,p.to.ch+1),{className:c}))}}if(a.length){o&&e.state.focused&&e.display.input.focus();var d=function(){e.operation(function(){for(var e=0;e<a.length;e++)a[e].clear()})};if(!i)return d;setTimeout(d,800)}}function n(e){e.operation(function(){if(l){l();l=null}l=r(e,!1,e.state.matchBrackets)})}var o=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),s=e.Pos,a={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},l=null;e.defineOption("matchBrackets",!1,function(t,i,r){r&&r!=e.Init&&t.off("cursorActivity",n);if(i){t.state.matchBrackets="object"==typeof i?i:{};t.on("cursorActivity",n)}});e.defineExtension("matchBrackets",function(){r(this,!0)});e.defineExtension("findMatchingBracket",function(e,i,r){return t(this,e,i,r)});e.defineExtension("scanForBracket",function(e,t,r,n){return i(this,e,t,r,n)})})},{"../../lib/codemirror":14}],7:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";e.registerHelper("fold","brace",function(t,i){function r(r){for(var n=i.ch,l=0;;){var u=0>=n?-1:a.lastIndexOf(r,n-1);if(-1!=u){if(1==l&&u<i.ch)break;o=t.getTokenTypeAt(e.Pos(s,u+1));if(!/^(comment|string)/.test(o))return u+1;n=u-1}else{if(1==l)break;l=1;n=a.length}}}var n,o,s=i.line,a=t.getLine(s),l="{",u="}",n=r("{");if(null==n){l="[",u="]";n=r("[")}if(null!=n){var p,c,d=1,f=t.lastLine();e:for(var h=s;f>=h;++h)for(var E=t.getLine(h),m=h==s?n:0;;){var g=E.indexOf(l,m),v=E.indexOf(u,m);0>g&&(g=E.length);0>v&&(v=E.length);m=Math.min(g,v);if(m==E.length)break;if(t.getTokenTypeAt(e.Pos(h,m+1))==o)if(m==g)++d;else if(!--d){p=h;c=m;break e}++m}if(null!=p&&(s!=p||c!=n))return{from:e.Pos(s,n),to:e.Pos(p,c)}}});e.registerHelper("fold","import",function(t,i){function r(i){if(i<t.firstLine()||i>t.lastLine())return null;var r=t.getTokenAt(e.Pos(i,1));/\S/.test(r.string)||(r=t.getTokenAt(e.Pos(i,r.end+1)));if("keyword"!=r.type||"import"!=r.string)return null;for(var n=i,o=Math.min(t.lastLine(),i+10);o>=n;++n){var s=t.getLine(n),a=s.indexOf(";");if(-1!=a)return{startCh:r.end,end:e.Pos(n,a)}}}var n,i=i.line,o=r(i);if(!o||r(i-1)||(n=r(i-2))&&n.end.line==i-1)return null;for(var s=o.end;;){var a=r(s.line+1);if(null==a)break;s=a.end}return{from:t.clipPos(e.Pos(i,o.startCh+1)),to:s}});e.registerHelper("fold","include",function(t,i){function r(i){if(i<t.firstLine()||i>t.lastLine())return null;var r=t.getTokenAt(e.Pos(i,1));/\S/.test(r.string)||(r=t.getTokenAt(e.Pos(i,r.end+1)));return"meta"==r.type&&"#include"==r.string.slice(0,8)?r.start+8:void 0}var i=i.line,n=r(i);if(null==n||null!=r(i-1))return null;for(var o=i;;){var s=r(o+1);if(null==s)break;++o}return{from:e.Pos(i,n+1),to:t.clipPos(e.Pos(o))}})})},{"../../lib/codemirror":14}],8:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(t,n,o,s){function a(e){var i=l(t,n);if(!i||i.to.line-i.from.line<u)return null;for(var r=t.findMarksAt(i.from),o=0;o<r.length;++o)if(r[o].__isFold&&"fold"!==s){if(!e)return null;i.cleared=!0;r[o].clear()}return i}if(o&&o.call){var l=o;o=null}else var l=r(t,o,"rangeFinder");"number"==typeof n&&(n=e.Pos(n,0));var u=r(t,o,"minFoldSize"),p=a(!0);if(r(t,o,"scanUp"))for(;!p&&n.line>t.firstLine();){n=e.Pos(n.line-1,0);p=a(!1)}if(p&&!p.cleared&&"unfold"!==s){var c=i(t,o);e.on(c,"mousedown",function(t){d.clear();e.e_preventDefault(t)});var d=t.markText(p.from,p.to,{replacedWith:c,clearOnEnter:!0,__isFold:!0});d.on("clear",function(i,r){e.signal(t,"unfold",t,i,r)});e.signal(t,"fold",t,p.from,p.to)}}function i(e,t){var i=r(e,t,"widget");if("string"==typeof i){var n=document.createTextNode(i);i=document.createElement("span");i.appendChild(n);i.className="CodeMirror-foldmarker"}return i}function r(e,t,i){if(t&&void 0!==t[i])return t[i];var r=e.options.foldOptions;return r&&void 0!==r[i]?r[i]:n[i]}e.newFoldFunction=function(e,i){return function(r,n){t(r,n,{rangeFinder:e,widget:i})}};e.defineExtension("foldCode",function(e,i,r){t(this,e,i,r)});e.defineExtension("isFolded",function(e){for(var t=this.findMarksAt(e),i=0;i<t.length;++i)if(t[i].__isFold)return!0});e.commands.toggleFold=function(e){e.foldCode(e.getCursor())};e.commands.fold=function(e){e.foldCode(e.getCursor(),null,"fold")};e.commands.unfold=function(e){e.foldCode(e.getCursor(),null,"unfold")};e.commands.foldAll=function(t){t.operation(function(){for(var i=t.firstLine(),r=t.lastLine();r>=i;i++)t.foldCode(e.Pos(i,0),null,"fold")})};e.commands.unfoldAll=function(t){t.operation(function(){for(var i=t.firstLine(),r=t.lastLine();r>=i;i++)t.foldCode(e.Pos(i,0),null,"unfold")})};e.registerHelper("fold","combine",function(){var e=Array.prototype.slice.call(arguments,0);return function(t,i){for(var r=0;r<e.length;++r){var n=e[r](t,i);if(n)return n}}});e.registerHelper("fold","auto",function(e,t){for(var i=e.getHelpers(t,"fold"),r=0;r<i.length;r++){var n=i[r](e,t);if(n)return n}});var n={rangeFinder:e.fold.auto,widget:"↔",minFoldSize:0,scanUp:!1};e.defineOption("foldOptions",null);e.defineExtension("foldOption",function(e,t){return r(this,e,t)})})},{"../../lib/codemirror":14}],9:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror"),t("./foldcode")):"function"==typeof e&&e.amd?e(["../../lib/codemirror","./foldcode"],n):n(CodeMirror)})(function(e){"use strict";function t(e){this.options=e;this.from=this.to=0}function i(e){e===!0&&(e={});null==e.gutter&&(e.gutter="CodeMirror-foldgutter");null==e.indicatorOpen&&(e.indicatorOpen="CodeMirror-foldgutter-open");null==e.indicatorFolded&&(e.indicatorFolded="CodeMirror-foldgutter-folded");return e}function r(e,t){for(var i=e.findMarksAt(c(t)),r=0;r<i.length;++r)if(i[r].__isFold&&i[r].find().from.line==t)return!0}function n(e){if("string"==typeof e){var t=document.createElement("div");t.className=e+" CodeMirror-guttermarker-subtle";return t}return e.cloneNode(!0)}function o(e,t,i){var o=e.state.foldGutter.options,s=t,a=e.foldOption(o,"minFoldSize"),l=e.foldOption(o,"rangeFinder");e.eachLine(t,i,function(t){var i=null;if(r(e,s))i=n(o.indicatorFolded);else{var u=c(s,0),p=l&&l(e,u);p&&p.to.line-p.from.line>=a&&(i=n(o.indicatorOpen))}e.setGutterMarker(t,o.gutter,i);++s})}function s(e){var t=e.getViewport(),i=e.state.foldGutter;if(i){e.operation(function(){o(e,t.from,t.to)});i.from=t.from;i.to=t.to}}function a(e,t,i){var r=e.state.foldGutter.options;i==r.gutter&&e.foldCode(c(t,0),r.rangeFinder)}function l(e){var t=e.state.foldGutter,i=e.state.foldGutter.options;t.from=t.to=0;clearTimeout(t.changeUpdate);t.changeUpdate=setTimeout(function(){s(e)},i.foldOnChangeTimeSpan||600)}function u(e){var t=e.state.foldGutter,i=e.state.foldGutter.options;clearTimeout(t.changeUpdate);t.changeUpdate=setTimeout(function(){var i=e.getViewport();t.from==t.to||i.from-t.to>20||t.from-i.to>20?s(e):e.operation(function(){if(i.from<t.from){o(e,i.from,t.from);t.from=i.from}if(i.to>t.to){o(e,t.to,i.to);t.to=i.to}})},i.updateViewportTimeSpan||400)}function p(e,t){var i=e.state.foldGutter,r=t.line;r>=i.from&&r<i.to&&o(e,r,r+1)}e.defineOption("foldGutter",!1,function(r,n,o){if(o&&o!=e.Init){r.clearGutter(r.state.foldGutter.options.gutter);r.state.foldGutter=null;r.off("gutterClick",a);r.off("change",l);r.off("viewportChange",u);r.off("fold",p);r.off("unfold",p);r.off("swapDoc",s)}if(n){r.state.foldGutter=new t(i(n));s(r);r.on("gutterClick",a);r.on("change",l);r.on("viewportChange",u);r.on("fold",p);r.on("unfold",p);r.on("swapDoc",s)}});var c=e.Pos})},{"../../lib/codemirror":14,"./foldcode":8}],10:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e,t){return e.line-t.line||e.ch-t.ch}function i(e,t,i,r){this.line=t;this.ch=i;this.cm=e;this.text=e.getLine(t);this.min=r?r.from:e.firstLine();this.max=r?r.to-1:e.lastLine()}function r(e,t){var i=e.cm.getTokenTypeAt(d(e.line,t));return i&&/\btag\b/.test(i)}function n(e){if(!(e.line>=e.max)){e.ch=0;e.text=e.cm.getLine(++e.line);return!0}}function o(e){if(!(e.line<=e.min)){e.text=e.cm.getLine(--e.line);e.ch=e.text.length;return!0}}function s(e){for(;;){var t=e.text.indexOf(">",e.ch);if(-1==t){if(n(e))continue;return}if(r(e,t+1)){var i=e.text.lastIndexOf("/",t),o=i>-1&&!/\S/.test(e.text.slice(i+1,t));e.ch=t+1;return o?"selfClose":"regular"}e.ch=t+1}}function a(e){for(;;){var t=e.ch?e.text.lastIndexOf("<",e.ch-1):-1;if(-1==t){if(o(e))continue;return}if(r(e,t+1)){E.lastIndex=t;e.ch=t;var i=E.exec(e.text);if(i&&i.index==t)return i}else e.ch=t}}function l(e){for(;;){E.lastIndex=e.ch;var t=E.exec(e.text);if(!t){if(n(e))continue;return}if(r(e,t.index+1)){e.ch=t.index+t[0].length;return t}e.ch=t.index+1}}function u(e){for(;;){var t=e.ch?e.text.lastIndexOf(">",e.ch-1):-1;if(-1==t){if(o(e))continue;return}if(r(e,t+1)){var i=e.text.lastIndexOf("/",t),n=i>-1&&!/\S/.test(e.text.slice(i+1,t));e.ch=t+1;return n?"selfClose":"regular"}e.ch=t}}function p(e,t){for(var i=[];;){var r,n=l(e),o=e.line,a=e.ch-(n?n[0].length:0);if(!n||!(r=s(e)))return;if("selfClose"!=r)if(n[1]){for(var u=i.length-1;u>=0;--u)if(i[u]==n[2]){i.length=u;break}if(0>u&&(!t||t==n[2]))return{tag:n[2],from:d(o,a),to:d(e.line,e.ch)}}else i.push(n[2])}}function c(e,t){for(var i=[];;){var r=u(e);if(!r)return;if("selfClose"!=r){var n=e.line,o=e.ch,s=a(e);if(!s)return;if(s[1])i.push(s[2]);else{for(var l=i.length-1;l>=0;--l)if(i[l]==s[2]){i.length=l;break}if(0>l&&(!t||t==s[2]))return{tag:s[2],from:d(e.line,e.ch),to:d(n,o)}}}else a(e)}}var d=e.Pos,f="A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",h=f+"-:.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",E=new RegExp("<(/?)(["+f+"]["+h+"]*)","g");e.registerHelper("fold","xml",function(e,t){for(var r=new i(e,t.line,0);;){var n,o=l(r);if(!o||r.line!=t.line||!(n=s(r)))return;if(!o[1]&&"selfClose"!=n){var t=d(r.line,r.ch),a=p(r,o[2]);return a&&{from:t,to:a.from}}}});e.findMatchingTag=function(e,r,n){var o=new i(e,r.line,r.ch,n);if(-1!=o.text.indexOf(">")||-1!=o.text.indexOf("<")){var l=s(o),u=l&&d(o.line,o.ch),f=l&&a(o);if(l&&f&&!(t(o,r)>0)){var h={from:d(o.line,o.ch),to:u,tag:f[2]};if("selfClose"==l)return{open:h,close:null,at:"open"};if(f[1])return{open:c(o,f[2]),close:h,at:"close"};o=new i(e,u.line,u.ch,n);return{open:h,close:p(o,f[2]),at:"open"}}}};e.findEnclosingTag=function(e,t,r){for(var n=new i(e,t.line,t.ch,r);;){var o=c(n);if(!o)break;var s=new i(e,t.line,t.ch,r),a=p(s,o.tag);if(a)return{open:o,close:a}}};e.scanForClosingTag=function(e,t,r,n){var o=new i(e,t.line,t.ch,n?{from:0,to:n}:null);return p(o,r)}})},{"../../lib/codemirror":14}],11:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e,t){this.cm=e;this.options=this.buildOptions(t);this.widget=this.onClose=null}function i(e){return"string"==typeof e?e:e.text}function r(e,t){function i(e,i){var n;n="string"!=typeof i?function(e){return i(e,t)}:r.hasOwnProperty(i)?r[i]:i;o[e]=n}var r={Up:function(){t.moveFocus(-1)},Down:function(){t.moveFocus(1)},PageUp:function(){t.moveFocus(-t.menuSize()+1,!0)},PageDown:function(){t.moveFocus(t.menuSize()-1,!0)},Home:function(){t.setFocus(0)},End:function(){t.setFocus(t.length-1)},Enter:t.pick,Tab:t.pick,Esc:t.close},n=e.options.customKeys,o=n?{}:r;if(n)for(var s in n)n.hasOwnProperty(s)&&i(s,n[s]);var a=e.options.extraKeys;if(a)for(var s in a)a.hasOwnProperty(s)&&i(s,a[s]);return o}function n(e,t){for(;t&&t!=e;){if("LI"===t.nodeName.toUpperCase()&&t.parentNode==e)return t;t=t.parentNode}}function o(t,o){this.completion=t;this.data=o;var l=this,u=t.cm,p=this.hints=document.createElement("ul");p.className="CodeMirror-hints";this.selectedHint=o.selectedHint||0;for(var c=o.list,d=0;d<c.length;++d){var f=p.appendChild(document.createElement("li")),h=c[d],E=s+(d!=this.selectedHint?"":" "+a);null!=h.className&&(E=h.className+" "+E);f.className=E;h.render?h.render(f,o,h):f.appendChild(document.createTextNode(h.displayText||i(h)));f.hintId=d}var m=u.cursorCoords(t.options.alignWithWord?o.from:null),g=m.left,v=m.bottom,x=!0;p.style.left=g+"px";p.style.top=v+"px";var N=window.innerWidth||Math.max(document.body.offsetWidth,document.documentElement.offsetWidth),T=window.innerHeight||Math.max(document.body.offsetHeight,document.documentElement.offsetHeight);(t.options.container||document.body).appendChild(p);var L=p.getBoundingClientRect(),I=L.bottom-T;if(I>0){var y=L.bottom-L.top,A=m.top-(m.bottom-L.top);if(A-y>0){p.style.top=(v=m.top-y)+"px";x=!1}else if(y>T){p.style.height=T-5+"px";p.style.top=(v=m.bottom-L.top)+"px";var S=u.getCursor();if(o.from.ch!=S.ch){m=u.cursorCoords(S);p.style.left=(g=m.left)+"px";L=p.getBoundingClientRect()}}}var C=L.right-N;if(C>0){if(L.right-L.left>N){p.style.width=N-5+"px";C-=L.right-L.left-N}p.style.left=(g=m.left-C)+"px"}u.addKeyMap(this.keyMap=r(t,{moveFocus:function(e,t){l.changeActive(l.selectedHint+e,t)},setFocus:function(e){l.changeActive(e)},menuSize:function(){return l.screenAmount()},length:c.length,close:function(){t.close()},pick:function(){l.pick()},data:o}));if(t.options.closeOnUnfocus){var R;u.on("blur",this.onBlur=function(){R=setTimeout(function(){t.close()},100)});u.on("focus",this.onFocus=function(){clearTimeout(R)})}var b=u.getScrollInfo();u.on("scroll",this.onScroll=function(){var e=u.getScrollInfo(),i=u.getWrapperElement().getBoundingClientRect(),r=v+b.top-e.top,n=r-(window.pageYOffset||(document.documentElement||document.body).scrollTop);x||(n+=p.offsetHeight);if(n<=i.top||n>=i.bottom)return t.close();p.style.top=r+"px";p.style.left=g+b.left-e.left+"px"});e.on(p,"dblclick",function(e){var t=n(p,e.target||e.srcElement);if(t&&null!=t.hintId){l.changeActive(t.hintId);l.pick()}});e.on(p,"click",function(e){var i=n(p,e.target||e.srcElement);if(i&&null!=i.hintId){l.changeActive(i.hintId);t.options.completeOnSingleClick&&l.pick()}});e.on(p,"mousedown",function(){setTimeout(function(){u.focus()},20)});e.signal(o,"select",c[0],p.firstChild);return!0}var s="CodeMirror-hint",a="CodeMirror-hint-active";e.showHint=function(e,t,i){if(!t)return e.showHint(i);i&&i.async&&(t.async=!0);var r={hint:t};if(i)for(var n in i)r[n]=i[n];return e.showHint(r)};e.defineExtension("showHint",function(i){if(!(this.listSelections().length>1||this.somethingSelected())){this.state.completionActive&&this.state.completionActive.close();var r=this.state.completionActive=new t(this,i),n=r.options.hint;if(n){e.signal(this,"startCompletion",this);if(!n.async)return r.showHints(n(this,r.options));n(this,function(e){r.showHints(e)},r.options);return void 0}}});t.prototype={close:function(){if(this.active()){this.cm.state.completionActive=null;this.widget&&this.widget.close();this.onClose&&this.onClose();e.signal(this.cm,"endCompletion",this.cm)}},active:function(){return this.cm.state.completionActive==this},pick:function(t,r){var n=t.list[r];n.hint?n.hint(this.cm,t,n):this.cm.replaceRange(i(n),n.from||t.from,n.to||t.to,"complete");e.signal(t,"pick",n);this.close()},showHints:function(e){if(!e||!e.list.length||!this.active())return this.close();this.options.completeSingle&&1==e.list.length?this.pick(e,0):this.showWidget(e);return void 0},showWidget:function(t){function i(){if(!l){l=!0;p.close();p.cm.off("cursorActivity",a);t&&e.signal(t,"close")}}function r(){if(!l){e.signal(t,"update");var i=p.options.hint;i.async?i(p.cm,n,p.options):n(i(p.cm,p.options))}}function n(e){t=e;if(!l){if(!t||!t.list.length)return i();p.widget&&p.widget.close();p.widget=new o(p,t)}}function s(){if(u){E(u);u=0}}function a(){s();var e=p.cm.getCursor(),t=p.cm.getLine(e.line);if(e.line!=d.line||t.length-e.ch!=f-d.ch||e.ch<d.ch||p.cm.somethingSelected()||e.ch&&c.test(t.charAt(e.ch-1)))p.close();else{u=h(r);p.widget&&p.widget.close()}}this.widget=new o(this,t);e.signal(t,"shown");var l,u=0,p=this,c=this.options.closeCharacters,d=this.cm.getCursor(),f=this.cm.getLine(d.line).length,h=window.requestAnimationFrame||function(e){return setTimeout(e,1e3/60)},E=window.cancelAnimationFrame||clearTimeout;this.cm.on("cursorActivity",a);this.onClose=i},buildOptions:function(e){var t=this.cm.options.hintOptions,i={};for(var r in l)i[r]=l[r];if(t)for(var r in t)void 0!==t[r]&&(i[r]=t[r]);if(e)for(var r in e)void 0!==e[r]&&(i[r]=e[r]);return i}};o.prototype={close:function(){if(this.completion.widget==this){this.completion.widget=null;this.hints.parentNode.removeChild(this.hints);this.completion.cm.removeKeyMap(this.keyMap);var e=this.completion.cm;if(this.completion.options.closeOnUnfocus){e.off("blur",this.onBlur);e.off("focus",this.onFocus)}e.off("scroll",this.onScroll)}},pick:function(){this.completion.pick(this.data,this.selectedHint)},changeActive:function(t,i){t>=this.data.list.length?t=i?this.data.list.length-1:0:0>t&&(t=i?0:this.data.list.length-1);if(this.selectedHint!=t){var r=this.hints.childNodes[this.selectedHint];r.className=r.className.replace(" "+a,"");r=this.hints.childNodes[this.selectedHint=t];r.className+=" "+a;r.offsetTop<this.hints.scrollTop?this.hints.scrollTop=r.offsetTop-3:r.offsetTop+r.offsetHeight>this.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=r.offsetTop+r.offsetHeight-this.hints.clientHeight+3);e.signal(this.data,"select",this.data.list[this.selectedHint],r)}},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1}};e.registerHelper("hint","auto",function(t,i){var r,n=t.getHelpers(t.getCursor(),"hint");if(n.length)for(var o=0;o<n.length;o++){var s=n[o](t,i);if(s&&s.list.length)return s}else if(r=t.getHelper(t.getCursor(),"hintWords")){if(r)return e.hint.fromList(t,{words:r})}else if(e.hint.anyword)return e.hint.anyword(t,i)});e.registerHelper("hint","fromList",function(t,i){for(var r=t.getCursor(),n=t.getTokenAt(r),o=[],s=0;s<i.words.length;s++){var a=i.words[s];a.slice(0,n.string.length)==n.string&&o.push(a)}return o.length?{list:o,from:e.Pos(r.line,n.start),to:e.Pos(r.line,n.end)}:void 0});e.commands.autocomplete=e.showHint;var l={hint:e.hint.auto,completeSingle:!0,alignWithWord:!0,closeCharacters:/[\s()\[\]{};:>,]/,closeOnUnfocus:!0,completeOnSingleClick:!1,container:null,customKeys:null,extraKeys:null};e.defineOption("hintOptions",null)})},{"../../lib/codemirror":14}],12:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";e.runMode=function(t,i,r,n){var o=e.getMode(e.defaults,i),s=/MSIE \d/.test(navigator.userAgent),a=s&&(null==document.documentMode||document.documentMode<9);if(1==r.nodeType){var l=n&&n.tabSize||e.defaults.tabSize,u=r,p=0;u.innerHTML="";r=function(e,t){if("\n"!=e){for(var i="",r=0;;){var n=e.indexOf(" ",r);if(-1==n){i+=e.slice(r);p+=e.length-r;break}p+=n-r;i+=e.slice(r,n);var o=l-p%l;p+=o;for(var s=0;o>s;++s)i+=" ";r=n+1}if(t){var c=u.appendChild(document.createElement("span"));c.className="cm-"+t.replace(/ +/g," cm-");c.appendChild(document.createTextNode(i))}else u.appendChild(document.createTextNode(i))}else{u.appendChild(document.createTextNode(a?"\r":e));p=0}}}for(var c=e.splitLines(t),d=n&&n.state||e.startState(o),f=0,h=c.length;h>f;++f){f&&r("\n");var E=new e.StringStream(c[f]);!E.string&&o.blankLine&&o.blankLine(d);for(;!E.eol();){var m=o.token(E,d);r(E.current(),m,f,E.start,d);E.start=E.pos}}}})},{"../../lib/codemirror":14}],13:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e,t,n,o){this.atOccurrence=!1;this.doc=e;null==o&&"string"==typeof t&&(o=!1);n=n?e.clipPos(n):r(0,0);this.pos={from:n,to:n};if("string"!=typeof t){t.global||(t=new RegExp(t.source,t.ignoreCase?"ig":"g"));this.matches=function(i,n){if(i){t.lastIndex=0;for(var o,s,a=e.getLine(n.line).slice(0,n.ch),l=0;;){t.lastIndex=l;var u=t.exec(a);if(!u)break;o=u;s=o.index;l=o.index+(o[0].length||1);if(l==a.length)break}var p=o&&o[0].length||0;p||(0==s&&0==a.length?o=void 0:s!=e.getLine(n.line).length&&p++)}else{t.lastIndex=n.ch;var a=e.getLine(n.line),o=t.exec(a),p=o&&o[0].length||0,s=o&&o.index;s+p==a.length||p||(p=1)}return o&&p?{from:r(n.line,s),to:r(n.line,s+p),match:o}:void 0}}else{var s=t;o&&(t=t.toLowerCase());var a=o?function(e){return e.toLowerCase()}:function(e){return e},l=t.split("\n");if(1==l.length)this.matches=t.length?function(n,o){if(n){var l=e.getLine(o.line).slice(0,o.ch),u=a(l),p=u.lastIndexOf(t);if(p>-1){p=i(l,u,p);return{from:r(o.line,p),to:r(o.line,p+s.length)}}}else{var l=e.getLine(o.line).slice(o.ch),u=a(l),p=u.indexOf(t);if(p>-1){p=i(l,u,p)+o.ch;return{from:r(o.line,p),to:r(o.line,p+s.length)}}}}:function(){};else{var u=s.split("\n");this.matches=function(t,i){var n=l.length-1;if(t){if(i.line-(l.length-1)<e.firstLine())return;if(a(e.getLine(i.line).slice(0,u[n].length))!=l[l.length-1])return;for(var o=r(i.line,u[n].length),s=i.line-1,p=n-1;p>=1;--p,--s)if(l[p]!=a(e.getLine(s)))return;var c=e.getLine(s),d=c.length-u[0].length;if(a(c.slice(d))!=l[0])return;return{from:r(s,d),to:o}}if(!(i.line+(l.length-1)>e.lastLine())){var c=e.getLine(i.line),d=c.length-u[0].length;if(a(c.slice(d))==l[0]){for(var f=r(i.line,d),s=i.line+1,p=1;n>p;++p,++s)if(l[p]!=a(e.getLine(s)))return;if(a(e.getLine(s).slice(0,u[n].length))==l[n])return{from:f,to:r(s,u[n].length)}}}}}}}function i(e,t,i){if(e.length==t.length)return i;for(var r=Math.min(i,e.length);;){var n=e.slice(0,r).toLowerCase().length;if(i>n)++r;else{if(!(n>i))return r;--r}}}var r=e.Pos;t.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(e){function t(e){var t=r(e,0);i.pos={from:t,to:t};i.atOccurrence=!1;return!1}for(var i=this,n=this.doc.clipPos(e?this.pos.from:this.pos.to);;){if(this.pos=this.matches(e,n)){this.atOccurrence=!0;return this.pos.match||!0}if(e){if(!n.line)return t(0);n=r(n.line-1,this.doc.getLine(n.line-1).length)}else{var o=this.doc.lineCount();if(n.line==o-1)return t(o);n=r(n.line+1,0)}}},from:function(){return this.atOccurrence?this.pos.from:void 0},to:function(){return this.atOccurrence?this.pos.to:void 0},replace:function(t){if(this.atOccurrence){var i=e.splitLines(t);this.doc.replaceRange(i,this.pos.from,this.pos.to);this.pos.to=r(this.pos.from.line+i.length-1,i[i.length-1].length+(1==i.length?this.pos.from.ch:0))}}};e.defineExtension("getSearchCursor",function(e,i,r){return new t(this.doc,e,i,r)});e.defineDocExtension("getSearchCursor",function(e,i,r){return new t(this,e,i,r)});e.defineExtension("selectMatches",function(t,i){for(var r,n=[],o=this.getSearchCursor(t,this.getCursor("from"),i);(r=o.findNext())&&!(e.cmpPos(o.to(),this.getCursor("to"))>0);)n.push({anchor:o.from(),head:o.to()});n.length&&this.setSelections(n,0)})})},{"../../lib/codemirror":14}],14:[function(t,i,r){(function(t){if("object"==typeof r&&"object"==typeof i)i.exports=t();else{if("function"==typeof e&&e.amd)return e([],t);this.CodeMirror=t()}})(function(){"use strict";function e(i,r){if(!(this instanceof e))return new e(i,r);this.options=r=r?yo(r):{};yo(Us,r,!1);f(r);var n=r.value;"string"==typeof n&&(n=new ua(n,r.mode));this.doc=n;var o=this.display=new t(i,n);o.wrapper.CodeMirror=this;u(this);a(this);r.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap");r.autofocus&&!Es&&Oi(this);g(this);this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,draggingText:!1,highlight:new go,keySeq:null};ns&&11>os&&setTimeout(Ao(bi,this,!0),20);wi(this);Go();ni(this);this.curOp.forceUpdate=!0;Gn(this,n);r.autofocus&&!Es||wo()==o.input?setTimeout(Ao(rr,this),20):nr(this);for(var s in Vs)Vs.hasOwnProperty(s)&&Vs[s](this,r[s],Fs);L(this);for(var l=0;l<qs.length;++l)qs[l](this);si(this);ss&&r.lineWrapping&&"optimizelegibility"==getComputedStyle(o.lineDiv).textRendering&&(o.lineDiv.style.textRendering="auto")}function t(e,t){var i=this,r=i.input=bo("textarea",null,null,"position: absolute; padding: 0; width: 1px; height: 1em; outline: none");ss?r.style.width="1000px":r.setAttribute("wrap","off");hs&&(r.style.border="1px solid black");r.setAttribute("autocorrect","off");r.setAttribute("autocapitalize","off");r.setAttribute("spellcheck","false");i.inputDiv=bo("div",[r],null,"overflow: hidden; position: relative; width: 3px; height: 0px;");i.scrollbarFiller=bo("div",null,"CodeMirror-scrollbar-filler");i.scrollbarFiller.setAttribute("not-content","true");i.gutterFiller=bo("div",null,"CodeMirror-gutter-filler");i.gutterFiller.setAttribute("not-content","true");i.lineDiv=bo("div",null,"CodeMirror-code");i.selectionDiv=bo("div",null,null,"position: relative; z-index: 1");i.cursorDiv=bo("div",null,"CodeMirror-cursors");i.measure=bo("div",null,"CodeMirror-measure");i.lineMeasure=bo("div",null,"CodeMirror-measure");i.lineSpace=bo("div",[i.measure,i.lineMeasure,i.selectionDiv,i.cursorDiv,i.lineDiv],null,"position: relative; outline: none");i.mover=bo("div",[bo("div",[i.lineSpace],"CodeMirror-lines")],null,"position: relative");i.sizer=bo("div",[i.mover],"CodeMirror-sizer");i.sizerWidth=null;i.heightForcer=bo("div",null,null,"position: absolute; height: "+xa+"px; width: 1px;");i.gutters=bo("div",null,"CodeMirror-gutters");i.lineGutter=null;i.scroller=bo("div",[i.sizer,i.heightForcer,i.gutters],"CodeMirror-scroll");i.scroller.setAttribute("tabIndex","-1");i.wrapper=bo("div",[i.inputDiv,i.scrollbarFiller,i.gutterFiller,i.scroller],"CodeMirror");if(ns&&8>os){i.gutters.style.zIndex=-1;i.scroller.style.paddingRight=0}hs&&(r.style.width="0px");ss||(i.scroller.draggable=!0);if(cs){i.inputDiv.style.height="1px";i.inputDiv.style.position="absolute"}e&&(e.appendChild?e.appendChild(i.wrapper):e(i.wrapper));i.viewFrom=i.viewTo=t.first;i.reportedViewFrom=i.reportedViewTo=t.first;i.view=[];i.renderedView=null;i.externalMeasured=null;i.viewOffset=0;i.lastWrapHeight=i.lastWrapWidth=0;i.updateLineNumbers=null;i.nativeBarWidth=i.barHeight=i.barWidth=0;i.scrollbarsClipped=!1;i.lineNumWidth=i.lineNumInnerWidth=i.lineNumChars=null;i.prevInput="";i.alignWidgets=!1;i.pollingFast=!1;i.poll=new go;i.cachedCharWidth=i.cachedTextHeight=i.cachedPaddingH=null;i.inaccurateSelection=!1;i.maxLine=null;i.maxLineLength=0;i.maxLineChanged=!1;i.wheelDX=i.wheelDY=i.wheelStartX=i.wheelStartY=null;i.shift=!1;i.selForContextMenu=null}function i(t){t.doc.mode=e.getMode(t.options,t.doc.modeOption);r(t)}function r(e){e.doc.iter(function(e){e.stateAfter&&(e.stateAfter=null);e.styles&&(e.styles=null)});e.doc.frontier=e.doc.first;yt(e,100);e.state.modeGen++;e.curOp&&xi(e)}function n(e){if(e.options.lineWrapping){_a(e.display.wrapper,"CodeMirror-wrap");e.display.sizer.style.minWidth="";e.display.sizerWidth=null}else{wa(e.display.wrapper,"CodeMirror-wrap");d(e)}s(e);xi(e);qt(e);setTimeout(function(){v(e)},100)}function o(e){var t=ii(e.display),i=e.options.lineWrapping,r=i&&Math.max(5,e.display.scroller.clientWidth/ri(e.display)-3);return function(n){if(un(e.doc,n))return 0;var o=0;if(n.widgets)for(var s=0;s<n.widgets.length;s++)n.widgets[s].height&&(o+=n.widgets[s].height);return i?o+(Math.ceil(n.text.length/r)||1)*t:o+t}}function s(e){var t=e.doc,i=o(e);t.iter(function(e){var t=i(e);t!=e.height&&Fn(e,t)})}function a(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-");qt(e)}function l(e){u(e);xi(e);setTimeout(function(){T(e)
},20)}function u(e){var t=e.display.gutters,i=e.options.gutters;Oo(t);for(var r=0;r<i.length;++r){var n=i[r],o=t.appendChild(bo("div",null,"CodeMirror-gutter "+n));if("CodeMirror-linenumbers"==n){e.display.lineGutter=o;o.style.width=(e.display.lineNumWidth||1)+"px"}}t.style.display=r?"":"none";p(e)}function p(e){var t=e.display.gutters.offsetWidth;e.display.sizer.style.marginLeft=t+"px"}function c(e){if(0==e.height)return 0;for(var t,i=e.text.length,r=e;t=tn(r);){var n=t.find(0,!0);r=n.from.line;i+=n.from.ch-n.to.ch}r=e;for(;t=rn(r);){var n=t.find(0,!0);i-=r.text.length-n.from.ch;r=n.to.line;i+=r.text.length-n.to.ch}return i}function d(e){var t=e.display,i=e.doc;t.maxLine=Bn(i,i.first);t.maxLineLength=c(t.maxLine);t.maxLineChanged=!0;i.iter(function(e){var i=c(e);if(i>t.maxLineLength){t.maxLineLength=i;t.maxLine=e}})}function f(e){var t=To(e.gutters,"CodeMirror-linenumbers");if(-1==t&&e.lineNumbers)e.gutters=e.gutters.concat(["CodeMirror-linenumbers"]);else if(t>-1&&!e.lineNumbers){e.gutters=e.gutters.slice(0);e.gutters.splice(t,1)}}function h(e){var t=e.display,i=t.gutters.offsetWidth,r=Math.round(e.doc.height+bt(e.display));return{clientHeight:t.scroller.clientHeight,viewHeight:t.wrapper.clientHeight,scrollWidth:t.scroller.scrollWidth,clientWidth:t.scroller.clientWidth,viewWidth:t.wrapper.clientWidth,barLeft:e.options.fixedGutter?i:0,docHeight:r,scrollHeight:r+Pt(e)+t.barHeight,nativeBarWidth:t.nativeBarWidth,gutterWidth:i}}function E(e,t,i){this.cm=i;var r=this.vert=bo("div",[bo("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),n=this.horiz=bo("div",[bo("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");e(r);e(n);Ea(r,"scroll",function(){r.clientHeight&&t(r.scrollTop,"vertical")});Ea(n,"scroll",function(){n.clientWidth&&t(n.scrollLeft,"horizontal")});this.checkedOverlay=!1;ns&&8>os&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")}function m(){}function g(t){if(t.display.scrollbars){t.display.scrollbars.clear();t.display.scrollbars.addClass&&wa(t.display.wrapper,t.display.scrollbars.addClass)}t.display.scrollbars=new e.scrollbarModel[t.options.scrollbarStyle](function(e){t.display.wrapper.insertBefore(e,t.display.scrollbarFiller);Ea(e,"mousedown",function(){t.state.focused&&setTimeout(Ao(Oi,t),0)});e.setAttribute("not-content","true")},function(e,i){"horizontal"==i?zi(t,e):qi(t,e)},t);t.display.scrollbars.addClass&&_a(t.display.wrapper,t.display.scrollbars.addClass)}function v(e,t){t||(t=h(e));var i=e.display.barWidth,r=e.display.barHeight;x(e,t);for(var n=0;4>n&&i!=e.display.barWidth||r!=e.display.barHeight;n++){i!=e.display.barWidth&&e.options.lineWrapping&&P(e);x(e,h(e));i=e.display.barWidth;r=e.display.barHeight}}function x(e,t){var i=e.display,r=i.scrollbars.update(t);i.sizer.style.paddingRight=(i.barWidth=r.right)+"px";i.sizer.style.paddingBottom=(i.barHeight=r.bottom)+"px";if(r.right&&r.bottom){i.scrollbarFiller.style.display="block";i.scrollbarFiller.style.height=r.bottom+"px";i.scrollbarFiller.style.width=r.right+"px"}else i.scrollbarFiller.style.display="";if(r.bottom&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter){i.gutterFiller.style.display="block";i.gutterFiller.style.height=r.bottom+"px";i.gutterFiller.style.width=t.gutterWidth+"px"}else i.gutterFiller.style.display=""}function N(e,t,i){var r=i&&null!=i.top?Math.max(0,i.top):e.scroller.scrollTop;r=Math.floor(r-Rt(e));var n=i&&null!=i.bottom?i.bottom:r+e.wrapper.clientHeight,o=jn(t,r),s=jn(t,n);if(i&&i.ensure){var a=i.ensure.from.line,l=i.ensure.to.line;if(o>a){o=a;s=jn(t,Wn(Bn(t,a))+e.wrapper.clientHeight)}else if(Math.min(l,t.lastLine())>=s){o=jn(t,Wn(Bn(t,l))-e.wrapper.clientHeight);s=l}}return{from:o,to:Math.max(s,o+1)}}function T(e){var t=e.display,i=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var r=y(t)-t.scroller.scrollLeft+e.doc.scrollLeft,n=t.gutters.offsetWidth,o=r+"px",s=0;s<i.length;s++)if(!i[s].hidden){e.options.fixedGutter&&i[s].gutter&&(i[s].gutter.style.left=o);var a=i[s].alignable;if(a)for(var l=0;l<a.length;l++)a[l].style.left=o}e.options.fixedGutter&&(t.gutters.style.left=r+n+"px")}}function L(e){if(!e.options.lineNumbers)return!1;var t=e.doc,i=I(e.options,t.first+t.size-1),r=e.display;if(i.length!=r.lineNumChars){var n=r.measure.appendChild(bo("div",[bo("div",i)],"CodeMirror-linenumber CodeMirror-gutter-elt")),o=n.firstChild.offsetWidth,s=n.offsetWidth-o;r.lineGutter.style.width="";r.lineNumInnerWidth=Math.max(o,r.lineGutter.offsetWidth-s);r.lineNumWidth=r.lineNumInnerWidth+s;r.lineNumChars=r.lineNumInnerWidth?i.length:-1;r.lineGutter.style.width=r.lineNumWidth+"px";p(e);return!0}return!1}function I(e,t){return String(e.lineNumberFormatter(t+e.firstLineNumber))}function y(e){return e.scroller.getBoundingClientRect().left-e.sizer.getBoundingClientRect().left}function A(e,t,i){var r=e.display;this.viewport=t;this.visible=N(r,e.doc,t);this.editorIsHidden=!r.wrapper.offsetWidth;this.wrapperHeight=r.wrapper.clientHeight;this.wrapperWidth=r.wrapper.clientWidth;this.oldDisplayWidth=Dt(e);this.force=i;this.dims=w(e)}function S(e){var t=e.display;if(!t.scrollbarsClipped&&t.scroller.offsetWidth){t.nativeBarWidth=t.scroller.offsetWidth-t.scroller.clientWidth;t.heightForcer.style.height=Pt(e)+"px";t.sizer.style.marginBottom=-t.nativeBarWidth+"px";t.sizer.style.borderRightWidth=Pt(e)+"px";t.scrollbarsClipped=!0}}function C(e,t){var i=e.display,r=e.doc;if(t.editorIsHidden){Ti(e);return!1}if(!t.force&&t.visible.from>=i.viewFrom&&t.visible.to<=i.viewTo&&(null==i.updateLineNumbers||i.updateLineNumbers>=i.viewTo)&&i.renderedView==i.view&&0==Ai(e))return!1;if(L(e)){Ti(e);t.dims=w(e)}var n=r.first+r.size,o=Math.max(t.visible.from-e.options.viewportMargin,r.first),s=Math.min(n,t.visible.to+e.options.viewportMargin);i.viewFrom<o&&o-i.viewFrom<20&&(o=Math.max(r.first,i.viewFrom));i.viewTo>s&&i.viewTo-s<20&&(s=Math.min(n,i.viewTo));if(Ls){o=an(e.doc,o);s=ln(e.doc,s)}var a=o!=i.viewFrom||s!=i.viewTo||i.lastWrapHeight!=t.wrapperHeight||i.lastWrapWidth!=t.wrapperWidth;yi(e,o,s);i.viewOffset=Wn(Bn(e.doc,i.viewFrom));e.display.mover.style.top=i.viewOffset+"px";var l=Ai(e);if(!a&&0==l&&!t.force&&i.renderedView==i.view&&(null==i.updateLineNumbers||i.updateLineNumbers>=i.viewTo))return!1;var u=wo();l>4&&(i.lineDiv.style.display="none");_(e,i.updateLineNumbers,t.dims);l>4&&(i.lineDiv.style.display="");i.renderedView=i.view;u&&wo()!=u&&u.offsetHeight&&u.focus();Oo(i.cursorDiv);Oo(i.selectionDiv);i.gutters.style.height=0;if(a){i.lastWrapHeight=t.wrapperHeight;i.lastWrapWidth=t.wrapperWidth;yt(e,400)}i.updateLineNumbers=null;return!0}function R(e,t){for(var i=t.force,r=t.viewport,n=!0;;n=!1){if(n&&e.options.lineWrapping&&t.oldDisplayWidth!=Dt(e))i=!0;else{i=!1;r&&null!=r.top&&(r={top:Math.min(e.doc.height+bt(e.display)-wt(e),r.top)});t.visible=N(e.display,e.doc,r);if(t.visible.from>=e.display.viewFrom&&t.visible.to<=e.display.viewTo)break}if(!C(e,t))break;P(e);var o=h(e);Nt(e);O(e,o);v(e,o)}po(e,"update",e);if(e.display.viewFrom!=e.display.reportedViewFrom||e.display.viewTo!=e.display.reportedViewTo){po(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo);e.display.reportedViewFrom=e.display.viewFrom;e.display.reportedViewTo=e.display.viewTo}}function b(e,t){var i=new A(e,t);if(C(e,i)){P(e);R(e,i);var r=h(e);Nt(e);O(e,r);v(e,r)}}function O(e,t){e.display.sizer.style.minHeight=t.docHeight+"px";var i=t.docHeight+e.display.barHeight;e.display.heightForcer.style.top=i+"px";e.display.gutters.style.height=Math.max(i+Pt(e),t.clientHeight)+"px"}function P(e){for(var t=e.display,i=t.lineDiv.offsetTop,r=0;r<t.view.length;r++){var n,o=t.view[r];if(!o.hidden){if(ns&&8>os){var s=o.node.offsetTop+o.node.offsetHeight;n=s-i;i=s}else{var a=o.node.getBoundingClientRect();n=a.bottom-a.top}var l=o.line.height-n;2>n&&(n=ii(t));if(l>.001||-.001>l){Fn(o.line,n);D(o.line);if(o.rest)for(var u=0;u<o.rest.length;u++)D(o.rest[u])}}}}function D(e){if(e.widgets)for(var t=0;t<e.widgets.length;++t)e.widgets[t].height=e.widgets[t].node.offsetHeight}function w(e){for(var t=e.display,i={},r={},n=t.gutters.clientLeft,o=t.gutters.firstChild,s=0;o;o=o.nextSibling,++s){i[e.options.gutters[s]]=o.offsetLeft+o.clientLeft+n;r[e.options.gutters[s]]=o.clientWidth}return{fixedPos:y(t),gutterTotalWidth:t.gutters.offsetWidth,gutterLeft:i,gutterWidth:r,wrapperWidth:t.wrapper.clientWidth}}function _(e,t,i){function r(t){var i=t.nextSibling;ss&&ms&&e.display.currentWheelTarget==t?t.style.display="none":t.parentNode.removeChild(t);return i}for(var n=e.display,o=e.options.lineNumbers,s=n.lineDiv,a=s.firstChild,l=n.view,u=n.viewFrom,p=0;p<l.length;p++){var c=l[p];if(c.hidden);else if(c.node){for(;a!=c.node;)a=r(a);var d=o&&null!=t&&u>=t&&c.lineNumber;if(c.changes){To(c.changes,"gutter")>-1&&(d=!1);M(e,c,u,i)}if(d){Oo(c.lineNumber);c.lineNumber.appendChild(document.createTextNode(I(e.options,u)))}a=c.node.nextSibling}else{var f=j(e,c,u,i);s.insertBefore(f,a)}u+=c.size}for(;a;)a=r(a)}function M(e,t,i,r){for(var n=0;n<t.changes.length;n++){var o=t.changes[n];"text"==o?U(e,t):"gutter"==o?F(e,t,i,r):"class"==o?V(t):"widget"==o&&H(t,r)}t.changes=null}function k(e){if(e.node==e.text){e.node=bo("div",null,null,"position: relative");e.text.parentNode&&e.text.parentNode.replaceChild(e.node,e.text);e.node.appendChild(e.text);ns&&8>os&&(e.node.style.zIndex=2)}return e.node}function G(e){var t=e.bgClass?e.bgClass+" "+(e.line.bgClass||""):e.line.bgClass;t&&(t+=" CodeMirror-linebackground");if(e.background)if(t)e.background.className=t;else{e.background.parentNode.removeChild(e.background);e.background=null}else if(t){var i=k(e);e.background=i.insertBefore(bo("div",null,t),i.firstChild)}}function B(e,t){var i=e.display.externalMeasured;if(i&&i.line==t.line){e.display.externalMeasured=null;t.measure=i.measure;return i.built}return An(e,t)}function U(e,t){var i=t.text.className,r=B(e,t);t.text==t.node&&(t.node=r.pre);t.text.parentNode.replaceChild(r.pre,t.text);t.text=r.pre;if(r.bgClass!=t.bgClass||r.textClass!=t.textClass){t.bgClass=r.bgClass;t.textClass=r.textClass;V(t)}else i&&(t.text.className=i)}function V(e){G(e);e.line.wrapClass?k(e).className=e.line.wrapClass:e.node!=e.text&&(e.node.className="");var t=e.textClass?e.textClass+" "+(e.line.textClass||""):e.line.textClass;e.text.className=t||""}function F(e,t,i,r){if(t.gutter){t.node.removeChild(t.gutter);t.gutter=null}var n=t.line.gutterMarkers;if(e.options.lineNumbers||n){var o=k(t),s=t.gutter=o.insertBefore(bo("div",null,"CodeMirror-gutter-wrapper","left: "+(e.options.fixedGutter?r.fixedPos:-r.gutterTotalWidth)+"px; width: "+r.gutterTotalWidth+"px"),t.text);t.line.gutterClass&&(s.className+=" "+t.line.gutterClass);!e.options.lineNumbers||n&&n["CodeMirror-linenumbers"]||(t.lineNumber=s.appendChild(bo("div",I(e.options,i),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+r.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+e.display.lineNumInnerWidth+"px")));if(n)for(var a=0;a<e.options.gutters.length;++a){var l=e.options.gutters[a],u=n.hasOwnProperty(l)&&n[l];u&&s.appendChild(bo("div",[u],"CodeMirror-gutter-elt","left: "+r.gutterLeft[l]+"px; width: "+r.gutterWidth[l]+"px"))}}}function H(e,t){e.alignable&&(e.alignable=null);for(var i,r=e.node.firstChild;r;r=i){var i=r.nextSibling;"CodeMirror-linewidget"==r.className&&e.node.removeChild(r)}W(e,t)}function j(e,t,i,r){var n=B(e,t);t.text=t.node=n.pre;n.bgClass&&(t.bgClass=n.bgClass);n.textClass&&(t.textClass=n.textClass);V(t);F(e,t,i,r);W(t,r);return t.node}function W(e,t){q(e.line,e,t,!0);if(e.rest)for(var i=0;i<e.rest.length;i++)q(e.rest[i],e,t,!1)}function q(e,t,i,r){if(e.widgets)for(var n=k(t),o=0,s=e.widgets;o<s.length;++o){var a=s[o],l=bo("div",[a.node],"CodeMirror-linewidget");a.handleMouseEvents||l.setAttribute("cm-ignore-events","true");z(a,l,t,i);r&&a.above?n.insertBefore(l,t.gutter||t.text):n.appendChild(l);po(a,"redraw")}}function z(e,t,i,r){if(e.noHScroll){(i.alignable||(i.alignable=[])).push(t);var n=r.wrapperWidth;t.style.left=r.fixedPos+"px";if(!e.coverGutter){n-=r.gutterTotalWidth;t.style.paddingLeft=r.gutterTotalWidth+"px"}t.style.width=n+"px"}if(e.coverGutter){t.style.zIndex=5;t.style.position="relative";e.noHScroll||(t.style.marginLeft=-r.gutterTotalWidth+"px")}}function X(e){return Is(e.line,e.ch)}function Y(e,t){return ys(e,t)<0?t:e}function K(e,t){return ys(e,t)<0?e:t}function $(e,t){this.ranges=e;this.primIndex=t}function Q(e,t){this.anchor=e;this.head=t}function Z(e,t){var i=e[t];e.sort(function(e,t){return ys(e.from(),t.from())});t=To(e,i);for(var r=1;r<e.length;r++){var n=e[r],o=e[r-1];if(ys(o.to(),n.from())>=0){var s=K(o.from(),n.from()),a=Y(o.to(),n.to()),l=o.empty()?n.from()==n.head:o.from()==o.head;t>=r&&--t;e.splice(--r,2,new Q(l?a:s,l?s:a))}}return new $(e,t)}function J(e,t){return new $([new Q(e,t||e)],0)}function et(e,t){return Math.max(e.first,Math.min(t,e.first+e.size-1))}function tt(e,t){if(t.line<e.first)return Is(e.first,0);var i=e.first+e.size-1;return t.line>i?Is(i,Bn(e,i).text.length):it(t,Bn(e,t.line).text.length)}function it(e,t){var i=e.ch;return null==i||i>t?Is(e.line,t):0>i?Is(e.line,0):e}function rt(e,t){return t>=e.first&&t<e.first+e.size}function nt(e,t){for(var i=[],r=0;r<t.length;r++)i[r]=tt(e,t[r]);return i}function ot(e,t,i,r){if(e.cm&&e.cm.display.shift||e.extend){var n=t.anchor;if(r){var o=ys(i,n)<0;if(o!=ys(r,n)<0){n=i;i=r}else o!=ys(i,r)<0&&(i=r)}return new Q(n,i)}return new Q(r||i,i)}function st(e,t,i,r){dt(e,new $([ot(e,e.sel.primary(),t,i)],0),r)}function at(e,t,i){for(var r=[],n=0;n<e.sel.ranges.length;n++)r[n]=ot(e,e.sel.ranges[n],t[n],null);var o=Z(r,e.sel.primIndex);dt(e,o,i)}function lt(e,t,i,r){var n=e.sel.ranges.slice(0);n[t]=i;dt(e,Z(n,e.sel.primIndex),r)}function ut(e,t,i,r){dt(e,J(t,i),r)}function pt(e,t){var i={ranges:t.ranges,update:function(t){this.ranges=[];for(var i=0;i<t.length;i++)this.ranges[i]=new Q(tt(e,t[i].anchor),tt(e,t[i].head))}};ga(e,"beforeSelectionChange",e,i);e.cm&&ga(e.cm,"beforeSelectionChange",e.cm,i);return i.ranges!=t.ranges?Z(i.ranges,i.ranges.length-1):t}function ct(e,t,i){var r=e.history.done,n=No(r);if(n&&n.ranges){r[r.length-1]=t;ft(e,t,i)}else dt(e,t,i)}function dt(e,t,i){ft(e,t,i);Zn(e,e.sel,e.cm?e.cm.curOp.id:0/0,i)}function ft(e,t,i){(Eo(e,"beforeSelectionChange")||e.cm&&Eo(e.cm,"beforeSelectionChange"))&&(t=pt(e,t));var r=i&&i.bias||(ys(t.primary().head,e.sel.primary().head)<0?-1:1);ht(e,mt(e,t,r,!0));i&&i.scroll===!1||!e.cm||yr(e.cm)}function ht(e,t){if(!t.equals(e.sel)){e.sel=t;if(e.cm){e.cm.curOp.updateInput=e.cm.curOp.selectionChanged=!0;ho(e.cm)}po(e,"cursorActivity",e)}}function Et(e){ht(e,mt(e,e.sel,null,!1),Ta)}function mt(e,t,i,r){for(var n,o=0;o<t.ranges.length;o++){var s=t.ranges[o],a=gt(e,s.anchor,i,r),l=gt(e,s.head,i,r);if(n||a!=s.anchor||l!=s.head){n||(n=t.ranges.slice(0,o));n[o]=new Q(a,l)}}return n?Z(n,t.primIndex):t}function gt(e,t,i,r){var n=!1,o=t,s=i||1;e.cantEdit=!1;e:for(;;){var a=Bn(e,o.line);if(a.markedSpans)for(var l=0;l<a.markedSpans.length;++l){var u=a.markedSpans[l],p=u.marker;if((null==u.from||(p.inclusiveLeft?u.from<=o.ch:u.from<o.ch))&&(null==u.to||(p.inclusiveRight?u.to>=o.ch:u.to>o.ch))){if(r){ga(p,"beforeCursorEnter");if(p.explicitlyCleared){if(a.markedSpans){--l;continue}break}}if(!p.atomic)continue;var c=p.find(0>s?-1:1);if(0==ys(c,o)){c.ch+=s;c.ch<0?c=c.line>e.first?tt(e,Is(c.line-1)):null:c.ch>a.text.length&&(c=c.line<e.first+e.size-1?Is(c.line+1,0):null);if(!c){if(n){if(!r)return gt(e,t,i,!0);e.cantEdit=!0;return Is(e.first,0)}n=!0;c=t;s=-s}}o=c;continue e}}return o}}function vt(e){for(var t=e.display,i=e.doc,r={},n=r.cursors=document.createDocumentFragment(),o=r.selection=document.createDocumentFragment(),s=0;s<i.sel.ranges.length;s++){var a=i.sel.ranges[s],l=a.empty();(l||e.options.showCursorWhenSelecting)&&Tt(e,a,n);l||Lt(e,a,o)}if(e.options.moveInputWithCursor){var u=Qt(e,i.sel.primary().head,"div"),p=t.wrapper.getBoundingClientRect(),c=t.lineDiv.getBoundingClientRect();r.teTop=Math.max(0,Math.min(t.wrapper.clientHeight-10,u.top+c.top-p.top));r.teLeft=Math.max(0,Math.min(t.wrapper.clientWidth-10,u.left+c.left-p.left))}return r}function xt(e,t){Po(e.display.cursorDiv,t.cursors);Po(e.display.selectionDiv,t.selection);if(null!=t.teTop){e.display.inputDiv.style.top=t.teTop+"px";e.display.inputDiv.style.left=t.teLeft+"px"}}function Nt(e){xt(e,vt(e))}function Tt(e,t,i){var r=Qt(e,t.head,"div",null,null,!e.options.singleCursorHeightPerLine),n=i.appendChild(bo("div"," ","CodeMirror-cursor"));n.style.left=r.left+"px";n.style.top=r.top+"px";n.style.height=Math.max(0,r.bottom-r.top)*e.options.cursorHeight+"px";if(r.other){var o=i.appendChild(bo("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));o.style.display="";o.style.left=r.other.left+"px";o.style.top=r.other.top+"px";o.style.height=.85*(r.other.bottom-r.other.top)+"px"}}function Lt(e,t,i){function r(e,t,i,r){0>t&&(t=0);t=Math.round(t);r=Math.round(r);a.appendChild(bo("div",null,"CodeMirror-selected","position: absolute; left: "+e+"px; top: "+t+"px; width: "+(null==i?p-e:i)+"px; height: "+(r-t)+"px"))}function n(t,i,n){function o(i,r){return $t(e,Is(t,i),"div",c,r)}var a,l,c=Bn(s,t),d=c.text.length;Ho(qn(c),i||0,null==n?d:n,function(e,t,s){var c,f,h,E=o(e,"left");if(e==t){c=E;f=h=E.left}else{c=o(t-1,"right");if("rtl"==s){var m=E;E=c;c=m}f=E.left;h=c.right}null==i&&0==e&&(f=u);if(c.top-E.top>3){r(f,E.top,null,E.bottom);f=u;E.bottom<c.top&&r(f,E.bottom,null,c.top)}null==n&&t==d&&(h=p);(!a||E.top<a.top||E.top==a.top&&E.left<a.left)&&(a=E);(!l||c.bottom>l.bottom||c.bottom==l.bottom&&c.right>l.right)&&(l=c);u+1>f&&(f=u);r(f,c.top,h-f,c.bottom)});return{start:a,end:l}}var o=e.display,s=e.doc,a=document.createDocumentFragment(),l=Ot(e.display),u=l.left,p=Math.max(o.sizerWidth,Dt(e)-o.sizer.offsetLeft)-l.right,c=t.from(),d=t.to();if(c.line==d.line)n(c.line,c.ch,d.ch);else{var f=Bn(s,c.line),h=Bn(s,d.line),E=on(f)==on(h),m=n(c.line,c.ch,E?f.text.length+1:null).end,g=n(d.line,E?0:null,d.ch).start;if(E)if(m.top<g.top-2){r(m.right,m.top,null,m.bottom);r(u,g.top,g.left,g.bottom)}else r(m.right,m.top,g.left-m.right,m.bottom);m.bottom<g.top&&r(u,m.bottom,null,g.top)}i.appendChild(a)}function It(e){if(e.state.focused){var t=e.display;clearInterval(t.blinker);var i=!0;t.cursorDiv.style.visibility="";e.options.cursorBlinkRate>0?t.blinker=setInterval(function(){t.cursorDiv.style.visibility=(i=!i)?"":"hidden"},e.options.cursorBlinkRate):e.options.cursorBlinkRate<0&&(t.cursorDiv.style.visibility="hidden")}}function yt(e,t){e.doc.mode.startState&&e.doc.frontier<e.display.viewTo&&e.state.highlight.set(t,Ao(At,e))}function At(e){var t=e.doc;t.frontier<t.first&&(t.frontier=t.first);if(!(t.frontier>=e.display.viewTo)){var i=+new Date+e.options.workTime,r=Xs(t.mode,Ct(e,t.frontier)),n=[];t.iter(t.frontier,Math.min(t.first+t.size,e.display.viewTo+500),function(o){if(t.frontier>=e.display.viewFrom){var s=o.styles,a=Tn(e,o,r,!0);o.styles=a.styles;var l=o.styleClasses,u=a.classes;u?o.styleClasses=u:l&&(o.styleClasses=null);for(var p=!s||s.length!=o.styles.length||l!=u&&(!l||!u||l.bgClass!=u.bgClass||l.textClass!=u.textClass),c=0;!p&&c<s.length;++c)p=s[c]!=o.styles[c];p&&n.push(t.frontier);o.stateAfter=Xs(t.mode,r)}else{In(e,o.text,r);o.stateAfter=t.frontier%5==0?Xs(t.mode,r):null}++t.frontier;if(+new Date>i){yt(e,e.options.workDelay);return!0}});n.length&&fi(e,function(){for(var t=0;t<n.length;t++)Ni(e,n[t],"text")})}}function St(e,t,i){for(var r,n,o=e.doc,s=i?-1:t-(e.doc.mode.innerMode?1e3:100),a=t;a>s;--a){if(a<=o.first)return o.first;var l=Bn(o,a-1);if(l.stateAfter&&(!i||a<=o.frontier))return a;var u=ya(l.text,null,e.options.tabSize);if(null==n||r>u){n=a-1;r=u}}return n}function Ct(e,t,i){var r=e.doc,n=e.display;if(!r.mode.startState)return!0;var o=St(e,t,i),s=o>r.first&&Bn(r,o-1).stateAfter;s=s?Xs(r.mode,s):Ys(r.mode);r.iter(o,t,function(i){In(e,i.text,s);var a=o==t-1||o%5==0||o>=n.viewFrom&&o<n.viewTo;i.stateAfter=a?Xs(r.mode,s):null;++o});i&&(r.frontier=o);return s}function Rt(e){return e.lineSpace.offsetTop}function bt(e){return e.mover.offsetHeight-e.lineSpace.offsetHeight}function Ot(e){if(e.cachedPaddingH)return e.cachedPaddingH;var t=Po(e.measure,bo("pre","x")),i=window.getComputedStyle?window.getComputedStyle(t):t.currentStyle,r={left:parseInt(i.paddingLeft),right:parseInt(i.paddingRight)};isNaN(r.left)||isNaN(r.right)||(e.cachedPaddingH=r);return r}function Pt(e){return xa-e.display.nativeBarWidth}function Dt(e){return e.display.scroller.clientWidth-Pt(e)-e.display.barWidth}function wt(e){return e.display.scroller.clientHeight-Pt(e)-e.display.barHeight}function _t(e,t,i){var r=e.options.lineWrapping,n=r&&Dt(e);if(!t.measure.heights||r&&t.measure.width!=n){var o=t.measure.heights=[];if(r){t.measure.width=n;for(var s=t.text.firstChild.getClientRects(),a=0;a<s.length-1;a++){var l=s[a],u=s[a+1];Math.abs(l.bottom-u.bottom)>2&&o.push((l.bottom+u.top)/2-i.top)}}o.push(i.bottom-i.top)}}function Mt(e,t,i){if(e.line==t)return{map:e.measure.map,cache:e.measure.cache};for(var r=0;r<e.rest.length;r++)if(e.rest[r]==t)return{map:e.measure.maps[r],cache:e.measure.caches[r]};for(var r=0;r<e.rest.length;r++)if(Hn(e.rest[r])>i)return{map:e.measure.maps[r],cache:e.measure.caches[r],before:!0}}function kt(e,t){t=on(t);var i=Hn(t),r=e.display.externalMeasured=new gi(e.doc,t,i);r.lineN=i;var n=r.built=An(e,r);r.text=n.pre;Po(e.display.lineMeasure,n.pre);return r}function Gt(e,t,i,r){return Vt(e,Ut(e,t),i,r)}function Bt(e,t){if(t>=e.display.viewFrom&&t<e.display.viewTo)return e.display.view[Li(e,t)];var i=e.display.externalMeasured;return i&&t>=i.lineN&&t<i.lineN+i.size?i:void 0}function Ut(e,t){var i=Hn(t),r=Bt(e,i);r&&!r.text?r=null:r&&r.changes&&M(e,r,i,w(e));r||(r=kt(e,t));var n=Mt(r,t,i);return{line:t,view:r,rect:null,map:n.map,cache:n.cache,before:n.before,hasHeights:!1}}function Vt(e,t,i,r,n){t.before&&(i=-1);var o,s=i+(r||"");if(t.cache.hasOwnProperty(s))o=t.cache[s];else{t.rect||(t.rect=t.view.text.getBoundingClientRect());if(!t.hasHeights){_t(e,t.view,t.rect);t.hasHeights=!0}o=Ft(e,t,i,r);o.bogus||(t.cache[s]=o)}return{left:o.left,right:o.right,top:n?o.rtop:o.top,bottom:n?o.rbottom:o.bottom}}function Ft(e,t,i,r){for(var n,o,s,a,l=t.map,u=0;u<l.length;u+=3){var p=l[u],c=l[u+1];if(p>i){o=0;s=1;a="left"}else if(c>i){o=i-p;s=o+1}else if(u==l.length-3||i==c&&l[u+3]>i){s=c-p;o=s-1;i>=c&&(a="right")}if(null!=o){n=l[u+2];p==c&&r==(n.insertLeft?"left":"right")&&(a=r);if("left"==r&&0==o)for(;u&&l[u-2]==l[u-3]&&l[u-1].insertLeft;){n=l[(u-=3)+2];a="left"}if("right"==r&&o==c-p)for(;u<l.length-3&&l[u+3]==l[u+4]&&!l[u+5].insertLeft;){n=l[(u+=3)+2];a="right"}break}}var d;if(3==n.nodeType){for(var u=0;4>u;u++){for(;o&&Ro(t.line.text.charAt(p+o));)--o;for(;c>p+s&&Ro(t.line.text.charAt(p+s));)++s;if(ns&&9>os&&0==o&&s==c-p)d=n.parentNode.getBoundingClientRect();else if(ns&&e.options.lineWrapping){var f=Ca(n,o,s).getClientRects();d=f.length?f["right"==r?f.length-1:0]:Rs}else d=Ca(n,o,s).getBoundingClientRect()||Rs;if(d.left||d.right||0==o)break;s=o;o-=1;a="right"}ns&&11>os&&(d=Ht(e.display.measure,d))}else{o>0&&(a=r="right");var f;d=e.options.lineWrapping&&(f=n.getClientRects()).length>1?f["right"==r?f.length-1:0]:n.getBoundingClientRect()}if(ns&&9>os&&!o&&(!d||!d.left&&!d.right)){var h=n.parentNode.getClientRects()[0];d=h?{left:h.left,right:h.left+ri(e.display),top:h.top,bottom:h.bottom}:Rs}for(var E=d.top-t.rect.top,m=d.bottom-t.rect.top,g=(E+m)/2,v=t.view.measure.heights,u=0;u<v.length-1&&!(g<v[u]);u++);var x=u?v[u-1]:0,N=v[u],T={left:("right"==a?d.right:d.left)-t.rect.left,right:("left"==a?d.left:d.right)-t.rect.left,top:x,bottom:N};d.left||d.right||(T.bogus=!0);if(!e.options.singleCursorHeightPerLine){T.rtop=E;T.rbottom=m}return T}function Ht(e,t){if(!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI||!Fo(e))return t;var i=screen.logicalXDPI/screen.deviceXDPI,r=screen.logicalYDPI/screen.deviceYDPI;return{left:t.left*i,right:t.right*i,top:t.top*r,bottom:t.bottom*r}}function jt(e){if(e.measure){e.measure.cache={};e.measure.heights=null;if(e.rest)for(var t=0;t<e.rest.length;t++)e.measure.caches[t]={}}}function Wt(e){e.display.externalMeasure=null;Oo(e.display.lineMeasure);for(var t=0;t<e.display.view.length;t++)jt(e.display.view[t])}function qt(e){Wt(e);e.display.cachedCharWidth=e.display.cachedTextHeight=e.display.cachedPaddingH=null;e.options.lineWrapping||(e.display.maxLineChanged=!0);e.display.lineNumChars=null}function zt(){return window.pageXOffset||(document.documentElement||document.body).scrollLeft}function Xt(){return window.pageYOffset||(document.documentElement||document.body).scrollTop}function Yt(e,t,i,r){if(t.widgets)for(var n=0;n<t.widgets.length;++n)if(t.widgets[n].above){var o=dn(t.widgets[n]);i.top+=o;i.bottom+=o}if("line"==r)return i;r||(r="local");var s=Wn(t);"local"==r?s+=Rt(e.display):s-=e.display.viewOffset;if("page"==r||"window"==r){var a=e.display.lineSpace.getBoundingClientRect();s+=a.top+("window"==r?0:Xt());var l=a.left+("window"==r?0:zt());i.left+=l;i.right+=l}i.top+=s;i.bottom+=s;return i}function Kt(e,t,i){if("div"==i)return t;var r=t.left,n=t.top;if("page"==i){r-=zt();n-=Xt()}else if("local"==i||!i){var o=e.display.sizer.getBoundingClientRect();r+=o.left;n+=o.top}var s=e.display.lineSpace.getBoundingClientRect();return{left:r-s.left,top:n-s.top}}function $t(e,t,i,r,n){r||(r=Bn(e.doc,t.line));return Yt(e,r,Gt(e,r,t.ch,n),i)}function Qt(e,t,i,r,n,o){function s(t,s){var a=Vt(e,n,t,s?"right":"left",o);s?a.left=a.right:a.right=a.left;return Yt(e,r,a,i)}function a(e,t){var i=l[t],r=i.level%2;if(e==jo(i)&&t&&i.level<l[t-1].level){i=l[--t];e=Wo(i)-(i.level%2?0:1);r=!0}else if(e==Wo(i)&&t<l.length-1&&i.level<l[t+1].level){i=l[++t];e=jo(i)-i.level%2;r=!1}return r&&e==i.to&&e>i.from?s(e-1):s(e,r)}r=r||Bn(e.doc,t.line);n||(n=Ut(e,r));var l=qn(r),u=t.ch;if(!l)return s(u);var p=Qo(l,u),c=a(u,p);null!=Ha&&(c.other=a(u,Ha));return c}function Zt(e,t){var i=0,t=tt(e.doc,t);e.options.lineWrapping||(i=ri(e.display)*t.ch);var r=Bn(e.doc,t.line),n=Wn(r)+Rt(e.display);return{left:i,right:i,top:n,bottom:n+r.height}}function Jt(e,t,i,r){var n=Is(e,t);n.xRel=r;i&&(n.outside=!0);return n}function ei(e,t,i){var r=e.doc;i+=e.display.viewOffset;if(0>i)return Jt(r.first,0,!0,-1);var n=jn(r,i),o=r.first+r.size-1;if(n>o)return Jt(r.first+r.size-1,Bn(r,o).text.length,!0,1);0>t&&(t=0);for(var s=Bn(r,n);;){var a=ti(e,s,n,t,i),l=rn(s),u=l&&l.find(0,!0);if(!l||!(a.ch>u.from.ch||a.ch==u.from.ch&&a.xRel>0))return a;n=Hn(s=u.to.line)}}function ti(e,t,i,r,n){function o(r){var n=Qt(e,Is(i,r),"line",t,u);a=!0;if(s>n.bottom)return n.left-l;if(s<n.top)return n.left+l;a=!1;return n.left}var s=n-Wn(t),a=!1,l=2*e.display.wrapper.clientWidth,u=Ut(e,t),p=qn(t),c=t.text.length,d=qo(t),f=zo(t),h=o(d),E=a,m=o(f),g=a;if(r>m)return Jt(i,f,g,1);for(;;){if(p?f==d||f==Jo(t,d,1):1>=f-d){for(var v=h>r||m-r>=r-h?d:f,x=r-(v==d?h:m);Ro(t.text.charAt(v));)++v;var N=Jt(i,v,v==d?E:g,-1>x?-1:x>1?1:0);return N}var T=Math.ceil(c/2),L=d+T;if(p){L=d;for(var I=0;T>I;++I)L=Jo(t,L,1)}var y=o(L);if(y>r){f=L;m=y;(g=a)&&(m+=1e3);c=T}else{d=L;h=y;E=a;c-=T}}}function ii(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==As){As=bo("pre");for(var t=0;49>t;++t){As.appendChild(document.createTextNode("x"));As.appendChild(bo("br"))}As.appendChild(document.createTextNode("x"))}Po(e.measure,As);var i=As.offsetHeight/50;i>3&&(e.cachedTextHeight=i);Oo(e.measure);return i||1}function ri(e){if(null!=e.cachedCharWidth)return e.cachedCharWidth;var t=bo("span","xxxxxxxxxx"),i=bo("pre",[t]);Po(e.measure,i);var r=t.getBoundingClientRect(),n=(r.right-r.left)/10;n>2&&(e.cachedCharWidth=n);return n||10}function ni(e){e.curOp={cm:e,viewChanged:!1,startHeight:e.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,id:++Os};bs?bs.ops.push(e.curOp):e.curOp.ownsGroup=bs={ops:[e.curOp],delayedCallbacks:[]}}function oi(e){var t=e.delayedCallbacks,i=0;do{for(;i<t.length;i++)t[i]();for(var r=0;r<e.ops.length;r++){var n=e.ops[r];if(n.cursorActivityHandlers)for(;n.cursorActivityCalled<n.cursorActivityHandlers.length;)n.cursorActivityHandlers[n.cursorActivityCalled++](n.cm)}}while(i<t.length)}function si(e){var t=e.curOp,i=t.ownsGroup;if(i)try{oi(i)}finally{bs=null;for(var r=0;r<i.ops.length;r++)i.ops[r].cm.curOp=null;ai(i)}}function ai(e){for(var t=e.ops,i=0;i<t.length;i++)li(t[i]);for(var i=0;i<t.length;i++)ui(t[i]);for(var i=0;i<t.length;i++)pi(t[i]);for(var i=0;i<t.length;i++)ci(t[i]);for(var i=0;i<t.length;i++)di(t[i])}function li(e){var t=e.cm,i=t.display;S(t);e.updateMaxLine&&d(t);e.mustUpdate=e.viewChanged||e.forceUpdate||null!=e.scrollTop||e.scrollToPos&&(e.scrollToPos.from.line<i.viewFrom||e.scrollToPos.to.line>=i.viewTo)||i.maxLineChanged&&t.options.lineWrapping;e.update=e.mustUpdate&&new A(t,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function ui(e){e.updatedDisplay=e.mustUpdate&&C(e.cm,e.update)}function pi(e){var t=e.cm,i=t.display;e.updatedDisplay&&P(t);e.barMeasure=h(t);if(i.maxLineChanged&&!t.options.lineWrapping){e.adjustWidthTo=Gt(t,i.maxLine,i.maxLine.text.length).left+3;t.display.sizerWidth=e.adjustWidthTo;e.barMeasure.scrollWidth=Math.max(i.scroller.clientWidth,i.sizer.offsetLeft+e.adjustWidthTo+Pt(t)+t.display.barWidth);e.maxScrollLeft=Math.max(0,i.sizer.offsetLeft+e.adjustWidthTo-Dt(t))}(e.updatedDisplay||e.selectionChanged)&&(e.newSelectionNodes=vt(t))}function ci(e){var t=e.cm;if(null!=e.adjustWidthTo){t.display.sizer.style.minWidth=e.adjustWidthTo+"px";e.maxScrollLeft<t.doc.scrollLeft&&zi(t,Math.min(t.display.scroller.scrollLeft,e.maxScrollLeft),!0);t.display.maxLineChanged=!1}e.newSelectionNodes&&xt(t,e.newSelectionNodes);e.updatedDisplay&&O(t,e.barMeasure);(e.updatedDisplay||e.startHeight!=t.doc.height)&&v(t,e.barMeasure);e.selectionChanged&&It(t);t.state.focused&&e.updateInput&&bi(t,e.typing)}function di(e){var t=e.cm,i=t.display,r=t.doc;e.updatedDisplay&&R(t,e.update);null==i.wheelStartX||null==e.scrollTop&&null==e.scrollLeft&&!e.scrollToPos||(i.wheelStartX=i.wheelStartY=null);if(null!=e.scrollTop&&(i.scroller.scrollTop!=e.scrollTop||e.forceScroll)){r.scrollTop=Math.max(0,Math.min(i.scroller.scrollHeight-i.scroller.clientHeight,e.scrollTop));i.scrollbars.setScrollTop(r.scrollTop);i.scroller.scrollTop=r.scrollTop}if(null!=e.scrollLeft&&(i.scroller.scrollLeft!=e.scrollLeft||e.forceScroll)){r.scrollLeft=Math.max(0,Math.min(i.scroller.scrollWidth-Dt(t),e.scrollLeft));i.scrollbars.setScrollLeft(r.scrollLeft);i.scroller.scrollLeft=r.scrollLeft;T(t)}if(e.scrollToPos){var n=Nr(t,tt(r,e.scrollToPos.from),tt(r,e.scrollToPos.to),e.scrollToPos.margin);e.scrollToPos.isCursor&&t.state.focused&&xr(t,n)}var o=e.maybeHiddenMarkers,s=e.maybeUnhiddenMarkers;if(o)for(var a=0;a<o.length;++a)o[a].lines.length||ga(o[a],"hide");if(s)for(var a=0;a<s.length;++a)s[a].lines.length&&ga(s[a],"unhide");i.wrapper.offsetHeight&&(r.scrollTop=t.display.scroller.scrollTop);e.changeObjs&&ga(t,"changes",t,e.changeObjs)}function fi(e,t){if(e.curOp)return t();ni(e);try{return t()}finally{si(e)}}function hi(e,t){return function(){if(e.curOp)return t.apply(e,arguments);ni(e);try{return t.apply(e,arguments)}finally{si(e)}}}function Ei(e){return function(){if(this.curOp)return e.apply(this,arguments);ni(this);try{return e.apply(this,arguments)}finally{si(this)}}}function mi(e){return function(){var t=this.cm;if(!t||t.curOp)return e.apply(this,arguments);ni(t);try{return e.apply(this,arguments)}finally{si(t)}}}function gi(e,t,i){this.line=t;this.rest=sn(t);this.size=this.rest?Hn(No(this.rest))-i+1:1;this.node=this.text=null;this.hidden=un(e,t)}function vi(e,t,i){for(var r,n=[],o=t;i>o;o=r){var s=new gi(e.doc,Bn(e.doc,o),o);r=o+s.size;n.push(s)}return n}function xi(e,t,i,r){null==t&&(t=e.doc.first);null==i&&(i=e.doc.first+e.doc.size);r||(r=0);var n=e.display;r&&i<n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>t)&&(n.updateLineNumbers=t);e.curOp.viewChanged=!0;if(t>=n.viewTo)Ls&&an(e.doc,t)<n.viewTo&&Ti(e);else if(i<=n.viewFrom)if(Ls&&ln(e.doc,i+r)>n.viewFrom)Ti(e);
else{n.viewFrom+=r;n.viewTo+=r}else if(t<=n.viewFrom&&i>=n.viewTo)Ti(e);else if(t<=n.viewFrom){var o=Ii(e,i,i+r,1);if(o){n.view=n.view.slice(o.index);n.viewFrom=o.lineN;n.viewTo+=r}else Ti(e)}else if(i>=n.viewTo){var o=Ii(e,t,t,-1);if(o){n.view=n.view.slice(0,o.index);n.viewTo=o.lineN}else Ti(e)}else{var s=Ii(e,t,t,-1),a=Ii(e,i,i+r,1);if(s&&a){n.view=n.view.slice(0,s.index).concat(vi(e,s.lineN,a.lineN)).concat(n.view.slice(a.index));n.viewTo+=r}else Ti(e)}var l=n.externalMeasured;l&&(i<l.lineN?l.lineN+=r:t<l.lineN+l.size&&(n.externalMeasured=null))}function Ni(e,t,i){e.curOp.viewChanged=!0;var r=e.display,n=e.display.externalMeasured;n&&t>=n.lineN&&t<n.lineN+n.size&&(r.externalMeasured=null);if(!(t<r.viewFrom||t>=r.viewTo)){var o=r.view[Li(e,t)];if(null!=o.node){var s=o.changes||(o.changes=[]);-1==To(s,i)&&s.push(i)}}}function Ti(e){e.display.viewFrom=e.display.viewTo=e.doc.first;e.display.view=[];e.display.viewOffset=0}function Li(e,t){if(t>=e.display.viewTo)return null;t-=e.display.viewFrom;if(0>t)return null;for(var i=e.display.view,r=0;r<i.length;r++){t-=i[r].size;if(0>t)return r}}function Ii(e,t,i,r){var n,o=Li(e,t),s=e.display.view;if(!Ls||i==e.doc.first+e.doc.size)return{index:o,lineN:i};for(var a=0,l=e.display.viewFrom;o>a;a++)l+=s[a].size;if(l!=t){if(r>0){if(o==s.length-1)return null;n=l+s[o].size-t;o++}else n=l-t;t+=n;i+=n}for(;an(e.doc,i)!=i;){if(o==(0>r?0:s.length-1))return null;i+=r*s[o-(0>r?1:0)].size;o+=r}return{index:o,lineN:i}}function yi(e,t,i){var r=e.display,n=r.view;if(0==n.length||t>=r.viewTo||i<=r.viewFrom){r.view=vi(e,t,i);r.viewFrom=t}else{r.viewFrom>t?r.view=vi(e,t,r.viewFrom).concat(r.view):r.viewFrom<t&&(r.view=r.view.slice(Li(e,t)));r.viewFrom=t;r.viewTo<i?r.view=r.view.concat(vi(e,r.viewTo,i)):r.viewTo>i&&(r.view=r.view.slice(0,Li(e,i)))}r.viewTo=i}function Ai(e){for(var t=e.display.view,i=0,r=0;r<t.length;r++){var n=t[r];n.hidden||n.node&&!n.changes||++i}return i}function Si(e){e.display.pollingFast||e.display.poll.set(e.options.pollInterval,function(){Ri(e);e.state.focused&&Si(e)})}function Ci(e){function t(){var r=Ri(e);if(r||i){e.display.pollingFast=!1;Si(e)}else{i=!0;e.display.poll.set(60,t)}}var i=!1;e.display.pollingFast=!0;e.display.poll.set(20,t)}function Ri(e){var t=e.display.input,i=e.display.prevInput,r=e.doc;if(!e.state.focused||Ba(t)&&!i||Di(e)||e.options.disableInput||e.state.keySeq)return!1;if(e.state.pasteIncoming&&e.state.fakedLastChar){t.value=t.value.substring(0,t.value.length-1);e.state.fakedLastChar=!1}var n=t.value;if(n==i&&!e.somethingSelected())return!1;if(ns&&os>=9&&e.display.inputHasSelection===n||ms&&/[\uf700-\uf7ff]/.test(n)){bi(e);return!1}var o=!e.curOp;o&&ni(e);e.display.shift=!1;8203!=n.charCodeAt(0)||r.sel!=e.display.selForContextMenu||i||(i="");for(var s=0,a=Math.min(i.length,n.length);a>s&&i.charCodeAt(s)==n.charCodeAt(s);)++s;var l=n.slice(s),u=Ga(l),p=null;e.state.pasteIncoming&&r.sel.ranges.length>1&&(Ps&&Ps.join("\n")==l?p=r.sel.ranges.length%Ps.length==0&&Lo(Ps,Ga):u.length==r.sel.ranges.length&&(p=Lo(u,function(e){return[e]})));for(var c=r.sel.ranges.length-1;c>=0;c--){var d=r.sel.ranges[c],f=d.from(),h=d.to();s<i.length?f=Is(f.line,f.ch-(i.length-s)):e.state.overwrite&&d.empty()&&!e.state.pasteIncoming&&(h=Is(h.line,Math.min(Bn(r,h.line).text.length,h.ch+No(u).length)));var E=e.curOp.updateInput,m={from:f,to:h,text:p?p[c%p.length]:u,origin:e.state.pasteIncoming?"paste":e.state.cutIncoming?"cut":"+input"};dr(e.doc,m);po(e,"inputRead",e,m);if(l&&!e.state.pasteIncoming&&e.options.electricChars&&e.options.smartIndent&&d.head.ch<100&&(!c||r.sel.ranges[c-1].head.line!=d.head.line)){var g=e.getModeAt(d.head),v=Bs(m);if(g.electricChars){for(var x=0;x<g.electricChars.length;x++)if(l.indexOf(g.electricChars.charAt(x))>-1){Sr(e,v.line,"smart");break}}else g.electricInput&&g.electricInput.test(Bn(r,v.line).text.slice(0,v.ch))&&Sr(e,v.line,"smart")}}yr(e);e.curOp.updateInput=E;e.curOp.typing=!0;n.length>1e3||n.indexOf("\n")>-1?t.value=e.display.prevInput="":e.display.prevInput=n;o&&si(e);e.state.pasteIncoming=e.state.cutIncoming=!1;return!0}function bi(e,t){if(!e.display.contextMenuPending){var i,r,n=e.doc;if(e.somethingSelected()){e.display.prevInput="";var o=n.sel.primary();i=Ua&&(o.to().line-o.from().line>100||(r=e.getSelection()).length>1e3);var s=i?"-":r||e.getSelection();e.display.input.value=s;e.state.focused&&Sa(e.display.input);ns&&os>=9&&(e.display.inputHasSelection=s)}else if(!t){e.display.prevInput=e.display.input.value="";ns&&os>=9&&(e.display.inputHasSelection=null)}e.display.inaccurateSelection=i}}function Oi(e){"nocursor"==e.options.readOnly||Es&&wo()==e.display.input||e.display.input.focus()}function Pi(e){if(!e.state.focused){Oi(e);rr(e)}}function Di(e){return e.options.readOnly||e.doc.cantEdit}function wi(e){function t(t){fo(e,t)||ha(t)}function i(t){if(e.somethingSelected()){Ps=e.getSelections();if(r.inaccurateSelection){r.prevInput="";r.inaccurateSelection=!1;r.input.value=Ps.join("\n");Sa(r.input)}}else{for(var i=[],n=[],o=0;o<e.doc.sel.ranges.length;o++){var s=e.doc.sel.ranges[o].head.line,a={anchor:Is(s,0),head:Is(s+1,0)};n.push(a);i.push(e.getRange(a.anchor,a.head))}if("cut"==t.type)e.setSelections(n,null,Ta);else{r.prevInput="";r.input.value=i.join("\n");Sa(r.input)}Ps=i}"cut"==t.type&&(e.state.cutIncoming=!0)}var r=e.display;Ea(r.scroller,"mousedown",hi(e,Gi));ns&&11>os?Ea(r.scroller,"dblclick",hi(e,function(t){if(!fo(e,t)){var i=ki(e,t);if(i&&!Hi(e,t)&&!Mi(e.display,t)){da(t);var r=e.findWordAt(i);st(e.doc,r.anchor,r.head)}}})):Ea(r.scroller,"dblclick",function(t){fo(e,t)||da(t)});Ea(r.lineSpace,"selectstart",function(e){Mi(r,e)||da(e)});Ns||Ea(r.scroller,"contextmenu",function(t){or(e,t)});Ea(r.scroller,"scroll",function(){if(r.scroller.clientHeight){qi(e,r.scroller.scrollTop);zi(e,r.scroller.scrollLeft,!0);ga(e,"scroll",e)}});Ea(r.scroller,"mousewheel",function(t){Xi(e,t)});Ea(r.scroller,"DOMMouseScroll",function(t){Xi(e,t)});Ea(r.wrapper,"scroll",function(){r.wrapper.scrollTop=r.wrapper.scrollLeft=0});Ea(r.input,"keyup",function(t){tr.call(e,t)});Ea(r.input,"input",function(){ns&&os>=9&&e.display.inputHasSelection&&(e.display.inputHasSelection=null);Ri(e)});Ea(r.input,"keydown",hi(e,Ji));Ea(r.input,"keypress",hi(e,ir));Ea(r.input,"focus",Ao(rr,e));Ea(r.input,"blur",Ao(nr,e));if(e.options.dragDrop){Ea(r.scroller,"dragstart",function(t){Wi(e,t)});Ea(r.scroller,"dragenter",t);Ea(r.scroller,"dragover",t);Ea(r.scroller,"drop",hi(e,ji))}Ea(r.scroller,"paste",function(t){if(!Mi(r,t)){e.state.pasteIncoming=!0;Oi(e);Ci(e)}});Ea(r.input,"paste",function(){if(ss&&!e.state.fakedLastChar&&!(new Date-e.state.lastMiddleDown<200)){var t=r.input.selectionStart,i=r.input.selectionEnd;r.input.value+="$";r.input.selectionEnd=i;r.input.selectionStart=t;e.state.fakedLastChar=!0}e.state.pasteIncoming=!0;Ci(e)});Ea(r.input,"cut",i);Ea(r.input,"copy",i);cs&&Ea(r.sizer,"mouseup",function(){wo()==r.input&&r.input.blur();Oi(e)})}function _i(e){var t=e.display;if(t.lastWrapHeight!=t.wrapper.clientHeight||t.lastWrapWidth!=t.wrapper.clientWidth){t.cachedCharWidth=t.cachedTextHeight=t.cachedPaddingH=null;t.scrollbarsClipped=!1;e.setSize()}}function Mi(e,t){for(var i=lo(t);i!=e.wrapper;i=i.parentNode)if(!i||1==i.nodeType&&"true"==i.getAttribute("cm-ignore-events")||i.parentNode==e.sizer&&i!=e.mover)return!0}function ki(e,t,i,r){var n=e.display;if(!i&&"true"==lo(t).getAttribute("not-content"))return null;var o,s,a=n.lineSpace.getBoundingClientRect();try{o=t.clientX-a.left;s=t.clientY-a.top}catch(t){return null}var l,u=ei(e,o,s);if(r&&1==u.xRel&&(l=Bn(e.doc,u.line).text).length==u.ch){var p=ya(l,l.length,e.options.tabSize)-l.length;u=Is(u.line,Math.max(0,Math.round((o-Ot(e.display).left)/ri(e.display))-p))}return u}function Gi(e){if(!fo(this,e)){var t=this,i=t.display;i.shift=e.shiftKey;if(Mi(i,e)){if(!ss){i.scroller.draggable=!1;setTimeout(function(){i.scroller.draggable=!0},100)}}else if(!Hi(t,e)){var r=ki(t,e);window.focus();switch(uo(e)){case 1:r?Bi(t,e,r):lo(e)==i.scroller&&da(e);break;case 2:ss&&(t.state.lastMiddleDown=+new Date);r&&st(t.doc,r);setTimeout(Ao(Oi,t),20);da(e);break;case 3:Ns&&or(t,e)}}}}function Bi(e,t,i){setTimeout(Ao(Pi,e),0);var r,n=+new Date;if(Cs&&Cs.time>n-400&&0==ys(Cs.pos,i))r="triple";else if(Ss&&Ss.time>n-400&&0==ys(Ss.pos,i)){r="double";Cs={time:n,pos:i}}else{r="single";Ss={time:n,pos:i}}var o,s=e.doc.sel,a=ms?t.metaKey:t.ctrlKey;e.options.dragDrop&&ka&&!Di(e)&&"single"==r&&(o=s.contains(i))>-1&&!s.ranges[o].empty()?Ui(e,t,i,a):Vi(e,t,i,r,a)}function Ui(e,t,i,r){var n=e.display,o=hi(e,function(s){ss&&(n.scroller.draggable=!1);e.state.draggingText=!1;ma(document,"mouseup",o);ma(n.scroller,"drop",o);if(Math.abs(t.clientX-s.clientX)+Math.abs(t.clientY-s.clientY)<10){da(s);r||st(e.doc,i);Oi(e);ns&&9==os&&setTimeout(function(){document.body.focus();Oi(e)},20)}});ss&&(n.scroller.draggable=!0);e.state.draggingText=o;n.scroller.dragDrop&&n.scroller.dragDrop();Ea(document,"mouseup",o);Ea(n.scroller,"drop",o)}function Vi(e,t,i,r,n){function o(t){if(0!=ys(m,t)){m=t;if("rect"==r){for(var n=[],o=e.options.tabSize,s=ya(Bn(u,i.line).text,i.ch,o),a=ya(Bn(u,t.line).text,t.ch,o),l=Math.min(s,a),f=Math.max(s,a),h=Math.min(i.line,t.line),E=Math.min(e.lastLine(),Math.max(i.line,t.line));E>=h;h++){var g=Bn(u,h).text,v=vo(g,l,o);l==f?n.push(new Q(Is(h,v),Is(h,v))):g.length>v&&n.push(new Q(Is(h,v),Is(h,vo(g,f,o))))}n.length||n.push(new Q(i,i));dt(u,Z(d.ranges.slice(0,c).concat(n),c),{origin:"*mouse",scroll:!1});e.scrollIntoView(t)}else{var x=p,N=x.anchor,T=t;if("single"!=r){if("double"==r)var L=e.findWordAt(t);else var L=new Q(Is(t.line,0),tt(u,Is(t.line+1,0)));if(ys(L.anchor,N)>0){T=L.head;N=K(x.from(),L.anchor)}else{T=L.anchor;N=Y(x.to(),L.head)}}var n=d.ranges.slice(0);n[c]=new Q(tt(u,N),T);dt(u,Z(n,c),La)}}}function s(t){var i=++v,n=ki(e,t,!0,"rect"==r);if(n)if(0!=ys(n,m)){Pi(e);o(n);var a=N(l,u);(n.line>=a.to||n.line<a.from)&&setTimeout(hi(e,function(){v==i&&s(t)}),150)}else{var p=t.clientY<g.top?-20:t.clientY>g.bottom?20:0;p&&setTimeout(hi(e,function(){if(v==i){l.scroller.scrollTop+=p;s(t)}}),50)}}function a(t){v=1/0;da(t);Oi(e);ma(document,"mousemove",x);ma(document,"mouseup",T);u.history.lastSelOrigin=null}var l=e.display,u=e.doc;da(t);var p,c,d=u.sel,f=d.ranges;if(n&&!t.shiftKey){c=u.sel.contains(i);p=c>-1?f[c]:new Q(i,i)}else p=u.sel.primary();if(t.altKey){r="rect";n||(p=new Q(i,i));i=ki(e,t,!0,!0);c=-1}else if("double"==r){var h=e.findWordAt(i);p=e.display.shift||u.extend?ot(u,p,h.anchor,h.head):h}else if("triple"==r){var E=new Q(Is(i.line,0),tt(u,Is(i.line+1,0)));p=e.display.shift||u.extend?ot(u,p,E.anchor,E.head):E}else p=ot(u,p,i);if(n)if(-1==c){c=f.length;dt(u,Z(f.concat([p]),c),{scroll:!1,origin:"*mouse"})}else if(f.length>1&&f[c].empty()&&"single"==r){dt(u,Z(f.slice(0,c).concat(f.slice(c+1)),0));d=u.sel}else lt(u,c,p,La);else{c=0;dt(u,new $([p],0),La);d=u.sel}var m=i,g=l.wrapper.getBoundingClientRect(),v=0,x=hi(e,function(e){uo(e)?s(e):a(e)}),T=hi(e,a);Ea(document,"mousemove",x);Ea(document,"mouseup",T)}function Fi(e,t,i,r,n){try{var o=t.clientX,s=t.clientY}catch(t){return!1}if(o>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;r&&da(t);var a=e.display,l=a.lineDiv.getBoundingClientRect();if(s>l.bottom||!Eo(e,i))return ao(t);s-=l.top-a.viewOffset;for(var u=0;u<e.options.gutters.length;++u){var p=a.gutters.childNodes[u];if(p&&p.getBoundingClientRect().right>=o){var c=jn(e.doc,s),d=e.options.gutters[u];n(e,i,e,c,d,t);return ao(t)}}}function Hi(e,t){return Fi(e,t,"gutterClick",!0,po)}function ji(e){var t=this;if(!fo(t,e)&&!Mi(t.display,e)){da(e);ns&&(Ds=+new Date);var i=ki(t,e,!0),r=e.dataTransfer.files;if(i&&!Di(t))if(r&&r.length&&window.FileReader&&window.File)for(var n=r.length,o=Array(n),s=0,a=function(e,r){var a=new FileReader;a.onload=hi(t,function(){o[r]=a.result;if(++s==n){i=tt(t.doc,i);var e={from:i,to:i,text:Ga(o.join("\n")),origin:"paste"};dr(t.doc,e);ct(t.doc,J(i,Bs(e)))}});a.readAsText(e)},l=0;n>l;++l)a(r[l],l);else{if(t.state.draggingText&&t.doc.sel.contains(i)>-1){t.state.draggingText(e);setTimeout(Ao(Oi,t),20);return}try{var o=e.dataTransfer.getData("Text");if(o){if(t.state.draggingText&&!(ms?e.metaKey:e.ctrlKey))var u=t.listSelections();ft(t.doc,J(i,i));if(u)for(var l=0;l<u.length;++l)vr(t.doc,"",u[l].anchor,u[l].head,"drag");t.replaceSelection(o,"around","paste");Oi(t)}}catch(e){}}}}function Wi(e,t){if(ns&&(!e.state.draggingText||+new Date-Ds<100))ha(t);else if(!fo(e,t)&&!Mi(e.display,t)){t.dataTransfer.setData("Text",e.getSelection());if(t.dataTransfer.setDragImage&&!ps){var i=bo("img",null,null,"position: fixed; left: 0; top: 0;");i.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";if(us){i.width=i.height=1;e.display.wrapper.appendChild(i);i._top=i.offsetTop}t.dataTransfer.setDragImage(i,0,0);us&&i.parentNode.removeChild(i)}}}function qi(e,t){if(!(Math.abs(e.doc.scrollTop-t)<2)){e.doc.scrollTop=t;ts||b(e,{top:t});e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t);e.display.scrollbars.setScrollTop(t);ts&&b(e);yt(e,100)}}function zi(e,t,i){if(!(i?t==e.doc.scrollLeft:Math.abs(e.doc.scrollLeft-t)<2)){t=Math.min(t,e.display.scroller.scrollWidth-e.display.scroller.clientWidth);e.doc.scrollLeft=t;T(e);e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t);e.display.scrollbars.setScrollLeft(t)}}function Xi(e,t){var i=Ms(t),r=i.x,n=i.y,o=e.display,s=o.scroller;if(r&&s.scrollWidth>s.clientWidth||n&&s.scrollHeight>s.clientHeight){if(n&&ms&&ss)e:for(var a=t.target,l=o.view;a!=s;a=a.parentNode)for(var u=0;u<l.length;u++)if(l[u].node==a){e.display.currentWheelTarget=a;break e}if(!r||ts||us||null==_s){if(n&&null!=_s){var p=n*_s,c=e.doc.scrollTop,d=c+o.wrapper.clientHeight;0>p?c=Math.max(0,c+p-50):d=Math.min(e.doc.height,d+p+50);b(e,{top:c,bottom:d})}if(20>ws)if(null==o.wheelStartX){o.wheelStartX=s.scrollLeft;o.wheelStartY=s.scrollTop;o.wheelDX=r;o.wheelDY=n;setTimeout(function(){if(null!=o.wheelStartX){var e=s.scrollLeft-o.wheelStartX,t=s.scrollTop-o.wheelStartY,i=t&&o.wheelDY&&t/o.wheelDY||e&&o.wheelDX&&e/o.wheelDX;o.wheelStartX=o.wheelStartY=null;if(i){_s=(_s*ws+i)/(ws+1);++ws}}},200)}else{o.wheelDX+=r;o.wheelDY+=n}}else{n&&qi(e,Math.max(0,Math.min(s.scrollTop+n*_s,s.scrollHeight-s.clientHeight)));zi(e,Math.max(0,Math.min(s.scrollLeft+r*_s,s.scrollWidth-s.clientWidth)));da(t);o.wheelStartX=null}}}function Yi(e,t,i){if("string"==typeof t){t=Ks[t];if(!t)return!1}e.display.pollingFast&&Ri(e)&&(e.display.pollingFast=!1);var r=e.display.shift,n=!1;try{Di(e)&&(e.state.suppressEdits=!0);i&&(e.display.shift=!1);n=t(e)!=Na}finally{e.display.shift=r;e.state.suppressEdits=!1}return n}function Ki(e,t,i){for(var r=0;r<e.state.keyMaps.length;r++){var n=Qs(t,e.state.keyMaps[r],i,e);if(n)return n}return e.options.extraKeys&&Qs(t,e.options.extraKeys,i,e)||Qs(t,e.options.keyMap,i,e)}function $i(e,t,i,r){var n=e.state.keySeq;if(n){if(Zs(t))return"handled";ks.set(50,function(){if(e.state.keySeq==n){e.state.keySeq=null;bi(e)}});t=n+" "+t}var o=Ki(e,t,r);"multi"==o&&(e.state.keySeq=t);"handled"==o&&po(e,"keyHandled",e,t,i);if("handled"==o||"multi"==o){da(i);It(e)}if(n&&!o&&/\'$/.test(t)){da(i);return!0}return!!o}function Qi(e,t){var i=Js(t,!0);return i?t.shiftKey&&!e.state.keySeq?$i(e,"Shift-"+i,t,function(t){return Yi(e,t,!0)})||$i(e,i,t,function(t){return("string"==typeof t?/^go[A-Z]/.test(t):t.motion)?Yi(e,t):void 0}):$i(e,i,t,function(t){return Yi(e,t)}):!1}function Zi(e,t,i){return $i(e,"'"+i+"'",t,function(t){return Yi(e,t,!0)})}function Ji(e){var t=this;Pi(t);if(!fo(t,e)){ns&&11>os&&27==e.keyCode&&(e.returnValue=!1);var i=e.keyCode;t.display.shift=16==i||e.shiftKey;var r=Qi(t,e);if(us){Gs=r?i:null;!r&&88==i&&!Ua&&(ms?e.metaKey:e.ctrlKey)&&t.replaceSelection("",null,"cut")}18!=i||/\bCodeMirror-crosshair\b/.test(t.display.lineDiv.className)||er(t)}}function er(e){function t(e){if(18==e.keyCode||!e.altKey){wa(i,"CodeMirror-crosshair");ma(document,"keyup",t);ma(document,"mouseover",t)}}var i=e.display.lineDiv;_a(i,"CodeMirror-crosshair");Ea(document,"keyup",t);Ea(document,"mouseover",t)}function tr(e){16==e.keyCode&&(this.doc.sel.shift=!1);fo(this,e)}function ir(e){var t=this;if(!(fo(t,e)||e.ctrlKey&&!e.altKey||ms&&e.metaKey)){var i=e.keyCode,r=e.charCode;if(us&&i==Gs){Gs=null;da(e)}else if(!(us&&(!e.which||e.which<10)||cs)||!Qi(t,e)){var n=String.fromCharCode(null==r?i:r);if(!Zi(t,e,n)){ns&&os>=9&&(t.display.inputHasSelection=null);Ci(t)}}}}function rr(e){if("nocursor"!=e.options.readOnly){if(!e.state.focused){ga(e,"focus",e);e.state.focused=!0;_a(e.display.wrapper,"CodeMirror-focused");if(!e.curOp&&e.display.selForContextMenu!=e.doc.sel){bi(e);ss&&setTimeout(Ao(bi,e,!0),0)}}Si(e);It(e)}}function nr(e){if(e.state.focused){ga(e,"blur",e);e.state.focused=!1;wa(e.display.wrapper,"CodeMirror-focused")}clearInterval(e.display.blinker);setTimeout(function(){e.state.focused||(e.display.shift=!1)},150)}function or(e,t){function i(){if(null!=n.input.selectionStart){var t=e.somethingSelected(),i=n.input.value=""+(t?n.input.value:"");n.prevInput=t?"":"";n.input.selectionStart=1;n.input.selectionEnd=i.length;n.selForContextMenu=e.doc.sel}}function r(){n.contextMenuPending=!1;n.inputDiv.style.position="relative";n.input.style.cssText=l;ns&&9>os&&n.scrollbars.setScrollTop(n.scroller.scrollTop=s);Si(e);if(null!=n.input.selectionStart){(!ns||ns&&9>os)&&i();var t=0,r=function(){n.selForContextMenu==e.doc.sel&&0==n.input.selectionStart?hi(e,Ks.selectAll)(e):t++<10?n.detectingSelectAll=setTimeout(r,500):bi(e)};n.detectingSelectAll=setTimeout(r,200)}}if(!fo(e,t,"contextmenu")){var n=e.display;if(!Mi(n,t)&&!sr(e,t)){var o=ki(e,t),s=n.scroller.scrollTop;if(o&&!us){var a=e.options.resetSelectionOnContextMenu;a&&-1==e.doc.sel.contains(o)&&hi(e,dt)(e.doc,J(o),Ta);var l=n.input.style.cssText;n.inputDiv.style.position="absolute";n.input.style.cssText="position: fixed; width: 30px; height: 30px; top: "+(t.clientY-5)+"px; left: "+(t.clientX-5)+"px; z-index: 1000; background: "+(ns?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";if(ss)var u=window.scrollY;Oi(e);ss&&window.scrollTo(null,u);bi(e);e.somethingSelected()||(n.input.value=n.prevInput=" ");n.contextMenuPending=!0;n.selForContextMenu=e.doc.sel;clearTimeout(n.detectingSelectAll);ns&&os>=9&&i();if(Ns){ha(t);var p=function(){ma(window,"mouseup",p);setTimeout(r,20)};Ea(window,"mouseup",p)}else setTimeout(r,50)}}}}function sr(e,t){return Eo(e,"gutterContextMenu")?Fi(e,t,"gutterContextMenu",!1,ga):!1}function ar(e,t){if(ys(e,t.from)<0)return e;if(ys(e,t.to)<=0)return Bs(t);var i=e.line+t.text.length-(t.to.line-t.from.line)-1,r=e.ch;e.line==t.to.line&&(r+=Bs(t).ch-t.to.ch);return Is(i,r)}function lr(e,t){for(var i=[],r=0;r<e.sel.ranges.length;r++){var n=e.sel.ranges[r];i.push(new Q(ar(n.anchor,t),ar(n.head,t)))}return Z(i,e.sel.primIndex)}function ur(e,t,i){return e.line==t.line?Is(i.line,e.ch-t.ch+i.ch):Is(i.line+(e.line-t.line),e.ch)}function pr(e,t,i){for(var r=[],n=Is(e.first,0),o=n,s=0;s<t.length;s++){var a=t[s],l=ur(a.from,n,o),u=ur(Bs(a),n,o);n=a.to;o=u;if("around"==i){var p=e.sel.ranges[s],c=ys(p.head,p.anchor)<0;r[s]=new Q(c?u:l,c?l:u)}else r[s]=new Q(l,l)}return new $(r,e.sel.primIndex)}function cr(e,t,i){var r={canceled:!1,from:t.from,to:t.to,text:t.text,origin:t.origin,cancel:function(){this.canceled=!0}};i&&(r.update=function(t,i,r,n){t&&(this.from=tt(e,t));i&&(this.to=tt(e,i));r&&(this.text=r);void 0!==n&&(this.origin=n)});ga(e,"beforeChange",e,r);e.cm&&ga(e.cm,"beforeChange",e.cm,r);return r.canceled?null:{from:r.from,to:r.to,text:r.text,origin:r.origin}}function dr(e,t,i){if(e.cm){if(!e.cm.curOp)return hi(e.cm,dr)(e,t,i);if(e.cm.state.suppressEdits)return}if(Eo(e,"beforeChange")||e.cm&&Eo(e.cm,"beforeChange")){t=cr(e,t,!0);if(!t)return}var r=Ts&&!i&&Yr(e,t.from,t.to);if(r)for(var n=r.length-1;n>=0;--n)fr(e,{from:r[n].from,to:r[n].to,text:n?[""]:t.text});else fr(e,t)}function fr(e,t){if(1!=t.text.length||""!=t.text[0]||0!=ys(t.from,t.to)){var i=lr(e,t);$n(e,t,i,e.cm?e.cm.curOp.id:0/0);mr(e,t,i,qr(e,t));var r=[];kn(e,function(e,i){if(!i&&-1==To(r,e.history)){so(e.history,t);r.push(e.history)}mr(e,t,null,qr(e,t))})}}function hr(e,t,i){if(!e.cm||!e.cm.state.suppressEdits){for(var r,n=e.history,o=e.sel,s="undo"==t?n.done:n.undone,a="undo"==t?n.undone:n.done,l=0;l<s.length;l++){r=s[l];if(i?r.ranges&&!r.equals(e.sel):!r.ranges)break}if(l!=s.length){n.lastOrigin=n.lastSelOrigin=null;for(;;){r=s.pop();if(!r.ranges)break;Jn(r,a);if(i&&!r.equals(e.sel)){dt(e,r,{clearRedo:!1});return}o=r}var u=[];Jn(o,a);a.push({changes:u,generation:n.generation});n.generation=r.generation||++n.maxGeneration;for(var p=Eo(e,"beforeChange")||e.cm&&Eo(e.cm,"beforeChange"),l=r.changes.length-1;l>=0;--l){var c=r.changes[l];c.origin=t;if(p&&!cr(e,c,!1)){s.length=0;return}u.push(Xn(e,c));var d=l?lr(e,c):No(s);mr(e,c,d,Xr(e,c));!l&&e.cm&&e.cm.scrollIntoView({from:c.from,to:Bs(c)});var f=[];kn(e,function(e,t){if(!t&&-1==To(f,e.history)){so(e.history,c);f.push(e.history)}mr(e,c,null,Xr(e,c))})}}}}function Er(e,t){if(0!=t){e.first+=t;e.sel=new $(Lo(e.sel.ranges,function(e){return new Q(Is(e.anchor.line+t,e.anchor.ch),Is(e.head.line+t,e.head.ch))}),e.sel.primIndex);if(e.cm){xi(e.cm,e.first,e.first-t,t);for(var i=e.cm.display,r=i.viewFrom;r<i.viewTo;r++)Ni(e.cm,r,"gutter")}}}function mr(e,t,i,r){if(e.cm&&!e.cm.curOp)return hi(e.cm,mr)(e,t,i,r);if(t.to.line<e.first)Er(e,t.text.length-1-(t.to.line-t.from.line));else if(!(t.from.line>e.lastLine())){if(t.from.line<e.first){var n=t.text.length-1-(e.first-t.from.line);Er(e,n);t={from:Is(e.first,0),to:Is(t.to.line+n,t.to.ch),text:[No(t.text)],origin:t.origin}}var o=e.lastLine();t.to.line>o&&(t={from:t.from,to:Is(o,Bn(e,o).text.length),text:[t.text[0]],origin:t.origin});t.removed=Un(e,t.from,t.to);i||(i=lr(e,t));e.cm?gr(e.cm,t,r):wn(e,t,r);ft(e,i,Ta)}}function gr(e,t,i){var r=e.doc,n=e.display,s=t.from,a=t.to,l=!1,u=s.line;if(!e.options.lineWrapping){u=Hn(on(Bn(r,s.line)));r.iter(u,a.line+1,function(e){if(e==n.maxLine){l=!0;return!0}})}r.sel.contains(t.from,t.to)>-1&&ho(e);wn(r,t,i,o(e));if(!e.options.lineWrapping){r.iter(u,s.line+t.text.length,function(e){var t=c(e);if(t>n.maxLineLength){n.maxLine=e;n.maxLineLength=t;n.maxLineChanged=!0;l=!1}});l&&(e.curOp.updateMaxLine=!0)}r.frontier=Math.min(r.frontier,s.line);yt(e,400);var p=t.text.length-(a.line-s.line)-1;t.full?xi(e):s.line!=a.line||1!=t.text.length||Dn(e.doc,t)?xi(e,s.line,a.line+1,p):Ni(e,s.line,"text");var d=Eo(e,"changes"),f=Eo(e,"change");if(f||d){var h={from:s,to:a,text:t.text,removed:t.removed,origin:t.origin};f&&po(e,"change",e,h);d&&(e.curOp.changeObjs||(e.curOp.changeObjs=[])).push(h)}e.display.selForContextMenu=null}function vr(e,t,i,r,n){r||(r=i);if(ys(r,i)<0){var o=r;r=i;i=o}"string"==typeof t&&(t=Ga(t));dr(e,{from:i,to:r,text:t,origin:n})}function xr(e,t){if(!fo(e,"scrollCursorIntoView")){var i=e.display,r=i.sizer.getBoundingClientRect(),n=null;t.top+r.top<0?n=!0:t.bottom+r.top>(window.innerHeight||document.documentElement.clientHeight)&&(n=!1);if(null!=n&&!fs){var o=bo("div","",null,"position: absolute; top: "+(t.top-i.viewOffset-Rt(e.display))+"px; height: "+(t.bottom-t.top+Pt(e)+i.barHeight)+"px; left: "+t.left+"px; width: 2px;");e.display.lineSpace.appendChild(o);o.scrollIntoView(n);e.display.lineSpace.removeChild(o)}}}function Nr(e,t,i,r){null==r&&(r=0);for(var n=0;5>n;n++){var o=!1,s=Qt(e,t),a=i&&i!=t?Qt(e,i):s,l=Lr(e,Math.min(s.left,a.left),Math.min(s.top,a.top)-r,Math.max(s.left,a.left),Math.max(s.bottom,a.bottom)+r),u=e.doc.scrollTop,p=e.doc.scrollLeft;if(null!=l.scrollTop){qi(e,l.scrollTop);Math.abs(e.doc.scrollTop-u)>1&&(o=!0)}if(null!=l.scrollLeft){zi(e,l.scrollLeft);Math.abs(e.doc.scrollLeft-p)>1&&(o=!0)}if(!o)break}return s}function Tr(e,t,i,r,n){var o=Lr(e,t,i,r,n);null!=o.scrollTop&&qi(e,o.scrollTop);null!=o.scrollLeft&&zi(e,o.scrollLeft)}function Lr(e,t,i,r,n){var o=e.display,s=ii(e.display);0>i&&(i=0);var a=e.curOp&&null!=e.curOp.scrollTop?e.curOp.scrollTop:o.scroller.scrollTop,l=wt(e),u={};n-i>l&&(n=i+l);var p=e.doc.height+bt(o),c=s>i,d=n>p-s;if(a>i)u.scrollTop=c?0:i;else if(n>a+l){var f=Math.min(i,(d?p:n)-l);f!=a&&(u.scrollTop=f)}var h=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:o.scroller.scrollLeft,E=Dt(e)-(e.options.fixedGutter?o.gutters.offsetWidth:0),m=r-t>E;m&&(r=t+E);10>t?u.scrollLeft=0:h>t?u.scrollLeft=Math.max(0,t-(m?0:10)):r>E+h-3&&(u.scrollLeft=r+(m?0:10)-E);return u}function Ir(e,t,i){(null!=t||null!=i)&&Ar(e);null!=t&&(e.curOp.scrollLeft=(null==e.curOp.scrollLeft?e.doc.scrollLeft:e.curOp.scrollLeft)+t);null!=i&&(e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+i)}function yr(e){Ar(e);var t=e.getCursor(),i=t,r=t;if(!e.options.lineWrapping){i=t.ch?Is(t.line,t.ch-1):t;r=Is(t.line,t.ch+1)}e.curOp.scrollToPos={from:i,to:r,margin:e.options.cursorScrollMargin,isCursor:!0}}function Ar(e){var t=e.curOp.scrollToPos;if(t){e.curOp.scrollToPos=null;var i=Zt(e,t.from),r=Zt(e,t.to),n=Lr(e,Math.min(i.left,r.left),Math.min(i.top,r.top)-t.margin,Math.max(i.right,r.right),Math.max(i.bottom,r.bottom)+t.margin);e.scrollTo(n.scrollLeft,n.scrollTop)}}function Sr(e,t,i,r){var n,o=e.doc;null==i&&(i="add");"smart"==i&&(o.mode.indent?n=Ct(e,t):i="prev");var s=e.options.tabSize,a=Bn(o,t),l=ya(a.text,null,s);a.stateAfter&&(a.stateAfter=null);var u,p=a.text.match(/^\s*/)[0];if(r||/\S/.test(a.text)){if("smart"==i){u=o.mode.indent(n,a.text.slice(p.length),a.text);if(u==Na||u>150){if(!r)return;i="prev"}}}else{u=0;i="not"}"prev"==i?u=t>o.first?ya(Bn(o,t-1).text,null,s):0:"add"==i?u=l+e.options.indentUnit:"subtract"==i?u=l-e.options.indentUnit:"number"==typeof i&&(u=l+i);u=Math.max(0,u);var c="",d=0;if(e.options.indentWithTabs)for(var f=Math.floor(u/s);f;--f){d+=s;c+=" "}u>d&&(c+=xo(u-d));if(c!=p)vr(o,c,Is(t,0),Is(t,p.length),"+input");else for(var f=0;f<o.sel.ranges.length;f++){var h=o.sel.ranges[f];if(h.head.line==t&&h.head.ch<p.length){var d=Is(t,p.length);lt(o,f,new Q(d,d));break}}a.stateAfter=null}function Cr(e,t,i,r){var n=t,o=t;"number"==typeof t?o=Bn(e,et(e,t)):n=Hn(t);if(null==n)return null;r(o,n)&&e.cm&&Ni(e.cm,n,i);return o}function Rr(e,t){for(var i=e.doc.sel.ranges,r=[],n=0;n<i.length;n++){for(var o=t(i[n]);r.length&&ys(o.from,No(r).to)<=0;){var s=r.pop();if(ys(s.from,o.from)<0){o.from=s.from;break}}r.push(o)}fi(e,function(){for(var t=r.length-1;t>=0;t--)vr(e.doc,"",r[t].from,r[t].to,"+delete");yr(e)})}function br(e,t,i,r,n){function o(){var t=a+i;if(t<e.first||t>=e.first+e.size)return c=!1;a=t;return p=Bn(e,t)}function s(e){var t=(n?Jo:es)(p,l,i,!0);if(null==t){if(e||!o())return c=!1;l=n?(0>i?zo:qo)(p):0>i?p.text.length:0}else l=t;return!0}var a=t.line,l=t.ch,u=i,p=Bn(e,a),c=!0;if("char"==r)s();else if("column"==r)s(!0);else if("word"==r||"group"==r)for(var d=null,f="group"==r,h=e.cm&&e.cm.getHelper(t,"wordChars"),E=!0;!(0>i)||s(!E);E=!1){var m=p.text.charAt(l)||"\n",g=So(m,h)?"w":f&&"\n"==m?"n":!f||/\s/.test(m)?null:"p";!f||E||g||(g="s");if(d&&d!=g){if(0>i){i=1;s()}break}g&&(d=g);if(i>0&&!s(!E))break}var v=gt(e,Is(a,l),u,!0);c||(v.hitSide=!0);return v}function Or(e,t,i,r){var n,o=e.doc,s=t.left;if("page"==r){var a=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);n=t.top+i*(a-(0>i?1.5:.5)*ii(e.display))}else"line"==r&&(n=i>0?t.bottom+3:t.top-3);for(;;){var l=ei(e,s,n);if(!l.outside)break;if(0>i?0>=n:n>=o.height){l.hitSide=!0;break}n+=5*i}return l}function Pr(t,i,r,n){e.defaults[t]=i;r&&(Vs[t]=n?function(e,t,i){i!=Fs&&r(e,t,i)}:r)}function Dr(e){for(var t,i,r,n,o=e.split(/-(?!$)/),e=o[o.length-1],s=0;s<o.length-1;s++){var a=o[s];if(/^(cmd|meta|m)$/i.test(a))n=!0;else if(/^a(lt)?$/i.test(a))t=!0;else if(/^(c|ctrl|control)$/i.test(a))i=!0;else{if(!/^s(hift)$/i.test(a))throw new Error("Unrecognized modifier name: "+a);r=!0}}t&&(e="Alt-"+e);i&&(e="Ctrl-"+e);n&&(e="Cmd-"+e);r&&(e="Shift-"+e);return e}function wr(e){return"string"==typeof e?$s[e]:e}function _r(e,t,i,r,n){if(r&&r.shared)return Mr(e,t,i,r,n);if(e.cm&&!e.cm.curOp)return hi(e.cm,_r)(e,t,i,r,n);var o=new ta(e,n),s=ys(t,i);r&&yo(r,o,!1);if(s>0||0==s&&o.clearWhenEmpty!==!1)return o;if(o.replacedWith){o.collapsed=!0;o.widgetNode=bo("span",[o.replacedWith],"CodeMirror-widget");r.handleMouseEvents||o.widgetNode.setAttribute("cm-ignore-events","true");r.insertLeft&&(o.widgetNode.insertLeft=!0)}if(o.collapsed){if(nn(e,t.line,t,i,o)||t.line!=i.line&&nn(e,i.line,t,i,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");Ls=!0}o.addToHistory&&$n(e,{from:t,to:i,origin:"markText"},e.sel,0/0);var a,l=t.line,u=e.cm;e.iter(l,i.line+1,function(e){u&&o.collapsed&&!u.options.lineWrapping&&on(e)==u.display.maxLine&&(a=!0);o.collapsed&&l!=t.line&&Fn(e,0);Hr(e,new Ur(o,l==t.line?t.ch:null,l==i.line?i.ch:null));++l});o.collapsed&&e.iter(t.line,i.line+1,function(t){un(e,t)&&Fn(t,0)});o.clearOnEnter&&Ea(o,"beforeCursorEnter",function(){o.clear()});if(o.readOnly){Ts=!0;(e.history.done.length||e.history.undone.length)&&e.clearHistory()}if(o.collapsed){o.id=++ia;o.atomic=!0}if(u){a&&(u.curOp.updateMaxLine=!0);if(o.collapsed)xi(u,t.line,i.line+1);else if(o.className||o.title||o.startStyle||o.endStyle||o.css)for(var p=t.line;p<=i.line;p++)Ni(u,p,"text");o.atomic&&Et(u.doc);po(u,"markerAdded",u,o)}return o}function Mr(e,t,i,r,n){r=yo(r);r.shared=!1;var o=[_r(e,t,i,r,n)],s=o[0],a=r.widgetNode;kn(e,function(e){a&&(r.widgetNode=a.cloneNode(!0));o.push(_r(e,tt(e,t),tt(e,i),r,n));for(var l=0;l<e.linked.length;++l)if(e.linked[l].isParent)return;s=No(o)});return new ra(o,s)}function kr(e){return e.findMarks(Is(e.first,0),e.clipPos(Is(e.lastLine())),function(e){return e.parent})}function Gr(e,t){for(var i=0;i<t.length;i++){var r=t[i],n=r.find(),o=e.clipPos(n.from),s=e.clipPos(n.to);if(ys(o,s)){var a=_r(e,o,s,r.primary,r.primary.type);r.markers.push(a);a.parent=r}}}function Br(e){for(var t=0;t<e.length;t++){var i=e[t],r=[i.primary.doc];kn(i.primary.doc,function(e){r.push(e)});for(var n=0;n<i.markers.length;n++){var o=i.markers[n];if(-1==To(r,o.doc)){o.parent=null;i.markers.splice(n--,1)}}}}function Ur(e,t,i){this.marker=e;this.from=t;this.to=i}function Vr(e,t){if(e)for(var i=0;i<e.length;++i){var r=e[i];if(r.marker==t)return r}}function Fr(e,t){for(var i,r=0;r<e.length;++r)e[r]!=t&&(i||(i=[])).push(e[r]);return i}function Hr(e,t){e.markedSpans=e.markedSpans?e.markedSpans.concat([t]):[t];t.marker.attachLine(e)}function jr(e,t,i){if(e)for(var r,n=0;n<e.length;++n){var o=e[n],s=o.marker,a=null==o.from||(s.inclusiveLeft?o.from<=t:o.from<t);if(a||o.from==t&&"bookmark"==s.type&&(!i||!o.marker.insertLeft)){var l=null==o.to||(s.inclusiveRight?o.to>=t:o.to>t);(r||(r=[])).push(new Ur(s,o.from,l?null:o.to))}}return r}function Wr(e,t,i){if(e)for(var r,n=0;n<e.length;++n){var o=e[n],s=o.marker,a=null==o.to||(s.inclusiveRight?o.to>=t:o.to>t);if(a||o.from==t&&"bookmark"==s.type&&(!i||o.marker.insertLeft)){var l=null==o.from||(s.inclusiveLeft?o.from<=t:o.from<t);(r||(r=[])).push(new Ur(s,l?null:o.from-t,null==o.to?null:o.to-t))}}return r}function qr(e,t){if(t.full)return null;var i=rt(e,t.from.line)&&Bn(e,t.from.line).markedSpans,r=rt(e,t.to.line)&&Bn(e,t.to.line).markedSpans;if(!i&&!r)return null;var n=t.from.ch,o=t.to.ch,s=0==ys(t.from,t.to),a=jr(i,n,s),l=Wr(r,o,s),u=1==t.text.length,p=No(t.text).length+(u?n:0);if(a)for(var c=0;c<a.length;++c){var d=a[c];if(null==d.to){var f=Vr(l,d.marker);f?u&&(d.to=null==f.to?null:f.to+p):d.to=n}}if(l)for(var c=0;c<l.length;++c){var d=l[c];null!=d.to&&(d.to+=p);if(null==d.from){var f=Vr(a,d.marker);if(!f){d.from=p;u&&(a||(a=[])).push(d)}}else{d.from+=p;u&&(a||(a=[])).push(d)}}a&&(a=zr(a));l&&l!=a&&(l=zr(l));var h=[a];if(!u){var E,m=t.text.length-2;if(m>0&&a)for(var c=0;c<a.length;++c)null==a[c].to&&(E||(E=[])).push(new Ur(a[c].marker,null,null));for(var c=0;m>c;++c)h.push(E);h.push(l)}return h}function zr(e){for(var t=0;t<e.length;++t){var i=e[t];null!=i.from&&i.from==i.to&&i.marker.clearWhenEmpty!==!1&&e.splice(t--,1)}return e.length?e:null}function Xr(e,t){var i=io(e,t),r=qr(e,t);
if(!i)return r;if(!r)return i;for(var n=0;n<i.length;++n){var o=i[n],s=r[n];if(o&&s)e:for(var a=0;a<s.length;++a){for(var l=s[a],u=0;u<o.length;++u)if(o[u].marker==l.marker)continue e;o.push(l)}else s&&(i[n]=s)}return i}function Yr(e,t,i){var r=null;e.iter(t.line,i.line+1,function(e){if(e.markedSpans)for(var t=0;t<e.markedSpans.length;++t){var i=e.markedSpans[t].marker;!i.readOnly||r&&-1!=To(r,i)||(r||(r=[])).push(i)}});if(!r)return null;for(var n=[{from:t,to:i}],o=0;o<r.length;++o)for(var s=r[o],a=s.find(0),l=0;l<n.length;++l){var u=n[l];if(!(ys(u.to,a.from)<0||ys(u.from,a.to)>0)){var p=[l,1],c=ys(u.from,a.from),d=ys(u.to,a.to);(0>c||!s.inclusiveLeft&&!c)&&p.push({from:u.from,to:a.from});(d>0||!s.inclusiveRight&&!d)&&p.push({from:a.to,to:u.to});n.splice.apply(n,p);l+=p.length-1}}return n}function Kr(e){var t=e.markedSpans;if(t){for(var i=0;i<t.length;++i)t[i].marker.detachLine(e);e.markedSpans=null}}function $r(e,t){if(t){for(var i=0;i<t.length;++i)t[i].marker.attachLine(e);e.markedSpans=t}}function Qr(e){return e.inclusiveLeft?-1:0}function Zr(e){return e.inclusiveRight?1:0}function Jr(e,t){var i=e.lines.length-t.lines.length;if(0!=i)return i;var r=e.find(),n=t.find(),o=ys(r.from,n.from)||Qr(e)-Qr(t);if(o)return-o;var s=ys(r.to,n.to)||Zr(e)-Zr(t);return s?s:t.id-e.id}function en(e,t){var i,r=Ls&&e.markedSpans;if(r)for(var n,o=0;o<r.length;++o){n=r[o];n.marker.collapsed&&null==(t?n.from:n.to)&&(!i||Jr(i,n.marker)<0)&&(i=n.marker)}return i}function tn(e){return en(e,!0)}function rn(e){return en(e,!1)}function nn(e,t,i,r,n){var o=Bn(e,t),s=Ls&&o.markedSpans;if(s)for(var a=0;a<s.length;++a){var l=s[a];if(l.marker.collapsed){var u=l.marker.find(0),p=ys(u.from,i)||Qr(l.marker)-Qr(n),c=ys(u.to,r)||Zr(l.marker)-Zr(n);if(!(p>=0&&0>=c||0>=p&&c>=0)&&(0>=p&&(ys(u.to,i)>0||l.marker.inclusiveRight&&n.inclusiveLeft)||p>=0&&(ys(u.from,r)<0||l.marker.inclusiveLeft&&n.inclusiveRight)))return!0}}}function on(e){for(var t;t=tn(e);)e=t.find(-1,!0).line;return e}function sn(e){for(var t,i;t=rn(e);){e=t.find(1,!0).line;(i||(i=[])).push(e)}return i}function an(e,t){var i=Bn(e,t),r=on(i);return i==r?t:Hn(r)}function ln(e,t){if(t>e.lastLine())return t;var i,r=Bn(e,t);if(!un(e,r))return t;for(;i=rn(r);)r=i.find(1,!0).line;return Hn(r)+1}function un(e,t){var i=Ls&&t.markedSpans;if(i)for(var r,n=0;n<i.length;++n){r=i[n];if(r.marker.collapsed){if(null==r.from)return!0;if(!r.marker.widgetNode&&0==r.from&&r.marker.inclusiveLeft&&pn(e,t,r))return!0}}}function pn(e,t,i){if(null==i.to){var r=i.marker.find(1,!0);return pn(e,r.line,Vr(r.line.markedSpans,i.marker))}if(i.marker.inclusiveRight&&i.to==t.text.length)return!0;for(var n,o=0;o<t.markedSpans.length;++o){n=t.markedSpans[o];if(n.marker.collapsed&&!n.marker.widgetNode&&n.from==i.to&&(null==n.to||n.to!=i.from)&&(n.marker.inclusiveLeft||i.marker.inclusiveRight)&&pn(e,t,n))return!0}}function cn(e,t,i){Wn(t)<(e.curOp&&e.curOp.scrollTop||e.doc.scrollTop)&&Ir(e,null,i)}function dn(e){if(null!=e.height)return e.height;if(!Do(document.body,e.node)){var t="position: relative;";e.coverGutter&&(t+="margin-left: -"+e.cm.display.gutters.offsetWidth+"px;");e.noHScroll&&(t+="width: "+e.cm.display.wrapper.clientWidth+"px;");Po(e.cm.display.measure,bo("div",[e.node],null,t))}return e.height=e.node.offsetHeight}function fn(e,t,i,r){var n=new na(e,i,r);n.noHScroll&&(e.display.alignWidgets=!0);Cr(e.doc,t,"widget",function(t){var i=t.widgets||(t.widgets=[]);null==n.insertAt?i.push(n):i.splice(Math.min(i.length-1,Math.max(0,n.insertAt)),0,n);n.line=t;if(!un(e.doc,t)){var r=Wn(t)<e.doc.scrollTop;Fn(t,t.height+dn(n));r&&Ir(e,null,n.height);e.curOp.forceUpdate=!0}return!0});return n}function hn(e,t,i,r){e.text=t;e.stateAfter&&(e.stateAfter=null);e.styles&&(e.styles=null);null!=e.order&&(e.order=null);Kr(e);$r(e,i);var n=r?r(e):1;n!=e.height&&Fn(e,n)}function En(e){e.parent=null;Kr(e)}function mn(e,t){if(e)for(;;){var i=e.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!i)break;e=e.slice(0,i.index)+e.slice(i.index+i[0].length);var r=i[1]?"bgClass":"textClass";null==t[r]?t[r]=i[2]:new RegExp("(?:^|s)"+i[2]+"(?:$|s)").test(t[r])||(t[r]+=" "+i[2])}return e}function gn(t,i){if(t.blankLine)return t.blankLine(i);if(t.innerMode){var r=e.innerMode(t,i);return r.mode.blankLine?r.mode.blankLine(r.state):void 0}}function vn(t,i,r,n){for(var o=0;10>o;o++){n&&(n[0]=e.innerMode(t,r).mode);var s=t.token(i,r);if(i.pos>i.start)return s}throw new Error("Mode "+t.name+" failed to advance stream.")}function xn(e,t,i,r){function n(e){return{start:c.start,end:c.pos,string:c.current(),type:o||null,state:e?Xs(s.mode,p):p}}var o,s=e.doc,a=s.mode;t=tt(s,t);var l,u=Bn(s,t.line),p=Ct(e,t.line,i),c=new ea(u.text,e.options.tabSize);r&&(l=[]);for(;(r||c.pos<t.ch)&&!c.eol();){c.start=c.pos;o=vn(a,c,p);r&&l.push(n(!0))}return r?l:n()}function Nn(e,t,i,r,n,o,s){var a=i.flattenSpans;null==a&&(a=e.options.flattenSpans);var l,u=0,p=null,c=new ea(t,e.options.tabSize),d=e.options.addModeClass&&[null];""==t&&mn(gn(i,r),o);for(;!c.eol();){if(c.pos>e.options.maxHighlightLength){a=!1;s&&In(e,t,r,c.pos);c.pos=t.length;l=null}else l=mn(vn(i,c,r,d),o);if(d){var f=d[0].name;f&&(l="m-"+(l?f+" "+l:f))}if(!a||p!=l){for(;u<c.start;){u=Math.min(c.start,u+5e4);n(u,p)}p=l}c.start=c.pos}for(;u<c.pos;){var h=Math.min(c.pos,u+5e4);n(h,p);u=h}}function Tn(e,t,i,r){var n=[e.state.modeGen],o={};Nn(e,t.text,e.doc.mode,i,function(e,t){n.push(e,t)},o,r);for(var s=0;s<e.state.overlays.length;++s){var a=e.state.overlays[s],l=1,u=0;Nn(e,t.text,a.mode,!0,function(e,t){for(var i=l;e>u;){var r=n[l];r>e&&n.splice(l,1,e,n[l+1],r);l+=2;u=Math.min(e,r)}if(t)if(a.opaque){n.splice(i,l-i,e,"cm-overlay "+t);l=i+2}else for(;l>i;i+=2){var o=n[i+1];n[i+1]=(o?o+" ":"")+"cm-overlay "+t}},o)}return{styles:n,classes:o.bgClass||o.textClass?o:null}}function Ln(e,t,i){if(!t.styles||t.styles[0]!=e.state.modeGen){var r=Tn(e,t,t.stateAfter=Ct(e,Hn(t)));t.styles=r.styles;r.classes?t.styleClasses=r.classes:t.styleClasses&&(t.styleClasses=null);i===e.doc.frontier&&e.doc.frontier++}return t.styles}function In(e,t,i,r){var n=e.doc.mode,o=new ea(t,e.options.tabSize);o.start=o.pos=r||0;""==t&&gn(n,i);for(;!o.eol()&&o.pos<=e.options.maxHighlightLength;){vn(n,o,i);o.start=o.pos}}function yn(e,t){if(!e||/^\s*$/.test(e))return null;var i=t.addModeClass?aa:sa;return i[e]||(i[e]=e.replace(/\S+/g,"cm-$&"))}function An(e,t){var i=bo("span",null,null,ss?"padding-right: .1px":null),r={pre:bo("pre",[i]),content:i,col:0,pos:0,cm:e};t.measure={};for(var n=0;n<=(t.rest?t.rest.length:0);n++){var o,s=n?t.rest[n-1]:t.line;r.pos=0;r.addToken=Cn;(ns||ss)&&e.getOption("lineWrapping")&&(r.addToken=Rn(r.addToken));Vo(e.display.measure)&&(o=qn(s))&&(r.addToken=bn(r.addToken,o));r.map=[];var a=t!=e.display.externalMeasured&&Hn(s);Pn(s,r,Ln(e,s,a));if(s.styleClasses){s.styleClasses.bgClass&&(r.bgClass=Mo(s.styleClasses.bgClass,r.bgClass||""));s.styleClasses.textClass&&(r.textClass=Mo(s.styleClasses.textClass,r.textClass||""))}0==r.map.length&&r.map.push(0,0,r.content.appendChild(Uo(e.display.measure)));if(0==n){t.measure.map=r.map;t.measure.cache={}}else{(t.measure.maps||(t.measure.maps=[])).push(r.map);(t.measure.caches||(t.measure.caches=[])).push({})}}ss&&/\bcm-tab\b/.test(r.content.lastChild.className)&&(r.content.className="cm-tab-wrap-hack");ga(e,"renderLine",e,t.line,r.pre);r.pre.className&&(r.textClass=Mo(r.pre.className,r.textClass||""));return r}function Sn(e){var t=bo("span","•","cm-invalidchar");t.title="\\u"+e.charCodeAt(0).toString(16);return t}function Cn(e,t,i,r,n,o,s){if(t){var a=e.cm.options.specialChars,l=!1;if(a.test(t))for(var u=document.createDocumentFragment(),p=0;;){a.lastIndex=p;var c=a.exec(t),d=c?c.index-p:t.length-p;if(d){var f=document.createTextNode(t.slice(p,p+d));u.appendChild(ns&&9>os?bo("span",[f]):f);e.map.push(e.pos,e.pos+d,f);e.col+=d;e.pos+=d}if(!c)break;p+=d+1;if(" "==c[0]){var h=e.cm.options.tabSize,E=h-e.col%h,f=u.appendChild(bo("span",xo(E),"cm-tab"));e.col+=E}else{var f=e.cm.options.specialCharPlaceholder(c[0]);u.appendChild(ns&&9>os?bo("span",[f]):f);e.col+=1}e.map.push(e.pos,e.pos+1,f);e.pos++}else{e.col+=t.length;var u=document.createTextNode(t);e.map.push(e.pos,e.pos+t.length,u);ns&&9>os&&(l=!0);e.pos+=t.length}if(i||r||n||l||s){var m=i||"";r&&(m+=r);n&&(m+=n);var g=bo("span",[u],m,s);o&&(g.title=o);return e.content.appendChild(g)}e.content.appendChild(u)}}function Rn(e){function t(e){for(var t=" ",i=0;i<e.length-2;++i)t+=i%2?" ":" ";t+=" ";return t}return function(i,r,n,o,s,a){e(i,r.replace(/ {3,}/g,t),n,o,s,a)}}function bn(e,t){return function(i,r,n,o,s,a){n=n?n+" cm-force-border":"cm-force-border";for(var l=i.pos,u=l+r.length;;){for(var p=0;p<t.length;p++){var c=t[p];if(c.to>l&&c.from<=l)break}if(c.to>=u)return e(i,r,n,o,s,a);e(i,r.slice(0,c.to-l),n,o,null,a);o=null;r=r.slice(c.to-l);l=c.to}}}function On(e,t,i,r){var n=!r&&i.widgetNode;if(n){e.map.push(e.pos,e.pos+t,n);e.content.appendChild(n)}e.pos+=t}function Pn(e,t,i){var r=e.markedSpans,n=e.text,o=0;if(r)for(var s,a,l,u,p,c,d,f=n.length,h=0,E=1,m="",g=0;;){if(g==h){l=u=p=c=a="";d=null;g=1/0;for(var v=[],x=0;x<r.length;++x){var N=r[x],T=N.marker;if(N.from<=h&&(null==N.to||N.to>h)){if(null!=N.to&&g>N.to){g=N.to;u=""}T.className&&(l+=" "+T.className);T.css&&(a=T.css);T.startStyle&&N.from==h&&(p+=" "+T.startStyle);T.endStyle&&N.to==g&&(u+=" "+T.endStyle);T.title&&!c&&(c=T.title);T.collapsed&&(!d||Jr(d.marker,T)<0)&&(d=N)}else N.from>h&&g>N.from&&(g=N.from);"bookmark"==T.type&&N.from==h&&T.widgetNode&&v.push(T)}if(d&&(d.from||0)==h){On(t,(null==d.to?f+1:d.to)-h,d.marker,null==d.from);if(null==d.to)return}if(!d&&v.length)for(var x=0;x<v.length;++x)On(t,0,v[x])}if(h>=f)break;for(var L=Math.min(f,g);;){if(m){var I=h+m.length;if(!d){var y=I>L?m.slice(0,L-h):m;t.addToken(t,y,s?s+l:l,p,h+y.length==g?u:"",c,a)}if(I>=L){m=m.slice(L-h);h=L;break}h=I;p=""}m=n.slice(o,o=i[E++]);s=yn(i[E++],t.cm.options)}}else for(var E=1;E<i.length;E+=2)t.addToken(t,n.slice(o,o=i[E]),yn(i[E+1],t.cm.options))}function Dn(e,t){return 0==t.from.ch&&0==t.to.ch&&""==No(t.text)&&(!e.cm||e.cm.options.wholeLineUpdateBefore)}function wn(e,t,i,r){function n(e){return i?i[e]:null}function o(e,i,n){hn(e,i,n,r);po(e,"change",e,t)}function s(e,t){for(var i=e,o=[];t>i;++i)o.push(new oa(u[i],n(i),r));return o}var a=t.from,l=t.to,u=t.text,p=Bn(e,a.line),c=Bn(e,l.line),d=No(u),f=n(u.length-1),h=l.line-a.line;if(t.full){e.insert(0,s(0,u.length));e.remove(u.length,e.size-u.length)}else if(Dn(e,t)){var E=s(0,u.length-1);o(c,c.text,f);h&&e.remove(a.line,h);E.length&&e.insert(a.line,E)}else if(p==c)if(1==u.length)o(p,p.text.slice(0,a.ch)+d+p.text.slice(l.ch),f);else{var E=s(1,u.length-1);E.push(new oa(d+p.text.slice(l.ch),f,r));o(p,p.text.slice(0,a.ch)+u[0],n(0));e.insert(a.line+1,E)}else if(1==u.length){o(p,p.text.slice(0,a.ch)+u[0]+c.text.slice(l.ch),n(0));e.remove(a.line+1,h)}else{o(p,p.text.slice(0,a.ch)+u[0],n(0));o(c,d+c.text.slice(l.ch),f);var E=s(1,u.length-1);h>1&&e.remove(a.line+1,h-1);e.insert(a.line+1,E)}po(e,"change",e,t)}function _n(e){this.lines=e;this.parent=null;for(var t=0,i=0;t<e.length;++t){e[t].parent=this;i+=e[t].height}this.height=i}function Mn(e){this.children=e;for(var t=0,i=0,r=0;r<e.length;++r){var n=e[r];t+=n.chunkSize();i+=n.height;n.parent=this}this.size=t;this.height=i;this.parent=null}function kn(e,t,i){function r(e,n,o){if(e.linked)for(var s=0;s<e.linked.length;++s){var a=e.linked[s];if(a.doc!=n){var l=o&&a.sharedHist;if(!i||l){t(a.doc,l);r(a.doc,e,l)}}}}r(e,null,!0)}function Gn(e,t){if(t.cm)throw new Error("This document is already in use.");e.doc=t;t.cm=e;s(e);i(e);e.options.lineWrapping||d(e);e.options.mode=t.modeOption;xi(e)}function Bn(e,t){t-=e.first;if(0>t||t>=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var i=e;!i.lines;)for(var r=0;;++r){var n=i.children[r],o=n.chunkSize();if(o>t){i=n;break}t-=o}return i.lines[t]}function Un(e,t,i){var r=[],n=t.line;e.iter(t.line,i.line+1,function(e){var o=e.text;n==i.line&&(o=o.slice(0,i.ch));n==t.line&&(o=o.slice(t.ch));r.push(o);++n});return r}function Vn(e,t,i){var r=[];e.iter(t,i,function(e){r.push(e.text)});return r}function Fn(e,t){var i=t-e.height;if(i)for(var r=e;r;r=r.parent)r.height+=i}function Hn(e){if(null==e.parent)return null;for(var t=e.parent,i=To(t.lines,e),r=t.parent;r;t=r,r=r.parent)for(var n=0;r.children[n]!=t;++n)i+=r.children[n].chunkSize();return i+t.first}function jn(e,t){var i=e.first;e:do{for(var r=0;r<e.children.length;++r){var n=e.children[r],o=n.height;if(o>t){e=n;continue e}t-=o;i+=n.chunkSize()}return i}while(!e.lines);for(var r=0;r<e.lines.length;++r){var s=e.lines[r],a=s.height;if(a>t)break;t-=a}return i+r}function Wn(e){e=on(e);for(var t=0,i=e.parent,r=0;r<i.lines.length;++r){var n=i.lines[r];if(n==e)break;t+=n.height}for(var o=i.parent;o;i=o,o=i.parent)for(var r=0;r<o.children.length;++r){var s=o.children[r];if(s==i)break;t+=s.height}return t}function qn(e){var t=e.order;null==t&&(t=e.order=ja(e.text));return t}function zn(e){this.done=[];this.undone=[];this.undoDepth=1/0;this.lastModTime=this.lastSelTime=0;this.lastOp=this.lastSelOp=null;this.lastOrigin=this.lastSelOrigin=null;this.generation=this.maxGeneration=e||1}function Xn(e,t){var i={from:X(t.from),to:Bs(t),text:Un(e,t.from,t.to)};eo(e,i,t.from.line,t.to.line+1);kn(e,function(e){eo(e,i,t.from.line,t.to.line+1)},!0);return i}function Yn(e){for(;e.length;){var t=No(e);if(!t.ranges)break;e.pop()}}function Kn(e,t){if(t){Yn(e.done);return No(e.done)}if(e.done.length&&!No(e.done).ranges)return No(e.done);if(e.done.length>1&&!e.done[e.done.length-2].ranges){e.done.pop();return No(e.done)}}function $n(e,t,i,r){var n=e.history;n.undone.length=0;var o,s=+new Date;if((n.lastOp==r||n.lastOrigin==t.origin&&t.origin&&("+"==t.origin.charAt(0)&&e.cm&&n.lastModTime>s-e.cm.options.historyEventDelay||"*"==t.origin.charAt(0)))&&(o=Kn(n,n.lastOp==r))){var a=No(o.changes);0==ys(t.from,t.to)&&0==ys(t.from,a.to)?a.to=Bs(t):o.changes.push(Xn(e,t))}else{var l=No(n.done);l&&l.ranges||Jn(e.sel,n.done);o={changes:[Xn(e,t)],generation:n.generation};n.done.push(o);for(;n.done.length>n.undoDepth;){n.done.shift();n.done[0].ranges||n.done.shift()}}n.done.push(i);n.generation=++n.maxGeneration;n.lastModTime=n.lastSelTime=s;n.lastOp=n.lastSelOp=r;n.lastOrigin=n.lastSelOrigin=t.origin;a||ga(e,"historyAdded")}function Qn(e,t,i,r){var n=t.charAt(0);return"*"==n||"+"==n&&i.ranges.length==r.ranges.length&&i.somethingSelected()==r.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}function Zn(e,t,i,r){var n=e.history,o=r&&r.origin;i==n.lastSelOp||o&&n.lastSelOrigin==o&&(n.lastModTime==n.lastSelTime&&n.lastOrigin==o||Qn(e,o,No(n.done),t))?n.done[n.done.length-1]=t:Jn(t,n.done);n.lastSelTime=+new Date;n.lastSelOrigin=o;n.lastSelOp=i;r&&r.clearRedo!==!1&&Yn(n.undone)}function Jn(e,t){var i=No(t);i&&i.ranges&&i.equals(e)||t.push(e)}function eo(e,t,i,r){var n=t["spans_"+e.id],o=0;e.iter(Math.max(e.first,i),Math.min(e.first+e.size,r),function(i){i.markedSpans&&((n||(n=t["spans_"+e.id]={}))[o]=i.markedSpans);++o})}function to(e){if(!e)return null;for(var t,i=0;i<e.length;++i)e[i].marker.explicitlyCleared?t||(t=e.slice(0,i)):t&&t.push(e[i]);return t?t.length?t:null:e}function io(e,t){var i=t["spans_"+e.id];if(!i)return null;for(var r=0,n=[];r<t.text.length;++r)n.push(to(i[r]));return n}function ro(e,t,i){for(var r=0,n=[];r<e.length;++r){var o=e[r];if(o.ranges)n.push(i?$.prototype.deepCopy.call(o):o);else{var s=o.changes,a=[];n.push({changes:a});for(var l=0;l<s.length;++l){var u,p=s[l];a.push({from:p.from,to:p.to,text:p.text});if(t)for(var c in p)if((u=c.match(/^spans_(\d+)$/))&&To(t,Number(u[1]))>-1){No(a)[c]=p[c];delete p[c]}}}}return n}function no(e,t,i,r){if(i<e.line)e.line+=r;else if(t<e.line){e.line=t;e.ch=0}}function oo(e,t,i,r){for(var n=0;n<e.length;++n){var o=e[n],s=!0;if(o.ranges){if(!o.copied){o=e[n]=o.deepCopy();o.copied=!0}for(var a=0;a<o.ranges.length;a++){no(o.ranges[a].anchor,t,i,r);no(o.ranges[a].head,t,i,r)}}else{for(var a=0;a<o.changes.length;++a){var l=o.changes[a];if(i<l.from.line){l.from=Is(l.from.line+r,l.from.ch);l.to=Is(l.to.line+r,l.to.ch)}else if(t<=l.to.line){s=!1;break}}if(!s){e.splice(0,n+1);n=0}}}}function so(e,t){var i=t.from.line,r=t.to.line,n=t.text.length-(r-i)-1;oo(e.done,i,r,n);oo(e.undone,i,r,n)}function ao(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function lo(e){return e.target||e.srcElement}function uo(e){var t=e.which;null==t&&(1&e.button?t=1:2&e.button?t=3:4&e.button&&(t=2));ms&&e.ctrlKey&&1==t&&(t=3);return t}function po(e,t){function i(e){return function(){e.apply(null,o)}}var r=e._handlers&&e._handlers[t];if(r){var n,o=Array.prototype.slice.call(arguments,2);if(bs)n=bs.delayedCallbacks;else if(va)n=va;else{n=va=[];setTimeout(co,0)}for(var s=0;s<r.length;++s)n.push(i(r[s]))}}function co(){var e=va;va=null;for(var t=0;t<e.length;++t)e[t]()}function fo(e,t,i){"string"==typeof t&&(t={type:t,preventDefault:function(){this.defaultPrevented=!0}});ga(e,i||t.type,e,t);return ao(t)||t.codemirrorIgnore}function ho(e){var t=e._handlers&&e._handlers.cursorActivity;if(t)for(var i=e.curOp.cursorActivityHandlers||(e.curOp.cursorActivityHandlers=[]),r=0;r<t.length;++r)-1==To(i,t[r])&&i.push(t[r])}function Eo(e,t){var i=e._handlers&&e._handlers[t];return i&&i.length>0}function mo(e){e.prototype.on=function(e,t){Ea(this,e,t)};e.prototype.off=function(e,t){ma(this,e,t)}}function go(){this.id=null}function vo(e,t,i){for(var r=0,n=0;;){var o=e.indexOf(" ",r);-1==o&&(o=e.length);var s=o-r;if(o==e.length||n+s>=t)return r+Math.min(s,t-n);n+=o-r;n+=i-n%i;r=o+1;if(n>=t)return r}}function xo(e){for(;Aa.length<=e;)Aa.push(No(Aa)+" ");return Aa[e]}function No(e){return e[e.length-1]}function To(e,t){for(var i=0;i<e.length;++i)if(e[i]==t)return i;return-1}function Lo(e,t){for(var i=[],r=0;r<e.length;r++)i[r]=t(e[r],r);return i}function Io(e,t){var i;if(Object.create)i=Object.create(e);else{var r=function(){};r.prototype=e;i=new r}t&&yo(t,i);return i}function yo(e,t,i){t||(t={});for(var r in e)!e.hasOwnProperty(r)||i===!1&&t.hasOwnProperty(r)||(t[r]=e[r]);return t}function Ao(e){var t=Array.prototype.slice.call(arguments,1);return function(){return e.apply(null,t)}}function So(e,t){return t?t.source.indexOf("\\w")>-1&&ba(e)?!0:t.test(e):ba(e)}function Co(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}function Ro(e){return e.charCodeAt(0)>=768&&Oa.test(e)}function bo(e,t,i,r){var n=document.createElement(e);i&&(n.className=i);r&&(n.style.cssText=r);if("string"==typeof t)n.appendChild(document.createTextNode(t));else if(t)for(var o=0;o<t.length;++o)n.appendChild(t[o]);return n}function Oo(e){for(var t=e.childNodes.length;t>0;--t)e.removeChild(e.firstChild);return e}function Po(e,t){return Oo(e).appendChild(t)}function Do(e,t){if(e.contains)return e.contains(t);for(;t=t.parentNode;)if(t==e)return!0}function wo(){return document.activeElement}function _o(e){return new RegExp("(^|\\s)"+e+"(?:$|\\s)\\s*")}function Mo(e,t){for(var i=e.split(" "),r=0;r<i.length;r++)i[r]&&!_o(i[r]).test(t)&&(t+=" "+i[r]);return t}function ko(e){if(document.body.getElementsByClassName)for(var t=document.body.getElementsByClassName("CodeMirror"),i=0;i<t.length;i++){var r=t[i].CodeMirror;r&&e(r)}}function Go(){if(!Ma){Bo();Ma=!0}}function Bo(){var e;Ea(window,"resize",function(){null==e&&(e=setTimeout(function(){e=null;ko(_i)},100))});Ea(window,"blur",function(){ko(nr)})}function Uo(e){if(null==Pa){var t=bo("span","");Po(e,bo("span",[t,document.createTextNode("x")]));0!=e.firstChild.offsetHeight&&(Pa=t.offsetWidth<=1&&t.offsetHeight>2&&!(ns&&8>os))}return Pa?bo("span",""):bo("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px")}function Vo(e){if(null!=Da)return Da;var t=Po(e,document.createTextNode("AخA")),i=Ca(t,0,1).getBoundingClientRect();if(!i||i.left==i.right)return!1;var r=Ca(t,1,2).getBoundingClientRect();return Da=r.right-i.right<3}function Fo(e){if(null!=Va)return Va;var t=Po(e,bo("span","x")),i=t.getBoundingClientRect(),r=Ca(t,0,1).getBoundingClientRect();return Va=Math.abs(i.left-r.left)>1}function Ho(e,t,i,r){if(!e)return r(t,i,"ltr");for(var n=!1,o=0;o<e.length;++o){var s=e[o];if(s.from<i&&s.to>t||t==i&&s.to==t){r(Math.max(s.from,t),Math.min(s.to,i),1==s.level?"rtl":"ltr");n=!0}}n||r(t,i,"ltr")}function jo(e){return e.level%2?e.to:e.from}function Wo(e){return e.level%2?e.from:e.to}function qo(e){var t=qn(e);return t?jo(t[0]):0}function zo(e){var t=qn(e);return t?Wo(No(t)):e.text.length}function Xo(e,t){var i=Bn(e.doc,t),r=on(i);r!=i&&(t=Hn(r));var n=qn(r),o=n?n[0].level%2?zo(r):qo(r):0;return Is(t,o)}function Yo(e,t){for(var i,r=Bn(e.doc,t);i=rn(r);){r=i.find(1,!0).line;t=null}var n=qn(r),o=n?n[0].level%2?qo(r):zo(r):r.text.length;return Is(null==t?Hn(r):t,o)}function Ko(e,t){var i=Xo(e,t.line),r=Bn(e.doc,i.line),n=qn(r);if(!n||0==n[0].level){var o=Math.max(0,r.text.search(/\S/)),s=t.line==i.line&&t.ch<=o&&t.ch;return Is(i.line,s?0:o)}return i}function $o(e,t,i){var r=e[0].level;return t==r?!0:i==r?!1:i>t}function Qo(e,t){Ha=null;for(var i,r=0;r<e.length;++r){var n=e[r];if(n.from<t&&n.to>t)return r;if(n.from==t||n.to==t){if(null!=i){if($o(e,n.level,e[i].level)){n.from!=n.to&&(Ha=i);return r}n.from!=n.to&&(Ha=r);return i}i=r}}return i}function Zo(e,t,i,r){if(!r)return t+i;do t+=i;while(t>0&&Ro(e.text.charAt(t)));return t}function Jo(e,t,i,r){var n=qn(e);if(!n)return es(e,t,i,r);for(var o=Qo(n,t),s=n[o],a=Zo(e,t,s.level%2?-i:i,r);;){if(a>s.from&&a<s.to)return a;if(a==s.from||a==s.to){if(Qo(n,a)==o)return a;s=n[o+=i];return i>0==s.level%2?s.to:s.from}s=n[o+=i];if(!s)return null;a=i>0==s.level%2?Zo(e,s.to,-1,r):Zo(e,s.from,1,r)}}function es(e,t,i,r){var n=t+i;if(r)for(;n>0&&Ro(e.text.charAt(n));)n+=i;return 0>n||n>e.text.length?null:n}var ts=/gecko\/\d/i.test(navigator.userAgent),is=/MSIE \d/.test(navigator.userAgent),rs=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),ns=is||rs,os=ns&&(is?document.documentMode||6:rs[1]),ss=/WebKit\//.test(navigator.userAgent),as=ss&&/Qt\/\d+\.\d+/.test(navigator.userAgent),ls=/Chrome\//.test(navigator.userAgent),us=/Opera\//.test(navigator.userAgent),ps=/Apple Computer/.test(navigator.vendor),cs=/KHTML\//.test(navigator.userAgent),ds=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent),fs=/PhantomJS/.test(navigator.userAgent),hs=/AppleWebKit/.test(navigator.userAgent)&&/Mobile\/\w+/.test(navigator.userAgent),Es=hs||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent),ms=hs||/Mac/.test(navigator.platform),gs=/win/i.test(navigator.platform),vs=us&&navigator.userAgent.match(/Version\/(\d*\.\d*)/);vs&&(vs=Number(vs[1]));if(vs&&vs>=15){us=!1;ss=!0}var xs=ms&&(as||us&&(null==vs||12.11>vs)),Ns=ts||ns&&os>=9,Ts=!1,Ls=!1;E.prototype=yo({update:function(e){var t=e.scrollWidth>e.clientWidth+1,i=e.scrollHeight>e.clientHeight+1,r=e.nativeBarWidth;if(i){this.vert.style.display="block";this.vert.style.bottom=t?r+"px":"0";var n=e.viewHeight-(t?r:0);this.vert.firstChild.style.height=Math.max(0,e.scrollHeight-e.clientHeight+n)+"px"}else{this.vert.style.display="";this.vert.firstChild.style.height="0"}if(t){this.horiz.style.display="block";this.horiz.style.right=i?r+"px":"0";this.horiz.style.left=e.barLeft+"px";var o=e.viewWidth-e.barLeft-(i?r:0);this.horiz.firstChild.style.width=e.scrollWidth-e.clientWidth+o+"px"}else{this.horiz.style.display="";this.horiz.firstChild.style.width="0"}if(!this.checkedOverlay&&e.clientHeight>0){0==r&&this.overlayHack();this.checkedOverlay=!0}return{right:i?r:0,bottom:t?r:0}},setScrollLeft:function(e){this.horiz.scrollLeft!=e&&(this.horiz.scrollLeft=e)},setScrollTop:function(e){this.vert.scrollTop!=e&&(this.vert.scrollTop=e)},overlayHack:function(){var e=ms&&!ds?"12px":"18px";this.horiz.style.minHeight=this.vert.style.minWidth=e;var t=this,i=function(e){lo(e)!=t.vert&&lo(e)!=t.horiz&&hi(t.cm,Gi)(e)};Ea(this.vert,"mousedown",i);Ea(this.horiz,"mousedown",i)},clear:function(){var e=this.horiz.parentNode;e.removeChild(this.horiz);e.removeChild(this.vert)}},E.prototype);m.prototype=yo({update:function(){return{bottom:0,right:0}},setScrollLeft:function(){},setScrollTop:function(){},clear:function(){}},m.prototype);e.scrollbarModel={"native":E,"null":m};var Is=e.Pos=function(e,t){if(!(this instanceof Is))return new Is(e,t);this.line=e;this.ch=t},ys=e.cmpPos=function(e,t){return e.line-t.line||e.ch-t.ch};$.prototype={primary:function(){return this.ranges[this.primIndex]},equals:function(e){if(e==this)return!0;if(e.primIndex!=this.primIndex||e.ranges.length!=this.ranges.length)return!1;for(var t=0;t<this.ranges.length;t++){var i=this.ranges[t],r=e.ranges[t];if(0!=ys(i.anchor,r.anchor)||0!=ys(i.head,r.head))return!1}return!0},deepCopy:function(){for(var e=[],t=0;t<this.ranges.length;t++)e[t]=new Q(X(this.ranges[t].anchor),X(this.ranges[t].head));return new $(e,this.primIndex)},somethingSelected:function(){for(var e=0;e<this.ranges.length;e++)if(!this.ranges[e].empty())return!0;return!1},contains:function(e,t){t||(t=e);for(var i=0;i<this.ranges.length;i++){var r=this.ranges[i];if(ys(t,r.from())>=0&&ys(e,r.to())<=0)return i}return-1}};Q.prototype={from:function(){return K(this.anchor,this.head)},to:function(){return Y(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var As,Ss,Cs,Rs={left:0,right:0,top:0,bottom:0},bs=null,Os=0,Ps=null,Ds=0,ws=0,_s=null;ns?_s=-.53:ts?_s=15:ls?_s=-.7:ps&&(_s=-1/3);var Ms=function(e){var t=e.wheelDeltaX,i=e.wheelDeltaY;null==t&&e.detail&&e.axis==e.HORIZONTAL_AXIS&&(t=e.detail);null==i&&e.detail&&e.axis==e.VERTICAL_AXIS?i=e.detail:null==i&&(i=e.wheelDelta);return{x:t,y:i}};e.wheelEventPixels=function(e){var t=Ms(e);t.x*=_s;t.y*=_s;return t};var ks=new go,Gs=null,Bs=e.changeEnd=function(e){return e.text?Is(e.from.line+e.text.length-1,No(e.text).length+(1==e.text.length?e.from.ch:0)):e.to};e.prototype={constructor:e,focus:function(){window.focus();Oi(this);Ci(this)},setOption:function(e,t){var i=this.options,r=i[e];if(i[e]!=t||"mode"==e){i[e]=t;Vs.hasOwnProperty(e)&&hi(this,Vs[e])(this,t,r)}},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](wr(e))},removeKeyMap:function(e){for(var t=this.state.keyMaps,i=0;i<t.length;++i)if(t[i]==e||t[i].name==e){t.splice(i,1);return!0}},addOverlay:Ei(function(t,i){var r=t.token?t:e.getMode(this.options,t);if(r.startState)throw new Error("Overlays may not be stateful.");this.state.overlays.push({mode:r,modeSpec:t,opaque:i&&i.opaque});this.state.modeGen++;xi(this)}),removeOverlay:Ei(function(e){for(var t=this.state.overlays,i=0;i<t.length;++i){var r=t[i].modeSpec;if(r==e||"string"==typeof e&&r.name==e){t.splice(i,1);this.state.modeGen++;xi(this);return}}}),indentLine:Ei(function(e,t,i){"string"!=typeof t&&"number"!=typeof t&&(t=null==t?this.options.smartIndent?"smart":"prev":t?"add":"subtract");rt(this.doc,e)&&Sr(this,e,t,i)}),indentSelection:Ei(function(e){for(var t=this.doc.sel.ranges,i=-1,r=0;r<t.length;r++){var n=t[r];if(n.empty()){if(n.head.line>i){Sr(this,n.head.line,e,!0);i=n.head.line;r==this.doc.sel.primIndex&&yr(this)}}else{var o=n.from(),s=n.to(),a=Math.max(i,o.line);i=Math.min(this.lastLine(),s.line-(s.ch?0:1))+1;for(var l=a;i>l;++l)Sr(this,l,e);var u=this.doc.sel.ranges;0==o.ch&&t.length==u.length&&u[r].from().ch>0&<(this.doc,r,new Q(o,u[r].to()),Ta)}}}),getTokenAt:function(e,t){return xn(this,e,t)},getLineTokens:function(e,t){return xn(this,Is(e),t,!0)},getTokenTypeAt:function(e){e=tt(this.doc,e);var t,i=Ln(this,Bn(this.doc,e.line)),r=0,n=(i.length-1)/2,o=e.ch;if(0==o)t=i[2];else for(;;){var s=r+n>>1;if((s?i[2*s-1]:0)>=o)n=s;else{if(!(i[2*s+1]<o)){t=i[2*s+2];break}r=s+1}}var a=t?t.indexOf("cm-overlay "):-1;return 0>a?t:0==a?null:t.slice(0,a-1)},getModeAt:function(t){var i=this.doc.mode;return i.innerMode?e.innerMode(i,this.getTokenAt(t).state).mode:i},getHelper:function(e,t){return this.getHelpers(e,t)[0]},getHelpers:function(e,t){var i=[];if(!zs.hasOwnProperty(t))return zs;var r=zs[t],n=this.getModeAt(e);if("string"==typeof n[t])r[n[t]]&&i.push(r[n[t]]);else if(n[t])for(var o=0;o<n[t].length;o++){var s=r[n[t][o]];s&&i.push(s)}else n.helperType&&r[n.helperType]?i.push(r[n.helperType]):r[n.name]&&i.push(r[n.name]);for(var o=0;o<r._global.length;o++){var a=r._global[o];a.pred(n,this)&&-1==To(i,a.val)&&i.push(a.val)}return i},getStateAfter:function(e,t){var i=this.doc;e=et(i,null==e?i.first+i.size-1:e);return Ct(this,e+1,t)},cursorCoords:function(e,t){var i,r=this.doc.sel.primary();i=null==e?r.head:"object"==typeof e?tt(this.doc,e):e?r.from():r.to();return Qt(this,i,t||"page")},charCoords:function(e,t){return $t(this,tt(this.doc,e),t||"page")},coordsChar:function(e,t){e=Kt(this,e,t||"page");return ei(this,e.left,e.top)},lineAtHeight:function(e,t){e=Kt(this,{top:e,left:0},t||"page").top;return jn(this.doc,e+this.display.viewOffset)},heightAtLine:function(e,t){var i=!1,r=this.doc.first+this.doc.size-1;if(e<this.doc.first)e=this.doc.first;else if(e>r){e=r;i=!0}var n=Bn(this.doc,e);return Yt(this,n,{top:0,left:0},t||"page").top+(i?this.doc.height-Wn(n):0)},defaultTextHeight:function(){return ii(this.display)},defaultCharWidth:function(){return ri(this.display)},setGutterMarker:Ei(function(e,t,i){return Cr(this.doc,e,"gutter",function(e){var r=e.gutterMarkers||(e.gutterMarkers={});r[t]=i;!i&&Co(r)&&(e.gutterMarkers=null);return!0})}),clearGutter:Ei(function(e){var t=this,i=t.doc,r=i.first;i.iter(function(i){if(i.gutterMarkers&&i.gutterMarkers[e]){i.gutterMarkers[e]=null;Ni(t,r,"gutter");Co(i.gutterMarkers)&&(i.gutterMarkers=null)}++r})}),addLineWidget:Ei(function(e,t,i){return fn(this,e,t,i)}),removeLineWidget:function(e){e.clear()},lineInfo:function(e){if("number"==typeof e){if(!rt(this.doc,e))return null;var t=e;e=Bn(this.doc,e);if(!e)return null}else{var t=Hn(e);if(null==t)return null}return{line:t,handle:e,text:e.text,gutterMarkers:e.gutterMarkers,textClass:e.textClass,bgClass:e.bgClass,wrapClass:e.wrapClass,widgets:e.widgets}},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(e,t,i,r,n){var o=this.display;e=Qt(this,tt(this.doc,e));var s=e.bottom,a=e.left;t.style.position="absolute";t.setAttribute("cm-ignore-events","true");o.sizer.appendChild(t);if("over"==r)s=e.top;else if("above"==r||"near"==r){var l=Math.max(o.wrapper.clientHeight,this.doc.height),u=Math.max(o.sizer.clientWidth,o.lineSpace.clientWidth);("above"==r||e.bottom+t.offsetHeight>l)&&e.top>t.offsetHeight?s=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=l&&(s=e.bottom);a+t.offsetWidth>u&&(a=u-t.offsetWidth)}t.style.top=s+"px";t.style.left=t.style.right="";if("right"==n){a=o.sizer.clientWidth-t.offsetWidth;t.style.right="0px"}else{"left"==n?a=0:"middle"==n&&(a=(o.sizer.clientWidth-t.offsetWidth)/2);t.style.left=a+"px"}i&&Tr(this,a,s,a+t.offsetWidth,s+t.offsetHeight)},triggerOnKeyDown:Ei(Ji),triggerOnKeyPress:Ei(ir),triggerOnKeyUp:tr,execCommand:function(e){return Ks.hasOwnProperty(e)?Ks[e](this):void 0},findPosH:function(e,t,i,r){var n=1;if(0>t){n=-1;t=-t}for(var o=0,s=tt(this.doc,e);t>o;++o){s=br(this.doc,s,n,i,r);if(s.hitSide)break}return s},moveH:Ei(function(e,t){var i=this;i.extendSelectionsBy(function(r){return i.display.shift||i.doc.extend||r.empty()?br(i.doc,r.head,e,t,i.options.rtlMoveVisually):0>e?r.from():r.to()},Ia)}),deleteH:Ei(function(e,t){var i=this.doc.sel,r=this.doc;i.somethingSelected()?r.replaceSelection("",null,"+delete"):Rr(this,function(i){var n=br(r,i.head,e,t,!1);return 0>e?{from:n,to:i.head}:{from:i.head,to:n}})}),findPosV:function(e,t,i,r){var n=1,o=r;if(0>t){n=-1;t=-t}for(var s=0,a=tt(this.doc,e);t>s;++s){var l=Qt(this,a,"div");null==o?o=l.left:l.left=o;a=Or(this,l,n,i);if(a.hitSide)break}return a},moveV:Ei(function(e,t){var i=this,r=this.doc,n=[],o=!i.display.shift&&!r.extend&&r.sel.somethingSelected();r.extendSelectionsBy(function(s){if(o)return 0>e?s.from():s.to();var a=Qt(i,s.head,"div");null!=s.goalColumn&&(a.left=s.goalColumn);n.push(a.left);var l=Or(i,a,e,t);
"page"==t&&s==r.sel.primary()&&Ir(i,null,$t(i,l,"div").top-a.top);return l},Ia);if(n.length)for(var s=0;s<r.sel.ranges.length;s++)r.sel.ranges[s].goalColumn=n[s]}),findWordAt:function(e){var t=this.doc,i=Bn(t,e.line).text,r=e.ch,n=e.ch;if(i){var o=this.getHelper(e,"wordChars");(e.xRel<0||n==i.length)&&r?--r:++n;for(var s=i.charAt(r),a=So(s,o)?function(e){return So(e,o)}:/\s/.test(s)?function(e){return/\s/.test(e)}:function(e){return!/\s/.test(e)&&!So(e)};r>0&&a(i.charAt(r-1));)--r;for(;n<i.length&&a(i.charAt(n));)++n}return new Q(Is(e.line,r),Is(e.line,n))},toggleOverwrite:function(e){if(null==e||e!=this.state.overwrite){(this.state.overwrite=!this.state.overwrite)?_a(this.display.cursorDiv,"CodeMirror-overwrite"):wa(this.display.cursorDiv,"CodeMirror-overwrite");ga(this,"overwriteToggle",this,this.state.overwrite)}},hasFocus:function(){return wo()==this.display.input},scrollTo:Ei(function(e,t){(null!=e||null!=t)&&Ar(this);null!=e&&(this.curOp.scrollLeft=e);null!=t&&(this.curOp.scrollTop=t)}),getScrollInfo:function(){var e=this.display.scroller;return{left:e.scrollLeft,top:e.scrollTop,height:e.scrollHeight-Pt(this)-this.display.barHeight,width:e.scrollWidth-Pt(this)-this.display.barWidth,clientHeight:wt(this),clientWidth:Dt(this)}},scrollIntoView:Ei(function(e,t){if(null==e){e={from:this.doc.sel.primary().head,to:null};null==t&&(t=this.options.cursorScrollMargin)}else"number"==typeof e?e={from:Is(e,0),to:null}:null==e.from&&(e={from:e,to:null});e.to||(e.to=e.from);e.margin=t||0;if(null!=e.from.line){Ar(this);this.curOp.scrollToPos=e}else{var i=Lr(this,Math.min(e.from.left,e.to.left),Math.min(e.from.top,e.to.top)-e.margin,Math.max(e.from.right,e.to.right),Math.max(e.from.bottom,e.to.bottom)+e.margin);this.scrollTo(i.scrollLeft,i.scrollTop)}}),setSize:Ei(function(e,t){function i(e){return"number"==typeof e||/^\d+$/.test(String(e))?e+"px":e}var r=this;null!=e&&(r.display.wrapper.style.width=i(e));null!=t&&(r.display.wrapper.style.height=i(t));r.options.lineWrapping&&Wt(this);var n=r.display.viewFrom;r.doc.iter(n,r.display.viewTo,function(e){if(e.widgets)for(var t=0;t<e.widgets.length;t++)if(e.widgets[t].noHScroll){Ni(r,n,"widget");break}++n});r.curOp.forceUpdate=!0;ga(r,"refresh",this)}),operation:function(e){return fi(this,e)},refresh:Ei(function(){var e=this.display.cachedTextHeight;xi(this);this.curOp.forceUpdate=!0;qt(this);this.scrollTo(this.doc.scrollLeft,this.doc.scrollTop);p(this);(null==e||Math.abs(e-ii(this.display))>.5)&&s(this);ga(this,"refresh",this)}),swapDoc:Ei(function(e){var t=this.doc;t.cm=null;Gn(this,e);qt(this);bi(this);this.scrollTo(e.scrollLeft,e.scrollTop);this.curOp.forceScroll=!0;po(this,"swapDoc",this,t);return t}),getInputField:function(){return this.display.input},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}};mo(e);var Us=e.defaults={},Vs=e.optionHandlers={},Fs=e.Init={toString:function(){return"CodeMirror.Init"}};Pr("value","",function(e,t){e.setValue(t)},!0);Pr("mode",null,function(e,t){e.doc.modeOption=t;i(e)},!0);Pr("indentUnit",2,i,!0);Pr("indentWithTabs",!1);Pr("smartIndent",!0);Pr("tabSize",4,function(e){r(e);qt(e);xi(e)},!0);Pr("specialChars",/[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g,function(e,t){e.options.specialChars=new RegExp(t.source+(t.test(" ")?"":"| "),"g");e.refresh()},!0);Pr("specialCharPlaceholder",Sn,function(e){e.refresh()},!0);Pr("electricChars",!0);Pr("rtlMoveVisually",!gs);Pr("wholeLineUpdateBefore",!0);Pr("theme","default",function(e){a(e);l(e)},!0);Pr("keyMap","default",function(t,i,r){var n=wr(i),o=r!=e.Init&&wr(r);o&&o.detach&&o.detach(t,n);n.attach&&n.attach(t,o||null)});Pr("extraKeys",null);Pr("lineWrapping",!1,n,!0);Pr("gutters",[],function(e){f(e.options);l(e)},!0);Pr("fixedGutter",!0,function(e,t){e.display.gutters.style.left=t?y(e.display)+"px":"0";e.refresh()},!0);Pr("coverGutterNextToScrollbar",!1,function(e){v(e)},!0);Pr("scrollbarStyle","native",function(e){g(e);v(e);e.display.scrollbars.setScrollTop(e.doc.scrollTop);e.display.scrollbars.setScrollLeft(e.doc.scrollLeft)},!0);Pr("lineNumbers",!1,function(e){f(e.options);l(e)},!0);Pr("firstLineNumber",1,l,!0);Pr("lineNumberFormatter",function(e){return e},l,!0);Pr("showCursorWhenSelecting",!1,Nt,!0);Pr("resetSelectionOnContextMenu",!0);Pr("readOnly",!1,function(e,t){if("nocursor"==t){nr(e);e.display.input.blur();e.display.disabled=!0}else{e.display.disabled=!1;t||bi(e)}});Pr("disableInput",!1,function(e,t){t||bi(e)},!0);Pr("dragDrop",!0);Pr("cursorBlinkRate",530);Pr("cursorScrollMargin",0);Pr("cursorHeight",1,Nt,!0);Pr("singleCursorHeightPerLine",!0,Nt,!0);Pr("workTime",100);Pr("workDelay",100);Pr("flattenSpans",!0,r,!0);Pr("addModeClass",!1,r,!0);Pr("pollInterval",100);Pr("undoDepth",200,function(e,t){e.doc.history.undoDepth=t});Pr("historyEventDelay",1250);Pr("viewportMargin",10,function(e){e.refresh()},!0);Pr("maxHighlightLength",1e4,r,!0);Pr("moveInputWithCursor",!0,function(e,t){t||(e.display.inputDiv.style.top=e.display.inputDiv.style.left=0)});Pr("tabindex",null,function(e,t){e.display.input.tabIndex=t||""});Pr("autofocus",null);var Hs=e.modes={},js=e.mimeModes={};e.defineMode=function(t,i){e.defaults.mode||"null"==t||(e.defaults.mode=t);arguments.length>2&&(i.dependencies=Array.prototype.slice.call(arguments,2));Hs[t]=i};e.defineMIME=function(e,t){js[e]=t};e.resolveMode=function(t){if("string"==typeof t&&js.hasOwnProperty(t))t=js[t];else if(t&&"string"==typeof t.name&&js.hasOwnProperty(t.name)){var i=js[t.name];"string"==typeof i&&(i={name:i});t=Io(i,t);t.name=i.name}else if("string"==typeof t&&/^[\w\-]+\/[\w\-]+\+xml$/.test(t))return e.resolveMode("application/xml");return"string"==typeof t?{name:t}:t||{name:"null"}};e.getMode=function(t,i){var i=e.resolveMode(i),r=Hs[i.name];if(!r)return e.getMode(t,"text/plain");var n=r(t,i);if(Ws.hasOwnProperty(i.name)){var o=Ws[i.name];for(var s in o)if(o.hasOwnProperty(s)){n.hasOwnProperty(s)&&(n["_"+s]=n[s]);n[s]=o[s]}}n.name=i.name;i.helperType&&(n.helperType=i.helperType);if(i.modeProps)for(var s in i.modeProps)n[s]=i.modeProps[s];return n};e.defineMode("null",function(){return{token:function(e){e.skipToEnd()}}});e.defineMIME("text/plain","null");var Ws=e.modeExtensions={};e.extendMode=function(e,t){var i=Ws.hasOwnProperty(e)?Ws[e]:Ws[e]={};yo(t,i)};e.defineExtension=function(t,i){e.prototype[t]=i};e.defineDocExtension=function(e,t){ua.prototype[e]=t};e.defineOption=Pr;var qs=[];e.defineInitHook=function(e){qs.push(e)};var zs=e.helpers={};e.registerHelper=function(t,i,r){zs.hasOwnProperty(t)||(zs[t]=e[t]={_global:[]});zs[t][i]=r};e.registerGlobalHelper=function(t,i,r,n){e.registerHelper(t,i,n);zs[t]._global.push({pred:r,val:n})};var Xs=e.copyState=function(e,t){if(t===!0)return t;if(e.copyState)return e.copyState(t);var i={};for(var r in t){var n=t[r];n instanceof Array&&(n=n.concat([]));i[r]=n}return i},Ys=e.startState=function(e,t,i){return e.startState?e.startState(t,i):!0};e.innerMode=function(e,t){for(;e.innerMode;){var i=e.innerMode(t);if(!i||i.mode==e)break;t=i.state;e=i.mode}return i||{mode:e,state:t}};var Ks=e.commands={selectAll:function(e){e.setSelection(Is(e.firstLine(),0),Is(e.lastLine()),Ta)},singleSelection:function(e){e.setSelection(e.getCursor("anchor"),e.getCursor("head"),Ta)},killLine:function(e){Rr(e,function(t){if(t.empty()){var i=Bn(e.doc,t.head.line).text.length;return t.head.ch==i&&t.head.line<e.lastLine()?{from:t.head,to:Is(t.head.line+1,0)}:{from:t.head,to:Is(t.head.line,i)}}return{from:t.from(),to:t.to()}})},deleteLine:function(e){Rr(e,function(t){return{from:Is(t.from().line,0),to:tt(e.doc,Is(t.to().line+1,0))}})},delLineLeft:function(e){Rr(e,function(e){return{from:Is(e.from().line,0),to:e.from()}})},delWrappedLineLeft:function(e){Rr(e,function(t){var i=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:0,top:i},"div");return{from:r,to:t.from()}})},delWrappedLineRight:function(e){Rr(e,function(t){var i=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:i},"div");return{from:t.from(),to:r}})},undo:function(e){e.undo()},redo:function(e){e.redo()},undoSelection:function(e){e.undoSelection()},redoSelection:function(e){e.redoSelection()},goDocStart:function(e){e.extendSelection(Is(e.firstLine(),0))},goDocEnd:function(e){e.extendSelection(Is(e.lastLine()))},goLineStart:function(e){e.extendSelectionsBy(function(t){return Xo(e,t.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(e){e.extendSelectionsBy(function(t){return Ko(e,t.head)},{origin:"+move",bias:1})},goLineEnd:function(e){e.extendSelectionsBy(function(t){return Yo(e,t.head.line)},{origin:"+move",bias:-1})},goLineRight:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:i},"div")},Ia)},goLineLeft:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:0,top:i},"div")},Ia)},goLineLeftSmart:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:0,top:i},"div");return r.ch<e.getLine(r.line).search(/\S/)?Ko(e,t.head):r},Ia)},goLineUp:function(e){e.moveV(-1,"line")},goLineDown:function(e){e.moveV(1,"line")},goPageUp:function(e){e.moveV(-1,"page")},goPageDown:function(e){e.moveV(1,"page")},goCharLeft:function(e){e.moveH(-1,"char")},goCharRight:function(e){e.moveH(1,"char")},goColumnLeft:function(e){e.moveH(-1,"column")},goColumnRight:function(e){e.moveH(1,"column")},goWordLeft:function(e){e.moveH(-1,"word")},goGroupRight:function(e){e.moveH(1,"group")},goGroupLeft:function(e){e.moveH(-1,"group")},goWordRight:function(e){e.moveH(1,"word")},delCharBefore:function(e){e.deleteH(-1,"char")},delCharAfter:function(e){e.deleteH(1,"char")},delWordBefore:function(e){e.deleteH(-1,"word")},delWordAfter:function(e){e.deleteH(1,"word")},delGroupBefore:function(e){e.deleteH(-1,"group")},delGroupAfter:function(e){e.deleteH(1,"group")},indentAuto:function(e){e.indentSelection("smart")},indentMore:function(e){e.indentSelection("add")},indentLess:function(e){e.indentSelection("subtract")},insertTab:function(e){e.replaceSelection(" ")},insertSoftTab:function(e){for(var t=[],i=e.listSelections(),r=e.options.tabSize,n=0;n<i.length;n++){var o=i[n].from(),s=ya(e.getLine(o.line),o.ch,r);t.push(new Array(r-s%r+1).join(" "))}e.replaceSelections(t)},defaultTab:function(e){e.somethingSelected()?e.indentSelection("add"):e.execCommand("insertTab")},transposeChars:function(e){fi(e,function(){for(var t=e.listSelections(),i=[],r=0;r<t.length;r++){var n=t[r].head,o=Bn(e.doc,n.line).text;if(o){n.ch==o.length&&(n=new Is(n.line,n.ch-1));if(n.ch>0){n=new Is(n.line,n.ch+1);e.replaceRange(o.charAt(n.ch-1)+o.charAt(n.ch-2),Is(n.line,n.ch-2),n,"+transpose")}else if(n.line>e.doc.first){var s=Bn(e.doc,n.line-1).text;s&&e.replaceRange(o.charAt(0)+"\n"+s.charAt(s.length-1),Is(n.line-1,s.length-1),Is(n.line,1),"+transpose")}}i.push(new Q(n,n))}e.setSelections(i)})},newlineAndIndent:function(e){fi(e,function(){for(var t=e.listSelections().length,i=0;t>i;i++){var r=e.listSelections()[i];e.replaceRange("\n",r.anchor,r.head,"+input");e.indentLine(r.from().line+1,null,!0);yr(e)}})},toggleOverwrite:function(e){e.toggleOverwrite()}},$s=e.keyMap={};$s.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"};$s.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"};$s.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars"};$s.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]};$s["default"]=ms?$s.macDefault:$s.pcDefault;e.normalizeKeyMap=function(e){var t={};for(var i in e)if(e.hasOwnProperty(i)){var r=e[i];if(/^(name|fallthrough|(de|at)tach)$/.test(i))continue;if("..."==r){delete e[i];continue}for(var n=Lo(i.split(" "),Dr),o=0;o<n.length;o++){var s,a;if(o==n.length-1){a=i;s=r}else{a=n.slice(0,o+1).join(" ");s="..."}var l=t[a];if(l){if(l!=s)throw new Error("Inconsistent bindings for "+a)}else t[a]=s}delete e[i]}for(var u in t)e[u]=t[u];return e};var Qs=e.lookupKey=function(e,t,i,r){t=wr(t);var n=t.call?t.call(e,r):t[e];if(n===!1)return"nothing";if("..."===n)return"multi";if(null!=n&&i(n))return"handled";if(t.fallthrough){if("[object Array]"!=Object.prototype.toString.call(t.fallthrough))return Qs(e,t.fallthrough,i,r);for(var o=0;o<t.fallthrough.length;o++){var s=Qs(e,t.fallthrough[o],i,r);if(s)return s}}},Zs=e.isModifierKey=function(e){var t="string"==typeof e?e:Fa[e.keyCode];return"Ctrl"==t||"Alt"==t||"Shift"==t||"Mod"==t},Js=e.keyName=function(e,t){if(us&&34==e.keyCode&&e["char"])return!1;var i=Fa[e.keyCode],r=i;if(null==r||e.altGraphKey)return!1;e.altKey&&"Alt"!=i&&(r="Alt-"+r);(xs?e.metaKey:e.ctrlKey)&&"Ctrl"!=i&&(r="Ctrl-"+r);(xs?e.ctrlKey:e.metaKey)&&"Cmd"!=i&&(r="Cmd-"+r);!t&&e.shiftKey&&"Shift"!=i&&(r="Shift-"+r);return r};e.fromTextArea=function(t,i){function r(){t.value=u.getValue()}i||(i={});i.value=t.value;!i.tabindex&&t.tabindex&&(i.tabindex=t.tabindex);!i.placeholder&&t.placeholder&&(i.placeholder=t.placeholder);if(null==i.autofocus){var n=wo();i.autofocus=n==t||null!=t.getAttribute("autofocus")&&n==document.body}if(t.form){Ea(t.form,"submit",r);if(!i.leaveSubmitMethodAlone){var o=t.form,s=o.submit;try{var a=o.submit=function(){r();o.submit=s;o.submit();o.submit=a}}catch(l){}}}t.style.display="none";var u=e(function(e){t.parentNode.insertBefore(e,t.nextSibling)},i);u.save=r;u.getTextArea=function(){return t};u.toTextArea=function(){u.toTextArea=isNaN;r();t.parentNode.removeChild(u.getWrapperElement());t.style.display="";if(t.form){ma(t.form,"submit",r);"function"==typeof t.form.submit&&(t.form.submit=s)}};return u};var ea=e.StringStream=function(e,t){this.pos=this.start=0;this.string=e;this.tabSize=t||8;this.lastColumnPos=this.lastColumnValue=0;this.lineStart=0};ea.prototype={eol:function(){return this.pos>=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){return this.pos<this.string.length?this.string.charAt(this.pos++):void 0},eat:function(e){var t=this.string.charAt(this.pos);if("string"==typeof e)var i=t==e;else var i=t&&(e.test?e.test(t):e(t));if(i){++this.pos;return t}},eatWhile:function(e){for(var t=this.pos;this.eat(e););return this.pos>t},eatSpace:function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},skipToEnd:function(){this.pos=this.string.length},skipTo:function(e){var t=this.string.indexOf(e,this.pos);if(t>-1){this.pos=t;return!0}},backUp:function(e){this.pos-=e},column:function(){if(this.lastColumnPos<this.start){this.lastColumnValue=ya(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue);this.lastColumnPos=this.start}return this.lastColumnValue-(this.lineStart?ya(this.string,this.lineStart,this.tabSize):0)},indentation:function(){return ya(this.string,null,this.tabSize)-(this.lineStart?ya(this.string,this.lineStart,this.tabSize):0)},match:function(e,t,i){if("string"!=typeof e){var r=this.string.slice(this.pos).match(e);if(r&&r.index>0)return null;r&&t!==!1&&(this.pos+=r[0].length);return r}var n=function(e){return i?e.toLowerCase():e},o=this.string.substr(this.pos,e.length);if(n(o)==n(e)){t!==!1&&(this.pos+=e.length);return!0}},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}}};var ta=e.TextMarker=function(e,t){this.lines=[];this.type=t;this.doc=e};mo(ta);ta.prototype.clear=function(){if(!this.explicitlyCleared){var e=this.doc.cm,t=e&&!e.curOp;t&&ni(e);if(Eo(this,"clear")){var i=this.find();i&&po(this,"clear",i.from,i.to)}for(var r=null,n=null,o=0;o<this.lines.length;++o){var s=this.lines[o],a=Vr(s.markedSpans,this);if(e&&!this.collapsed)Ni(e,Hn(s),"text");else if(e){null!=a.to&&(n=Hn(s));null!=a.from&&(r=Hn(s))}s.markedSpans=Fr(s.markedSpans,a);null==a.from&&this.collapsed&&!un(this.doc,s)&&e&&Fn(s,ii(e.display))}if(e&&this.collapsed&&!e.options.lineWrapping)for(var o=0;o<this.lines.length;++o){var l=on(this.lines[o]),u=c(l);if(u>e.display.maxLineLength){e.display.maxLine=l;e.display.maxLineLength=u;e.display.maxLineChanged=!0}}null!=r&&e&&this.collapsed&&xi(e,r,n+1);this.lines.length=0;this.explicitlyCleared=!0;if(this.atomic&&this.doc.cantEdit){this.doc.cantEdit=!1;e&&Et(e.doc)}e&&po(e,"markerCleared",e,this);t&&si(e);this.parent&&this.parent.clear()}};ta.prototype.find=function(e,t){null==e&&"bookmark"==this.type&&(e=1);for(var i,r,n=0;n<this.lines.length;++n){var o=this.lines[n],s=Vr(o.markedSpans,this);if(null!=s.from){i=Is(t?o:Hn(o),s.from);if(-1==e)return i}if(null!=s.to){r=Is(t?o:Hn(o),s.to);if(1==e)return r}}return i&&{from:i,to:r}};ta.prototype.changed=function(){var e=this.find(-1,!0),t=this,i=this.doc.cm;e&&i&&fi(i,function(){var r=e.line,n=Hn(e.line),o=Bt(i,n);if(o){jt(o);i.curOp.selectionChanged=i.curOp.forceUpdate=!0}i.curOp.updateMaxLine=!0;if(!un(t.doc,r)&&null!=t.height){var s=t.height;t.height=null;var a=dn(t)-s;a&&Fn(r,r.height+a)}})};ta.prototype.attachLine=function(e){if(!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;t.maybeHiddenMarkers&&-1!=To(t.maybeHiddenMarkers,this)||(t.maybeUnhiddenMarkers||(t.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(e)};ta.prototype.detachLine=function(e){this.lines.splice(To(this.lines,e),1);if(!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;(t.maybeHiddenMarkers||(t.maybeHiddenMarkers=[])).push(this)}};var ia=0,ra=e.SharedTextMarker=function(e,t){this.markers=e;this.primary=t;for(var i=0;i<e.length;++i)e[i].parent=this};mo(ra);ra.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var e=0;e<this.markers.length;++e)this.markers[e].clear();po(this,"clear")}};ra.prototype.find=function(e,t){return this.primary.find(e,t)};var na=e.LineWidget=function(e,t,i){if(i)for(var r in i)i.hasOwnProperty(r)&&(this[r]=i[r]);this.cm=e;this.node=t};mo(na);na.prototype.clear=function(){var e=this.cm,t=this.line.widgets,i=this.line,r=Hn(i);if(null!=r&&t){for(var n=0;n<t.length;++n)t[n]==this&&t.splice(n--,1);t.length||(i.widgets=null);var o=dn(this);fi(e,function(){cn(e,i,-o);Ni(e,r,"widget");Fn(i,Math.max(0,i.height-o))})}};na.prototype.changed=function(){var e=this.height,t=this.cm,i=this.line;this.height=null;var r=dn(this)-e;r&&fi(t,function(){t.curOp.forceUpdate=!0;cn(t,i,r);Fn(i,i.height+r)})};var oa=e.Line=function(e,t,i){this.text=e;$r(this,t);this.height=i?i(this):1};mo(oa);oa.prototype.lineNo=function(){return Hn(this)};var sa={},aa={};_n.prototype={chunkSize:function(){return this.lines.length},removeInner:function(e,t){for(var i=e,r=e+t;r>i;++i){var n=this.lines[i];this.height-=n.height;En(n);po(n,"delete")}this.lines.splice(e,t)},collapse:function(e){e.push.apply(e,this.lines)},insertInner:function(e,t,i){this.height+=i;this.lines=this.lines.slice(0,e).concat(t).concat(this.lines.slice(e));for(var r=0;r<t.length;++r)t[r].parent=this},iterN:function(e,t,i){for(var r=e+t;r>e;++e)if(i(this.lines[e]))return!0}};Mn.prototype={chunkSize:function(){return this.size},removeInner:function(e,t){this.size-=t;for(var i=0;i<this.children.length;++i){var r=this.children[i],n=r.chunkSize();if(n>e){var o=Math.min(t,n-e),s=r.height;r.removeInner(e,o);this.height-=s-r.height;if(n==o){this.children.splice(i--,1);r.parent=null}if(0==(t-=o))break;e=0}else e-=n}if(this.size-t<25&&(this.children.length>1||!(this.children[0]instanceof _n))){var a=[];this.collapse(a);this.children=[new _n(a)];this.children[0].parent=this}},collapse:function(e){for(var t=0;t<this.children.length;++t)this.children[t].collapse(e)},insertInner:function(e,t,i){this.size+=t.length;this.height+=i;for(var r=0;r<this.children.length;++r){var n=this.children[r],o=n.chunkSize();if(o>=e){n.insertInner(e,t,i);if(n.lines&&n.lines.length>50){for(;n.lines.length>50;){var s=n.lines.splice(n.lines.length-25,25),a=new _n(s);n.height-=a.height;this.children.splice(r+1,0,a);a.parent=this}this.maybeSpill()}break}e-=o}},maybeSpill:function(){if(!(this.children.length<=10)){var e=this;do{var t=e.children.splice(e.children.length-5,5),i=new Mn(t);if(e.parent){e.size-=i.size;e.height-=i.height;var r=To(e.parent.children,e);e.parent.children.splice(r+1,0,i)}else{var n=new Mn(e.children);n.parent=e;e.children=[n,i];e=n}i.parent=e.parent}while(e.children.length>10);e.parent.maybeSpill()}},iterN:function(e,t,i){for(var r=0;r<this.children.length;++r){var n=this.children[r],o=n.chunkSize();if(o>e){var s=Math.min(t,o-e);if(n.iterN(e,s,i))return!0;if(0==(t-=s))break;e=0}else e-=o}}};var la=0,ua=e.Doc=function(e,t,i){if(!(this instanceof ua))return new ua(e,t,i);null==i&&(i=0);Mn.call(this,[new _n([new oa("",null)])]);this.first=i;this.scrollTop=this.scrollLeft=0;this.cantEdit=!1;this.cleanGeneration=1;this.frontier=i;var r=Is(i,0);this.sel=J(r);this.history=new zn(null);this.id=++la;this.modeOption=t;"string"==typeof e&&(e=Ga(e));wn(this,{from:r,to:r,text:e});dt(this,J(r),Ta)};ua.prototype=Io(Mn.prototype,{constructor:ua,iter:function(e,t,i){i?this.iterN(e-this.first,t-e,i):this.iterN(this.first,this.first+this.size,e)},insert:function(e,t){for(var i=0,r=0;r<t.length;++r)i+=t[r].height;this.insertInner(e-this.first,t,i)},remove:function(e,t){this.removeInner(e-this.first,t)},getValue:function(e){var t=Vn(this,this.first,this.first+this.size);return e===!1?t:t.join(e||"\n")},setValue:mi(function(e){var t=Is(this.first,0),i=this.first+this.size-1;dr(this,{from:t,to:Is(i,Bn(this,i).text.length),text:Ga(e),origin:"setValue",full:!0},!0);dt(this,J(t))}),replaceRange:function(e,t,i,r){t=tt(this,t);i=i?tt(this,i):t;vr(this,e,t,i,r)},getRange:function(e,t,i){var r=Un(this,tt(this,e),tt(this,t));return i===!1?r:r.join(i||"\n")},getLine:function(e){var t=this.getLineHandle(e);return t&&t.text},getLineHandle:function(e){return rt(this,e)?Bn(this,e):void 0},getLineNumber:function(e){return Hn(e)},getLineHandleVisualStart:function(e){"number"==typeof e&&(e=Bn(this,e));return on(e)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(e){return tt(this,e)},getCursor:function(e){var t,i=this.sel.primary();t=null==e||"head"==e?i.head:"anchor"==e?i.anchor:"end"==e||"to"==e||e===!1?i.to():i.from();return t},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:mi(function(e,t,i){ut(this,tt(this,"number"==typeof e?Is(e,t||0):e),null,i)}),setSelection:mi(function(e,t,i){ut(this,tt(this,e),tt(this,t||e),i)}),extendSelection:mi(function(e,t,i){st(this,tt(this,e),t&&tt(this,t),i)}),extendSelections:mi(function(e,t){at(this,nt(this,e,t))}),extendSelectionsBy:mi(function(e,t){at(this,Lo(this.sel.ranges,e),t)}),setSelections:mi(function(e,t,i){if(e.length){for(var r=0,n=[];r<e.length;r++)n[r]=new Q(tt(this,e[r].anchor),tt(this,e[r].head));null==t&&(t=Math.min(e.length-1,this.sel.primIndex));dt(this,Z(n,t),i)}}),addSelection:mi(function(e,t,i){var r=this.sel.ranges.slice(0);r.push(new Q(tt(this,e),tt(this,t||e)));dt(this,Z(r,r.length-1),i)}),getSelection:function(e){for(var t,i=this.sel.ranges,r=0;r<i.length;r++){var n=Un(this,i[r].from(),i[r].to());t=t?t.concat(n):n}return e===!1?t:t.join(e||"\n")},getSelections:function(e){for(var t=[],i=this.sel.ranges,r=0;r<i.length;r++){var n=Un(this,i[r].from(),i[r].to());e!==!1&&(n=n.join(e||"\n"));t[r]=n}return t},replaceSelection:function(e,t,i){for(var r=[],n=0;n<this.sel.ranges.length;n++)r[n]=e;this.replaceSelections(r,t,i||"+input")},replaceSelections:mi(function(e,t,i){for(var r=[],n=this.sel,o=0;o<n.ranges.length;o++){var s=n.ranges[o];r[o]={from:s.from(),to:s.to(),text:Ga(e[o]),origin:i}}for(var a=t&&"end"!=t&&pr(this,r,t),o=r.length-1;o>=0;o--)dr(this,r[o]);a?ct(this,a):this.cm&&yr(this.cm)}),undo:mi(function(){hr(this,"undo")}),redo:mi(function(){hr(this,"redo")}),undoSelection:mi(function(){hr(this,"undo",!0)}),redoSelection:mi(function(){hr(this,"redo",!0)}),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){for(var e=this.history,t=0,i=0,r=0;r<e.done.length;r++)e.done[r].ranges||++t;for(var r=0;r<e.undone.length;r++)e.undone[r].ranges||++i;return{undo:t,redo:i}},clearHistory:function(){this.history=new zn(this.history.maxGeneration)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(e){e&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null);return this.history.generation},isClean:function(e){return this.history.generation==(e||this.cleanGeneration)},getHistory:function(){return{done:ro(this.history.done),undone:ro(this.history.undone)}},setHistory:function(e){var t=this.history=new zn(this.history.maxGeneration);t.done=ro(e.done.slice(0),null,!0);t.undone=ro(e.undone.slice(0),null,!0)},addLineClass:mi(function(e,t,i){return Cr(this,e,"gutter"==t?"gutter":"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"gutter"==t?"gutterClass":"wrapClass";if(e[r]){if(_o(i).test(e[r]))return!1;e[r]+=" "+i}else e[r]=i;return!0})}),removeLineClass:mi(function(e,t,i){return Cr(this,e,"gutter"==t?"gutter":"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"gutter"==t?"gutterClass":"wrapClass",n=e[r];if(!n)return!1;if(null==i)e[r]=null;else{var o=n.match(_o(i));if(!o)return!1;var s=o.index+o[0].length;e[r]=n.slice(0,o.index)+(o.index&&s!=n.length?" ":"")+n.slice(s)||null}return!0})}),markText:function(e,t,i){return _r(this,tt(this,e),tt(this,t),i,"range")},setBookmark:function(e,t){var i={replacedWith:t&&(null==t.nodeType?t.widget:t),insertLeft:t&&t.insertLeft,clearWhenEmpty:!1,shared:t&&t.shared};e=tt(this,e);return _r(this,e,e,i,"bookmark")},findMarksAt:function(e){e=tt(this,e);var t=[],i=Bn(this,e.line).markedSpans;if(i)for(var r=0;r<i.length;++r){var n=i[r];(null==n.from||n.from<=e.ch)&&(null==n.to||n.to>=e.ch)&&t.push(n.marker.parent||n.marker)}return t},findMarks:function(e,t,i){e=tt(this,e);t=tt(this,t);var r=[],n=e.line;this.iter(e.line,t.line+1,function(o){var s=o.markedSpans;if(s)for(var a=0;a<s.length;a++){var l=s[a];n==e.line&&e.ch>l.to||null==l.from&&n!=e.line||n==t.line&&l.from>t.ch||i&&!i(l.marker)||r.push(l.marker.parent||l.marker)}++n});return r},getAllMarks:function(){var e=[];this.iter(function(t){var i=t.markedSpans;if(i)for(var r=0;r<i.length;++r)null!=i[r].from&&e.push(i[r].marker)});return e},posFromIndex:function(e){var t,i=this.first;this.iter(function(r){var n=r.text.length+1;if(n>e){t=e;return!0}e-=n;++i});return tt(this,Is(i,t))},indexFromPos:function(e){e=tt(this,e);var t=e.ch;if(e.line<this.first||e.ch<0)return 0;this.iter(this.first,e.line,function(e){t+=e.text.length+1});return t},copy:function(e){var t=new ua(Vn(this,this.first,this.first+this.size),this.modeOption,this.first);t.scrollTop=this.scrollTop;t.scrollLeft=this.scrollLeft;t.sel=this.sel;t.extend=!1;if(e){t.history.undoDepth=this.history.undoDepth;t.setHistory(this.getHistory())}return t},linkedDoc:function(e){e||(e={});var t=this.first,i=this.first+this.size;null!=e.from&&e.from>t&&(t=e.from);null!=e.to&&e.to<i&&(i=e.to);var r=new ua(Vn(this,t,i),e.mode||this.modeOption,t);e.sharedHist&&(r.history=this.history);(this.linked||(this.linked=[])).push({doc:r,sharedHist:e.sharedHist});r.linked=[{doc:this,isParent:!0,sharedHist:e.sharedHist}];Gr(r,kr(this));return r},unlinkDoc:function(t){t instanceof e&&(t=t.doc);if(this.linked)for(var i=0;i<this.linked.length;++i){var r=this.linked[i];if(r.doc==t){this.linked.splice(i,1);t.unlinkDoc(this);Br(kr(this));break}}if(t.history==this.history){var n=[t.id];kn(t,function(e){n.push(e.id)},!0);t.history=new zn(null);t.history.done=ro(this.history.done,n);t.history.undone=ro(this.history.undone,n)}},iterLinkedDocs:function(e){kn(this,e)},getMode:function(){return this.mode},getEditor:function(){return this.cm}});ua.prototype.eachLine=ua.prototype.iter;var pa="iter insert remove copy getEditor".split(" ");for(var ca in ua.prototype)ua.prototype.hasOwnProperty(ca)&&To(pa,ca)<0&&(e.prototype[ca]=function(e){return function(){return e.apply(this.doc,arguments)}}(ua.prototype[ca]));mo(ua);var da=e.e_preventDefault=function(e){e.preventDefault?e.preventDefault():e.returnValue=!1},fa=e.e_stopPropagation=function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0},ha=e.e_stop=function(e){da(e);fa(e)},Ea=e.on=function(e,t,i){if(e.addEventListener)e.addEventListener(t,i,!1);else if(e.attachEvent)e.attachEvent("on"+t,i);else{var r=e._handlers||(e._handlers={}),n=r[t]||(r[t]=[]);n.push(i)}},ma=e.off=function(e,t,i){if(e.removeEventListener)e.removeEventListener(t,i,!1);else if(e.detachEvent)e.detachEvent("on"+t,i);else{var r=e._handlers&&e._handlers[t];if(!r)return;for(var n=0;n<r.length;++n)if(r[n]==i){r.splice(n,1);break}}},ga=e.signal=function(e,t){var i=e._handlers&&e._handlers[t];if(i)for(var r=Array.prototype.slice.call(arguments,2),n=0;n<i.length;++n)i[n].apply(null,r)},va=null,xa=30,Na=e.Pass={toString:function(){return"CodeMirror.Pass"}},Ta={scroll:!1},La={origin:"*mouse"},Ia={origin:"+move"};go.prototype.set=function(e,t){clearTimeout(this.id);this.id=setTimeout(t,e)};var ya=e.countColumn=function(e,t,i,r,n){if(null==t){t=e.search(/[^\s\u00a0]/);-1==t&&(t=e.length)}for(var o=r||0,s=n||0;;){var a=e.indexOf(" ",o);if(0>a||a>=t)return s+(t-o);s+=a-o;s+=i-s%i;o=a+1}},Aa=[""],Sa=function(e){e.select()};hs?Sa=function(e){e.selectionStart=0;e.selectionEnd=e.value.length}:ns&&(Sa=function(e){try{e.select()}catch(t){}});var Ca,Ra=/[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,ba=e.isWordChar=function(e){return/\w/.test(e)||e>""&&(e.toUpperCase()!=e.toLowerCase()||Ra.test(e))},Oa=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
Ca=document.createRange?function(e,t,i){var r=document.createRange();r.setEnd(e,i);r.setStart(e,t);return r}:function(e,t,i){var r=document.body.createTextRange();try{r.moveToElementText(e.parentNode)}catch(n){return r}r.collapse(!0);r.moveEnd("character",i);r.moveStart("character",t);return r};ns&&11>os&&(wo=function(){try{return document.activeElement}catch(e){return document.body}});var Pa,Da,wa=e.rmClass=function(e,t){var i=e.className,r=_o(t).exec(i);if(r){var n=i.slice(r.index+r[0].length);e.className=i.slice(0,r.index)+(n?r[1]+n:"")}},_a=e.addClass=function(e,t){var i=e.className;_o(t).test(i)||(e.className+=(i?" ":"")+t)},Ma=!1,ka=function(){if(ns&&9>os)return!1;var e=bo("div");return"draggable"in e||"dragDrop"in e}(),Ga=e.splitLines=3!="\n\nb".split(/\n/).length?function(e){for(var t=0,i=[],r=e.length;r>=t;){var n=e.indexOf("\n",t);-1==n&&(n=e.length);var o=e.slice(t,"\r"==e.charAt(n-1)?n-1:n),s=o.indexOf("\r");if(-1!=s){i.push(o.slice(0,s));t+=s+1}else{i.push(o);t=n+1}}return i}:function(e){return e.split(/\r\n?|\n/)},Ba=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(t){return!1}}:function(e){try{var t=e.ownerDocument.selection.createRange()}catch(i){}return t&&t.parentElement()==e?0!=t.compareEndPoints("StartToEnd",t):!1},Ua=function(){var e=bo("div");if("oncopy"in e)return!0;e.setAttribute("oncopy","return;");return"function"==typeof e.oncopy}(),Va=null,Fa={3:"Enter",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",107:"=",109:"-",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"};e.keyNames=Fa;(function(){for(var e=0;10>e;e++)Fa[e+48]=Fa[e+96]=String(e);for(var e=65;90>=e;e++)Fa[e]=String.fromCharCode(e);for(var e=1;12>=e;e++)Fa[e+111]=Fa[e+63235]="F"+e})();var Ha,ja=function(){function e(e){return 247>=e?i.charAt(e):e>=1424&&1524>=e?"R":e>=1536&&1773>=e?r.charAt(e-1536):e>=1774&&2220>=e?"r":e>=8192&&8203>=e?"w":8204==e?"b":"L"}function t(e,t,i){this.level=e;this.from=t;this.to=i}var i="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",r="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",n=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,o=/[stwN]/,s=/[LRr]/,a=/[Lb1n]/,l=/[1n]/,u="L";return function(i){if(!n.test(i))return!1;for(var r,p=i.length,c=[],d=0;p>d;++d)c.push(r=e(i.charCodeAt(d)));for(var d=0,f=u;p>d;++d){var r=c[d];"m"==r?c[d]=f:f=r}for(var d=0,h=u;p>d;++d){var r=c[d];if("1"==r&&"r"==h)c[d]="n";else if(s.test(r)){h=r;"r"==r&&(c[d]="R")}}for(var d=1,f=c[0];p-1>d;++d){var r=c[d];"+"==r&&"1"==f&&"1"==c[d+1]?c[d]="1":","!=r||f!=c[d+1]||"1"!=f&&"n"!=f||(c[d]=f);f=r}for(var d=0;p>d;++d){var r=c[d];if(","==r)c[d]="N";else if("%"==r){for(var E=d+1;p>E&&"%"==c[E];++E);for(var m=d&&"!"==c[d-1]||p>E&&"1"==c[E]?"1":"N",g=d;E>g;++g)c[g]=m;d=E-1}}for(var d=0,h=u;p>d;++d){var r=c[d];"L"==h&&"1"==r?c[d]="L":s.test(r)&&(h=r)}for(var d=0;p>d;++d)if(o.test(c[d])){for(var E=d+1;p>E&&o.test(c[E]);++E);for(var v="L"==(d?c[d-1]:u),x="L"==(p>E?c[E]:u),m=v||x?"L":"R",g=d;E>g;++g)c[g]=m;d=E-1}for(var N,T=[],d=0;p>d;)if(a.test(c[d])){var L=d;for(++d;p>d&&a.test(c[d]);++d);T.push(new t(0,L,d))}else{var I=d,y=T.length;for(++d;p>d&&"L"!=c[d];++d);for(var g=I;d>g;)if(l.test(c[g])){g>I&&T.splice(y,0,new t(1,I,g));var A=g;for(++g;d>g&&l.test(c[g]);++g);T.splice(y,0,new t(2,A,g));I=g}else++g;d>I&&T.splice(y,0,new t(1,I,d))}if(1==T[0].level&&(N=i.match(/^\s+/))){T[0].from=N[0].length;T.unshift(new t(0,0,N[0].length))}if(1==No(T).level&&(N=i.match(/\s+$/))){No(T).to-=N[0].length;T.push(new t(0,p-N[0].length,p))}T[0].level!=No(T).level&&T.push(new t(T[0].level,p,p));return T}}();e.version="4.12.0";return e})},{}],15:[function(t,i){(function(e,t){"object"==typeof i&&"object"==typeof i.exports?i.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)})("undefined"!=typeof window?window:this,function(t,i){function r(e){var t=e.length,i=ot.type(e);return"function"===i||ot.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===i||0===t||"number"==typeof t&&t>0&&t-1 in e}function n(e,t,i){if(ot.isFunction(t))return ot.grep(e,function(e,r){return!!t.call(e,r,e)!==i});if(t.nodeType)return ot.grep(e,function(e){return e===t!==i});if("string"==typeof t){if(ft.test(t))return ot.filter(t,e,i);t=ot.filter(t,e)}return ot.grep(e,function(e){return ot.inArray(e,t)>=0!==i})}function o(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function s(e){var t=Tt[e]={};ot.each(e.match(Nt)||[],function(e,i){t[i]=!0});return t}function a(){if(Et.addEventListener){Et.removeEventListener("DOMContentLoaded",l,!1);t.removeEventListener("load",l,!1)}else{Et.detachEvent("onreadystatechange",l);t.detachEvent("onload",l)}}function l(){if(Et.addEventListener||"load"===event.type||"complete"===Et.readyState){a();ot.ready()}}function u(e,t,i){if(void 0===i&&1===e.nodeType){var r="data-"+t.replace(St,"-$1").toLowerCase();i=e.getAttribute(r);if("string"==typeof i){try{i="true"===i?!0:"false"===i?!1:"null"===i?null:+i+""===i?+i:At.test(i)?ot.parseJSON(i):i}catch(n){}ot.data(e,t,i)}else i=void 0}return i}function p(e){var t;for(t in e)if(("data"!==t||!ot.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function c(e,t,i,r){if(ot.acceptData(e)){var n,o,s=ot.expando,a=e.nodeType,l=a?ot.cache:e,u=a?e[s]:e[s]&&s;if(u&&l[u]&&(r||l[u].data)||void 0!==i||"string"!=typeof t){u||(u=a?e[s]=K.pop()||ot.guid++:s);l[u]||(l[u]=a?{}:{toJSON:ot.noop});("object"==typeof t||"function"==typeof t)&&(r?l[u]=ot.extend(l[u],t):l[u].data=ot.extend(l[u].data,t));o=l[u];if(!r){o.data||(o.data={});o=o.data}void 0!==i&&(o[ot.camelCase(t)]=i);if("string"==typeof t){n=o[t];null==n&&(n=o[ot.camelCase(t)])}else n=o;return n}}}function d(e,t,i){if(ot.acceptData(e)){var r,n,o=e.nodeType,s=o?ot.cache:e,a=o?e[ot.expando]:ot.expando;if(s[a]){if(t){r=i?s[a]:s[a].data;if(r){if(ot.isArray(t))t=t.concat(ot.map(t,ot.camelCase));else if(t in r)t=[t];else{t=ot.camelCase(t);t=t in r?[t]:t.split(" ")}n=t.length;for(;n--;)delete r[t[n]];if(i?!p(r):!ot.isEmptyObject(r))return}}if(!i){delete s[a].data;if(!p(s[a]))return}o?ot.cleanData([e],!0):rt.deleteExpando||s!=s.window?delete s[a]:s[a]=null}}}function f(){return!0}function h(){return!1}function E(){try{return Et.activeElement}catch(e){}}function m(e){var t=Gt.split("|"),i=e.createDocumentFragment();if(i.createElement)for(;t.length;)i.createElement(t.pop());return i}function g(e,t){var i,r,n=0,o=typeof e.getElementsByTagName!==yt?e.getElementsByTagName(t||"*"):typeof e.querySelectorAll!==yt?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],i=e.childNodes||e;null!=(r=i[n]);n++)!t||ot.nodeName(r,t)?o.push(r):ot.merge(o,g(r,t));return void 0===t||t&&ot.nodeName(e,t)?ot.merge([e],o):o}function v(e){Pt.test(e.type)&&(e.defaultChecked=e.checked)}function x(e,t){return ot.nodeName(e,"table")&&ot.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function N(e){e.type=(null!==ot.find.attr(e,"type"))+"/"+e.type;return e}function T(e){var t=Yt.exec(e.type);t?e.type=t[1]:e.removeAttribute("type");return e}function L(e,t){for(var i,r=0;null!=(i=e[r]);r++)ot._data(i,"globalEval",!t||ot._data(t[r],"globalEval"))}function I(e,t){if(1===t.nodeType&&ot.hasData(e)){var i,r,n,o=ot._data(e),s=ot._data(t,o),a=o.events;if(a){delete s.handle;s.events={};for(i in a)for(r=0,n=a[i].length;n>r;r++)ot.event.add(t,i,a[i][r])}s.data&&(s.data=ot.extend({},s.data))}}function y(e,t){var i,r,n;if(1===t.nodeType){i=t.nodeName.toLowerCase();if(!rt.noCloneEvent&&t[ot.expando]){n=ot._data(t);for(r in n.events)ot.removeEvent(t,r,n.handle);t.removeAttribute(ot.expando)}if("script"===i&&t.text!==e.text){N(t).text=e.text;T(t)}else if("object"===i){t.parentNode&&(t.outerHTML=e.outerHTML);rt.html5Clone&&e.innerHTML&&!ot.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)}else if("input"===i&&Pt.test(e.type)){t.defaultChecked=t.checked=e.checked;t.value!==e.value&&(t.value=e.value)}else"option"===i?t.defaultSelected=t.selected=e.defaultSelected:("input"===i||"textarea"===i)&&(t.defaultValue=e.defaultValue)}}function A(e,i){var r,n=ot(i.createElement(e)).appendTo(i.body),o=t.getDefaultComputedStyle&&(r=t.getDefaultComputedStyle(n[0]))?r.display:ot.css(n[0],"display");n.detach();return o}function S(e){var t=Et,i=ei[e];if(!i){i=A(e,t);if("none"===i||!i){Jt=(Jt||ot("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement);t=(Jt[0].contentWindow||Jt[0].contentDocument).document;t.write();t.close();i=A(e,t);Jt.detach()}ei[e]=i}return i}function C(e,t){return{get:function(){var i=e();if(null!=i){if(!i)return(this.get=t).apply(this,arguments);delete this.get}}}}function R(e,t){if(t in e)return t;for(var i=t.charAt(0).toUpperCase()+t.slice(1),r=t,n=fi.length;n--;){t=fi[n]+i;if(t in e)return t}return r}function b(e,t){for(var i,r,n,o=[],s=0,a=e.length;a>s;s++){r=e[s];if(r.style){o[s]=ot._data(r,"olddisplay");i=r.style.display;if(t){o[s]||"none"!==i||(r.style.display="");""===r.style.display&&bt(r)&&(o[s]=ot._data(r,"olddisplay",S(r.nodeName)))}else{n=bt(r);(i&&"none"!==i||!n)&&ot._data(r,"olddisplay",n?i:ot.css(r,"display"))}}}for(s=0;a>s;s++){r=e[s];r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[s]||"":"none"))}return e}function O(e,t,i){var r=ui.exec(t);return r?Math.max(0,r[1]-(i||0))+(r[2]||"px"):t}function P(e,t,i,r,n){for(var o=i===(r?"border":"content")?4:"width"===t?1:0,s=0;4>o;o+=2){"margin"===i&&(s+=ot.css(e,i+Rt[o],!0,n));if(r){"content"===i&&(s-=ot.css(e,"padding"+Rt[o],!0,n));"margin"!==i&&(s-=ot.css(e,"border"+Rt[o]+"Width",!0,n))}else{s+=ot.css(e,"padding"+Rt[o],!0,n);"padding"!==i&&(s+=ot.css(e,"border"+Rt[o]+"Width",!0,n))}}return s}function D(e,t,i){var r=!0,n="width"===t?e.offsetWidth:e.offsetHeight,o=ti(e),s=rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,o);if(0>=n||null==n){n=ii(e,t,o);(0>n||null==n)&&(n=e.style[t]);if(ni.test(n))return n;r=s&&(rt.boxSizingReliable()||n===e.style[t]);n=parseFloat(n)||0}return n+P(e,t,i||(s?"border":"content"),r,o)+"px"}function w(e,t,i,r,n){return new w.prototype.init(e,t,i,r,n)}function _(){setTimeout(function(){hi=void 0});return hi=ot.now()}function M(e,t){var i,r={height:e},n=0;t=t?1:0;for(;4>n;n+=2-t){i=Rt[n];r["margin"+i]=r["padding"+i]=e}t&&(r.opacity=r.width=e);return r}function k(e,t,i){for(var r,n=(Ni[t]||[]).concat(Ni["*"]),o=0,s=n.length;s>o;o++)if(r=n[o].call(i,t,e))return r}function G(e,t,i){var r,n,o,s,a,l,u,p,c=this,d={},f=e.style,h=e.nodeType&&bt(e),E=ot._data(e,"fxshow");if(!i.queue){a=ot._queueHooks(e,"fx");if(null==a.unqueued){a.unqueued=0;l=a.empty.fire;a.empty.fire=function(){a.unqueued||l()}}a.unqueued++;c.always(function(){c.always(function(){a.unqueued--;ot.queue(e,"fx").length||a.empty.fire()})})}if(1===e.nodeType&&("height"in t||"width"in t)){i.overflow=[f.overflow,f.overflowX,f.overflowY];u=ot.css(e,"display");p="none"===u?ot._data(e,"olddisplay")||S(e.nodeName):u;"inline"===p&&"none"===ot.css(e,"float")&&(rt.inlineBlockNeedsLayout&&"inline"!==S(e.nodeName)?f.zoom=1:f.display="inline-block")}if(i.overflow){f.overflow="hidden";rt.shrinkWrapBlocks()||c.always(function(){f.overflow=i.overflow[0];f.overflowX=i.overflow[1];f.overflowY=i.overflow[2]})}for(r in t){n=t[r];if(mi.exec(n)){delete t[r];o=o||"toggle"===n;if(n===(h?"hide":"show")){if("show"!==n||!E||void 0===E[r])continue;h=!0}d[r]=E&&E[r]||ot.style(e,r)}else u=void 0}if(ot.isEmptyObject(d))"inline"===("none"===u?S(e.nodeName):u)&&(f.display=u);else{E?"hidden"in E&&(h=E.hidden):E=ot._data(e,"fxshow",{});o&&(E.hidden=!h);h?ot(e).show():c.done(function(){ot(e).hide()});c.done(function(){var t;ot._removeData(e,"fxshow");for(t in d)ot.style(e,t,d[t])});for(r in d){s=k(h?E[r]:0,r,c);if(!(r in E)){E[r]=s.start;if(h){s.end=s.start;s.start="width"===r||"height"===r?1:0}}}}}function B(e,t){var i,r,n,o,s;for(i in e){r=ot.camelCase(i);n=t[r];o=e[i];if(ot.isArray(o)){n=o[1];o=e[i]=o[0]}if(i!==r){e[r]=o;delete e[i]}s=ot.cssHooks[r];if(s&&"expand"in s){o=s.expand(o);delete e[r];for(i in o)if(!(i in e)){e[i]=o[i];t[i]=n}}else t[r]=n}}function U(e,t,i){var r,n,o=0,s=xi.length,a=ot.Deferred().always(function(){delete l.elem}),l=function(){if(n)return!1;for(var t=hi||_(),i=Math.max(0,u.startTime+u.duration-t),r=i/u.duration||0,o=1-r,s=0,l=u.tweens.length;l>s;s++)u.tweens[s].run(o);a.notifyWith(e,[u,o,i]);if(1>o&&l)return i;a.resolveWith(e,[u]);return!1},u=a.promise({elem:e,props:ot.extend({},t),opts:ot.extend(!0,{specialEasing:{}},i),originalProperties:t,originalOptions:i,startTime:hi||_(),duration:i.duration,tweens:[],createTween:function(t,i){var r=ot.Tween(e,u.opts,t,i,u.opts.specialEasing[t]||u.opts.easing);u.tweens.push(r);return r},stop:function(t){var i=0,r=t?u.tweens.length:0;if(n)return this;n=!0;for(;r>i;i++)u.tweens[i].run(1);t?a.resolveWith(e,[u,t]):a.rejectWith(e,[u,t]);return this}}),p=u.props;B(p,u.opts.specialEasing);for(;s>o;o++){r=xi[o].call(u,e,p,u.opts);if(r)return r}ot.map(p,k,u);ot.isFunction(u.opts.start)&&u.opts.start.call(e,u);ot.fx.timer(ot.extend(l,{elem:e,anim:u,queue:u.opts.queue}));return u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function V(e){return function(t,i){if("string"!=typeof t){i=t;t="*"}var r,n=0,o=t.toLowerCase().match(Nt)||[];if(ot.isFunction(i))for(;r=o[n++];)if("+"===r.charAt(0)){r=r.slice(1)||"*";(e[r]=e[r]||[]).unshift(i)}else(e[r]=e[r]||[]).push(i)}}function F(e,t,i,r){function n(a){var l;o[a]=!0;ot.each(e[a]||[],function(e,a){var u=a(t,i,r);if("string"==typeof u&&!s&&!o[u]){t.dataTypes.unshift(u);n(u);return!1}return s?!(l=u):void 0});return l}var o={},s=e===Wi;return n(t.dataTypes[0])||!o["*"]&&n("*")}function H(e,t){var i,r,n=ot.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((n[r]?e:i||(i={}))[r]=t[r]);i&&ot.extend(!0,e,i);return e}function j(e,t,i){for(var r,n,o,s,a=e.contents,l=e.dataTypes;"*"===l[0];){l.shift();void 0===n&&(n=e.mimeType||t.getResponseHeader("Content-Type"))}if(n)for(s in a)if(a[s]&&a[s].test(n)){l.unshift(s);break}if(l[0]in i)o=l[0];else{for(s in i){if(!l[0]||e.converters[s+" "+l[0]]){o=s;break}r||(r=s)}o=o||r}if(o){o!==l[0]&&l.unshift(o);return i[o]}}function W(e,t,i,r){var n,o,s,a,l,u={},p=e.dataTypes.slice();if(p[1])for(s in e.converters)u[s.toLowerCase()]=e.converters[s];o=p.shift();for(;o;){e.responseFields[o]&&(i[e.responseFields[o]]=t);!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType));l=o;o=p.shift();if(o)if("*"===o)o=l;else if("*"!==l&&l!==o){s=u[l+" "+o]||u["* "+o];if(!s)for(n in u){a=n.split(" ");if(a[1]===o){s=u[l+" "+a[0]]||u["* "+a[0]];if(s){if(s===!0)s=u[n];else if(u[n]!==!0){o=a[0];p.unshift(a[1])}break}}}if(s!==!0)if(s&&e["throws"])t=s(t);else try{t=s(t)}catch(c){return{state:"parsererror",error:s?c:"No conversion from "+l+" to "+o}}}}return{state:"success",data:t}}function q(e,t,i,r){var n;if(ot.isArray(t))ot.each(t,function(t,n){i||Yi.test(e)?r(e,n):q(e+"["+("object"==typeof n?t:"")+"]",n,i,r)});else if(i||"object"!==ot.type(t))r(e,t);else for(n in t)q(e+"["+n+"]",t[n],i,r)}function z(){try{return new t.XMLHttpRequest}catch(e){}}function X(){try{return new t.ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}function Y(e){return ot.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var K=[],$=K.slice,Q=K.concat,Z=K.push,J=K.indexOf,et={},tt=et.toString,it=et.hasOwnProperty,rt={},nt="1.11.2",ot=function(e,t){return new ot.fn.init(e,t)},st=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,at=/^-ms-/,lt=/-([\da-z])/gi,ut=function(e,t){return t.toUpperCase()};ot.fn=ot.prototype={jquery:nt,constructor:ot,selector:"",length:0,toArray:function(){return $.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:$.call(this)},pushStack:function(e){var t=ot.merge(this.constructor(),e);t.prevObject=this;t.context=this.context;return t},each:function(e,t){return ot.each(this,e,t)},map:function(e){return this.pushStack(ot.map(this,function(t,i){return e.call(t,i,t)}))},slice:function(){return this.pushStack($.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,i=+e+(0>e?t:0);return this.pushStack(i>=0&&t>i?[this[i]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:Z,sort:K.sort,splice:K.splice};ot.extend=ot.fn.extend=function(){var e,t,i,r,n,o,s=arguments[0]||{},a=1,l=arguments.length,u=!1;if("boolean"==typeof s){u=s;s=arguments[a]||{};a++}"object"==typeof s||ot.isFunction(s)||(s={});if(a===l){s=this;a--}for(;l>a;a++)if(null!=(n=arguments[a]))for(r in n){e=s[r];i=n[r];if(s!==i)if(u&&i&&(ot.isPlainObject(i)||(t=ot.isArray(i)))){if(t){t=!1;o=e&&ot.isArray(e)?e:[]}else o=e&&ot.isPlainObject(e)?e:{};s[r]=ot.extend(u,o,i)}else void 0!==i&&(s[r]=i)}return s};ot.extend({expando:"jQuery"+(nt+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===ot.type(e)},isArray:Array.isArray||function(e){return"array"===ot.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!ot.isArray(e)&&e-parseFloat(e)+1>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==ot.type(e)||e.nodeType||ot.isWindow(e))return!1;try{if(e.constructor&&!it.call(e,"constructor")&&!it.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(i){return!1}if(rt.ownLast)for(t in e)return it.call(e,t);for(t in e);return void 0===t||it.call(e,t)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?et[tt.call(e)]||"object":typeof e},globalEval:function(e){e&&ot.trim(e)&&(t.execScript||function(e){t.eval.call(t,e)})(e)},camelCase:function(e){return e.replace(at,"ms-").replace(lt,ut)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,i){var n,o=0,s=e.length,a=r(e);if(i)if(a)for(;s>o;o++){n=t.apply(e[o],i);if(n===!1)break}else for(o in e){n=t.apply(e[o],i);if(n===!1)break}else if(a)for(;s>o;o++){n=t.call(e[o],o,e[o]);if(n===!1)break}else for(o in e){n=t.call(e[o],o,e[o]);if(n===!1)break}return e},trim:function(e){return null==e?"":(e+"").replace(st,"")},makeArray:function(e,t){var i=t||[];null!=e&&(r(Object(e))?ot.merge(i,"string"==typeof e?[e]:e):Z.call(i,e));return i},inArray:function(e,t,i){var r;if(t){if(J)return J.call(t,e,i);r=t.length;i=i?0>i?Math.max(0,r+i):i:0;for(;r>i;i++)if(i in t&&t[i]===e)return i}return-1},merge:function(e,t){for(var i=+t.length,r=0,n=e.length;i>r;)e[n++]=t[r++];if(i!==i)for(;void 0!==t[r];)e[n++]=t[r++];e.length=n;return e},grep:function(e,t,i){for(var r,n=[],o=0,s=e.length,a=!i;s>o;o++){r=!t(e[o],o);r!==a&&n.push(e[o])}return n},map:function(e,t,i){var n,o=0,s=e.length,a=r(e),l=[];if(a)for(;s>o;o++){n=t(e[o],o,i);null!=n&&l.push(n)}else for(o in e){n=t(e[o],o,i);null!=n&&l.push(n)}return Q.apply([],l)},guid:1,proxy:function(e,t){var i,r,n;if("string"==typeof t){n=e[t];t=e;e=n}if(!ot.isFunction(e))return void 0;i=$.call(arguments,2);r=function(){return e.apply(t||this,i.concat($.call(arguments)))};r.guid=e.guid=e.guid||ot.guid++;return r},now:function(){return+new Date},support:rt});ot.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){et["[object "+t+"]"]=t.toLowerCase()});var pt=function(e){function t(e,t,i,r){var n,o,s,a,l,u,c,f,h,E;(t?t.ownerDocument||t:V)!==D&&P(t);t=t||D;i=i||[];a=t.nodeType;if("string"!=typeof e||!e||1!==a&&9!==a&&11!==a)return i;if(!r&&_){if(11!==a&&(n=vt.exec(e)))if(s=n[1]){if(9===a){o=t.getElementById(s);if(!o||!o.parentNode)return i;if(o.id===s){i.push(o);return i}}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(s))&&B(t,o)&&o.id===s){i.push(o);return i}}else{if(n[2]){Z.apply(i,t.getElementsByTagName(e));return i}if((s=n[3])&&T.getElementsByClassName){Z.apply(i,t.getElementsByClassName(s));return i}}if(T.qsa&&(!M||!M.test(e))){f=c=U;h=t;E=1!==a&&e;if(1===a&&"object"!==t.nodeName.toLowerCase()){u=A(e);(c=t.getAttribute("id"))?f=c.replace(Nt,"\\$&"):t.setAttribute("id",f);f="[id='"+f+"'] ";l=u.length;for(;l--;)u[l]=f+d(u[l]);h=xt.test(e)&&p(t.parentNode)||t;E=u.join(",")}if(E)try{Z.apply(i,h.querySelectorAll(E));return i}catch(m){}finally{c||t.removeAttribute("id")}}}return C(e.replace(lt,"$1"),t,i,r)}function i(){function e(i,r){t.push(i+" ")>L.cacheLength&&delete e[t.shift()];return e[i+" "]=r}var t=[];return e}function r(e){e[U]=!0;return e}function n(e){var t=D.createElement("div");try{return!!e(t)}catch(i){return!1}finally{t.parentNode&&t.parentNode.removeChild(t);t=null}}function o(e,t){for(var i=e.split("|"),r=e.length;r--;)L.attrHandle[i[r]]=t}function s(e,t){var i=t&&e,r=i&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||X)-(~e.sourceIndex||X);if(r)return r;if(i)for(;i=i.nextSibling;)if(i===t)return-1;return e?1:-1}function a(e){return function(t){var i=t.nodeName.toLowerCase();return"input"===i&&t.type===e}}function l(e){return function(t){var i=t.nodeName.toLowerCase();return("input"===i||"button"===i)&&t.type===e}}function u(e){return r(function(t){t=+t;return r(function(i,r){for(var n,o=e([],i.length,t),s=o.length;s--;)i[n=o[s]]&&(i[n]=!(r[n]=i[n]))})})}function p(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function c(){}function d(e){for(var t=0,i=e.length,r="";i>t;t++)r+=e[t].value;return r}function f(e,t,i){var r=t.dir,n=i&&"parentNode"===r,o=H++;return t.first?function(t,i,o){for(;t=t[r];)if(1===t.nodeType||n)return e(t,i,o)}:function(t,i,s){var a,l,u=[F,o];if(s){for(;t=t[r];)if((1===t.nodeType||n)&&e(t,i,s))return!0}else for(;t=t[r];)if(1===t.nodeType||n){l=t[U]||(t[U]={});if((a=l[r])&&a[0]===F&&a[1]===o)return u[2]=a[2];l[r]=u;if(u[2]=e(t,i,s))return!0}}}function h(e){return e.length>1?function(t,i,r){for(var n=e.length;n--;)if(!e[n](t,i,r))return!1;return!0}:e[0]}function E(e,i,r){for(var n=0,o=i.length;o>n;n++)t(e,i[n],r);return r}function m(e,t,i,r,n){for(var o,s=[],a=0,l=e.length,u=null!=t;l>a;a++)if((o=e[a])&&(!i||i(o,r,n))){s.push(o);u&&t.push(a)}return s}function g(e,t,i,n,o,s){n&&!n[U]&&(n=g(n));o&&!o[U]&&(o=g(o,s));return r(function(r,s,a,l){var u,p,c,d=[],f=[],h=s.length,g=r||E(t||"*",a.nodeType?[a]:a,[]),v=!e||!r&&t?g:m(g,d,e,a,l),x=i?o||(r?e:h||n)?[]:s:v;i&&i(v,x,a,l);if(n){u=m(x,f);n(u,[],a,l);p=u.length;for(;p--;)(c=u[p])&&(x[f[p]]=!(v[f[p]]=c))}if(r){if(o||e){if(o){u=[];p=x.length;for(;p--;)(c=x[p])&&u.push(v[p]=c);o(null,x=[],u,l)}p=x.length;for(;p--;)(c=x[p])&&(u=o?et(r,c):d[p])>-1&&(r[u]=!(s[u]=c))}}else{x=m(x===s?x.splice(h,x.length):x);o?o(null,s,x,l):Z.apply(s,x)}})}function v(e){for(var t,i,r,n=e.length,o=L.relative[e[0].type],s=o||L.relative[" "],a=o?1:0,l=f(function(e){return e===t},s,!0),u=f(function(e){return et(t,e)>-1},s,!0),p=[function(e,i,r){var n=!o&&(r||i!==R)||((t=i).nodeType?l(e,i,r):u(e,i,r));t=null;return n}];n>a;a++)if(i=L.relative[e[a].type])p=[f(h(p),i)];else{i=L.filter[e[a].type].apply(null,e[a].matches);if(i[U]){r=++a;for(;n>r&&!L.relative[e[r].type];r++);return g(a>1&&h(p),a>1&&d(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(lt,"$1"),i,r>a&&v(e.slice(a,r)),n>r&&v(e=e.slice(r)),n>r&&d(e))}p.push(i)}return h(p)}function x(e,i){var n=i.length>0,o=e.length>0,s=function(r,s,a,l,u){var p,c,d,f=0,h="0",E=r&&[],g=[],v=R,x=r||o&&L.find.TAG("*",u),N=F+=null==v?1:Math.random()||.1,T=x.length;u&&(R=s!==D&&s);for(;h!==T&&null!=(p=x[h]);h++){if(o&&p){c=0;for(;d=e[c++];)if(d(p,s,a)){l.push(p);break}u&&(F=N)}if(n){(p=!d&&p)&&f--;r&&E.push(p)}}f+=h;if(n&&h!==f){c=0;for(;d=i[c++];)d(E,g,s,a);if(r){if(f>0)for(;h--;)E[h]||g[h]||(g[h]=$.call(l));g=m(g)}Z.apply(l,g);u&&!r&&g.length>0&&f+i.length>1&&t.uniqueSort(l)}if(u){F=N;R=v}return E};return n?r(s):s}var N,T,L,I,y,A,S,C,R,b,O,P,D,w,_,M,k,G,B,U="sizzle"+1*new Date,V=e.document,F=0,H=0,j=i(),W=i(),q=i(),z=function(e,t){e===t&&(O=!0);return 0},X=1<<31,Y={}.hasOwnProperty,K=[],$=K.pop,Q=K.push,Z=K.push,J=K.slice,et=function(e,t){for(var i=0,r=e.length;r>i;i++)if(e[i]===t)return i;return-1},tt="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",it="[\\x20\\t\\r\\n\\f]",rt="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",nt=rt.replace("w","w#"),ot="\\["+it+"*("+rt+")(?:"+it+"*([*^$|!~]?=)"+it+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+nt+"))|)"+it+"*\\]",st=":("+rt+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+ot+")*)|.*)\\)|)",at=new RegExp(it+"+","g"),lt=new RegExp("^"+it+"+|((?:^|[^\\\\])(?:\\\\.)*)"+it+"+$","g"),ut=new RegExp("^"+it+"*,"+it+"*"),pt=new RegExp("^"+it+"*([>+~]|"+it+")"+it+"*"),ct=new RegExp("="+it+"*([^\\]'\"]*?)"+it+"*\\]","g"),dt=new RegExp(st),ft=new RegExp("^"+nt+"$"),ht={ID:new RegExp("^#("+rt+")"),CLASS:new RegExp("^\\.("+rt+")"),TAG:new RegExp("^("+rt.replace("w","w*")+")"),ATTR:new RegExp("^"+ot),PSEUDO:new RegExp("^"+st),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+it+"*(even|odd|(([+-]|)(\\d*)n|)"+it+"*(?:([+-]|)"+it+"*(\\d+)|))"+it+"*\\)|)","i"),bool:new RegExp("^(?:"+tt+")$","i"),needsContext:new RegExp("^"+it+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+it+"*((?:-\\d)?\\d*)"+it+"*\\)|)(?=[^-]|$)","i")},Et=/^(?:input|select|textarea|button)$/i,mt=/^h\d$/i,gt=/^[^{]+\{\s*\[native \w/,vt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,xt=/[+~]/,Nt=/'|\\/g,Tt=new RegExp("\\\\([\\da-f]{1,6}"+it+"?|("+it+")|.)","ig"),Lt=function(e,t,i){var r="0x"+t-65536;return r!==r||i?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},It=function(){P()};try{Z.apply(K=J.call(V.childNodes),V.childNodes);K[V.childNodes.length].nodeType}catch(yt){Z={apply:K.length?function(e,t){Q.apply(e,J.call(t))}:function(e,t){for(var i=e.length,r=0;e[i++]=t[r++];);e.length=i-1}}}T=t.support={};y=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1};P=t.setDocument=function(e){var t,i,r=e?e.ownerDocument||e:V;if(r===D||9!==r.nodeType||!r.documentElement)return D;D=r;w=r.documentElement;i=r.defaultView;i&&i!==i.top&&(i.addEventListener?i.addEventListener("unload",It,!1):i.attachEvent&&i.attachEvent("onunload",It));_=!y(r);T.attributes=n(function(e){e.className="i";return!e.getAttribute("className")});T.getElementsByTagName=n(function(e){e.appendChild(r.createComment(""));return!e.getElementsByTagName("*").length});T.getElementsByClassName=gt.test(r.getElementsByClassName);T.getById=n(function(e){w.appendChild(e).id=U;return!r.getElementsByName||!r.getElementsByName(U).length});if(T.getById){L.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&_){var i=t.getElementById(e);return i&&i.parentNode?[i]:[]}};L.filter.ID=function(e){var t=e.replace(Tt,Lt);return function(e){return e.getAttribute("id")===t}}}else{delete L.find.ID;L.filter.ID=function(e){var t=e.replace(Tt,Lt);return function(e){var i="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return i&&i.value===t}}}L.find.TAG=T.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):T.qsa?t.querySelectorAll(e):void 0}:function(e,t){var i,r=[],n=0,o=t.getElementsByTagName(e);if("*"===e){for(;i=o[n++];)1===i.nodeType&&r.push(i);return r}return o};L.find.CLASS=T.getElementsByClassName&&function(e,t){return _?t.getElementsByClassName(e):void 0};k=[];M=[];if(T.qsa=gt.test(r.querySelectorAll)){n(function(e){w.appendChild(e).innerHTML="<a id='"+U+"'></a><select id='"+U+"-\f]' msallowcapture=''><option selected=''></option></select>";e.querySelectorAll("[msallowcapture^='']").length&&M.push("[*^$]="+it+"*(?:''|\"\")");e.querySelectorAll("[selected]").length||M.push("\\["+it+"*(?:value|"+tt+")");e.querySelectorAll("[id~="+U+"-]").length||M.push("~=");e.querySelectorAll(":checked").length||M.push(":checked");e.querySelectorAll("a#"+U+"+*").length||M.push(".#.+[+~]")});n(function(e){var t=r.createElement("input");t.setAttribute("type","hidden");e.appendChild(t).setAttribute("name","D");e.querySelectorAll("[name=d]").length&&M.push("name"+it+"*[*^$|!~]?=");e.querySelectorAll(":enabled").length||M.push(":enabled",":disabled");e.querySelectorAll("*,:x");M.push(",.*:")})}(T.matchesSelector=gt.test(G=w.matches||w.webkitMatchesSelector||w.mozMatchesSelector||w.oMatchesSelector||w.msMatchesSelector))&&n(function(e){T.disconnectedMatch=G.call(e,"div");G.call(e,"[s!='']:x");k.push("!=",st)});M=M.length&&new RegExp(M.join("|"));k=k.length&&new RegExp(k.join("|"));t=gt.test(w.compareDocumentPosition);B=t||gt.test(w.contains)?function(e,t){var i=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(i.contains?i.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1};z=t?function(e,t){if(e===t){O=!0;return 0}var i=!e.compareDocumentPosition-!t.compareDocumentPosition;if(i)return i;i=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1;return 1&i||!T.sortDetached&&t.compareDocumentPosition(e)===i?e===r||e.ownerDocument===V&&B(V,e)?-1:t===r||t.ownerDocument===V&&B(V,t)?1:b?et(b,e)-et(b,t):0:4&i?-1:1}:function(e,t){if(e===t){O=!0;return 0}var i,n=0,o=e.parentNode,a=t.parentNode,l=[e],u=[t];if(!o||!a)return e===r?-1:t===r?1:o?-1:a?1:b?et(b,e)-et(b,t):0;if(o===a)return s(e,t);i=e;for(;i=i.parentNode;)l.unshift(i);i=t;for(;i=i.parentNode;)u.unshift(i);for(;l[n]===u[n];)n++;return n?s(l[n],u[n]):l[n]===V?-1:u[n]===V?1:0};return r};t.matches=function(e,i){return t(e,null,null,i)};t.matchesSelector=function(e,i){(e.ownerDocument||e)!==D&&P(e);i=i.replace(ct,"='$1']");if(!(!T.matchesSelector||!_||k&&k.test(i)||M&&M.test(i)))try{var r=G.call(e,i);if(r||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(n){}return t(i,D,null,[e]).length>0};t.contains=function(e,t){(e.ownerDocument||e)!==D&&P(e);return B(e,t)};t.attr=function(e,t){(e.ownerDocument||e)!==D&&P(e);var i=L.attrHandle[t.toLowerCase()],r=i&&Y.call(L.attrHandle,t.toLowerCase())?i(e,t,!_):void 0;return void 0!==r?r:T.attributes||!_?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null};t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)};t.uniqueSort=function(e){var t,i=[],r=0,n=0;O=!T.detectDuplicates;b=!T.sortStable&&e.slice(0);e.sort(z);if(O){for(;t=e[n++];)t===e[n]&&(r=i.push(n));for(;r--;)e.splice(i[r],1)}b=null;return e};I=t.getText=function(e){var t,i="",r=0,n=e.nodeType;if(n){if(1===n||9===n||11===n){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)i+=I(e)}else if(3===n||4===n)return e.nodeValue}else for(;t=e[r++];)i+=I(t);return i};L=t.selectors={cacheLength:50,createPseudo:r,match:ht,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){e[1]=e[1].replace(Tt,Lt);e[3]=(e[3]||e[4]||e[5]||"").replace(Tt,Lt);"~="===e[2]&&(e[3]=" "+e[3]+" ");return e.slice(0,4)},CHILD:function(e){e[1]=e[1].toLowerCase();if("nth"===e[1].slice(0,3)){e[3]||t.error(e[0]);e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3]));e[5]=+(e[7]+e[8]||"odd"===e[3])}else e[3]&&t.error(e[0]);return e},PSEUDO:function(e){var t,i=!e[6]&&e[2];
if(ht.CHILD.test(e[0]))return null;if(e[3])e[2]=e[4]||e[5]||"";else if(i&&dt.test(i)&&(t=A(i,!0))&&(t=i.indexOf(")",i.length-t)-i.length)){e[0]=e[0].slice(0,t);e[2]=i.slice(0,t)}return e.slice(0,3)}},filter:{TAG:function(e){var t=e.replace(Tt,Lt).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=j[e+" "];return t||(t=new RegExp("(^|"+it+")"+e+"("+it+"|$)"))&&j(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,i,r){return function(n){var o=t.attr(n,e);if(null==o)return"!="===i;if(!i)return!0;o+="";return"="===i?o===r:"!="===i?o!==r:"^="===i?r&&0===o.indexOf(r):"*="===i?r&&o.indexOf(r)>-1:"$="===i?r&&o.slice(-r.length)===r:"~="===i?(" "+o.replace(at," ")+" ").indexOf(r)>-1:"|="===i?o===r||o.slice(0,r.length+1)===r+"-":!1}},CHILD:function(e,t,i,r,n){var o="nth"!==e.slice(0,3),s="last"!==e.slice(-4),a="of-type"===t;return 1===r&&0===n?function(e){return!!e.parentNode}:function(t,i,l){var u,p,c,d,f,h,E=o!==s?"nextSibling":"previousSibling",m=t.parentNode,g=a&&t.nodeName.toLowerCase(),v=!l&&!a;if(m){if(o){for(;E;){c=t;for(;c=c[E];)if(a?c.nodeName.toLowerCase()===g:1===c.nodeType)return!1;h=E="only"===e&&!h&&"nextSibling"}return!0}h=[s?m.firstChild:m.lastChild];if(s&&v){p=m[U]||(m[U]={});u=p[e]||[];f=u[0]===F&&u[1];d=u[0]===F&&u[2];c=f&&m.childNodes[f];for(;c=++f&&c&&c[E]||(d=f=0)||h.pop();)if(1===c.nodeType&&++d&&c===t){p[e]=[F,f,d];break}}else if(v&&(u=(t[U]||(t[U]={}))[e])&&u[0]===F)d=u[1];else for(;c=++f&&c&&c[E]||(d=f=0)||h.pop();)if((a?c.nodeName.toLowerCase()===g:1===c.nodeType)&&++d){v&&((c[U]||(c[U]={}))[e]=[F,d]);if(c===t)break}d-=n;return d===r||d%r===0&&d/r>=0}}},PSEUDO:function(e,i){var n,o=L.pseudos[e]||L.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);if(o[U])return o(i);if(o.length>1){n=[e,e,"",i];return L.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,t){for(var r,n=o(e,i),s=n.length;s--;){r=et(e,n[s]);e[r]=!(t[r]=n[s])}}):function(e){return o(e,0,n)}}return o}},pseudos:{not:r(function(e){var t=[],i=[],n=S(e.replace(lt,"$1"));return n[U]?r(function(e,t,i,r){for(var o,s=n(e,null,r,[]),a=e.length;a--;)(o=s[a])&&(e[a]=!(t[a]=o))}):function(e,r,o){t[0]=e;n(t,null,o,i);t[0]=null;return!i.pop()}}),has:r(function(e){return function(i){return t(e,i).length>0}}),contains:r(function(e){e=e.replace(Tt,Lt);return function(t){return(t.textContent||t.innerText||I(t)).indexOf(e)>-1}}),lang:r(function(e){ft.test(e||"")||t.error("unsupported lang: "+e);e=e.replace(Tt,Lt).toLowerCase();return function(t){var i;do if(i=_?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang")){i=i.toLowerCase();return i===e||0===i.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var i=e.location&&e.location.hash;return i&&i.slice(1)===t.id},root:function(e){return e===w},focus:function(e){return e===D.activeElement&&(!D.hasFocus||D.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){e.parentNode&&e.parentNode.selectedIndex;return e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!L.pseudos.empty(e)},header:function(e){return mt.test(e.nodeName)},input:function(e){return Et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,i){return[0>i?i+t:i]}),even:u(function(e,t){for(var i=0;t>i;i+=2)e.push(i);return e}),odd:u(function(e,t){for(var i=1;t>i;i+=2)e.push(i);return e}),lt:u(function(e,t,i){for(var r=0>i?i+t:i;--r>=0;)e.push(r);return e}),gt:u(function(e,t,i){for(var r=0>i?i+t:i;++r<t;)e.push(r);return e})}};L.pseudos.nth=L.pseudos.eq;for(N in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})L.pseudos[N]=a(N);for(N in{submit:!0,reset:!0})L.pseudos[N]=l(N);c.prototype=L.filters=L.pseudos;L.setFilters=new c;A=t.tokenize=function(e,i){var r,n,o,s,a,l,u,p=W[e+" "];if(p)return i?0:p.slice(0);a=e;l=[];u=L.preFilter;for(;a;){if(!r||(n=ut.exec(a))){n&&(a=a.slice(n[0].length)||a);l.push(o=[])}r=!1;if(n=pt.exec(a)){r=n.shift();o.push({value:r,type:n[0].replace(lt," ")});a=a.slice(r.length)}for(s in L.filter)if((n=ht[s].exec(a))&&(!u[s]||(n=u[s](n)))){r=n.shift();o.push({value:r,type:s,matches:n});a=a.slice(r.length)}if(!r)break}return i?a.length:a?t.error(e):W(e,l).slice(0)};S=t.compile=function(e,t){var i,r=[],n=[],o=q[e+" "];if(!o){t||(t=A(e));i=t.length;for(;i--;){o=v(t[i]);o[U]?r.push(o):n.push(o)}o=q(e,x(n,r));o.selector=e}return o};C=t.select=function(e,t,i,r){var n,o,s,a,l,u="function"==typeof e&&e,c=!r&&A(e=u.selector||e);i=i||[];if(1===c.length){o=c[0]=c[0].slice(0);if(o.length>2&&"ID"===(s=o[0]).type&&T.getById&&9===t.nodeType&&_&&L.relative[o[1].type]){t=(L.find.ID(s.matches[0].replace(Tt,Lt),t)||[])[0];if(!t)return i;u&&(t=t.parentNode);e=e.slice(o.shift().value.length)}n=ht.needsContext.test(e)?0:o.length;for(;n--;){s=o[n];if(L.relative[a=s.type])break;if((l=L.find[a])&&(r=l(s.matches[0].replace(Tt,Lt),xt.test(o[0].type)&&p(t.parentNode)||t))){o.splice(n,1);e=r.length&&d(o);if(!e){Z.apply(i,r);return i}break}}}(u||S(e,c))(r,t,!_,i,xt.test(e)&&p(t.parentNode)||t);return i};T.sortStable=U.split("").sort(z).join("")===U;T.detectDuplicates=!!O;P();T.sortDetached=n(function(e){return 1&e.compareDocumentPosition(D.createElement("div"))});n(function(e){e.innerHTML="<a href='#'></a>";return"#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,i){return i?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)});T.attributes&&n(function(e){e.innerHTML="<input/>";e.firstChild.setAttribute("value","");return""===e.firstChild.getAttribute("value")})||o("value",function(e,t,i){return i||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue});n(function(e){return null==e.getAttribute("disabled")})||o(tt,function(e,t,i){var r;return i?void 0:e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null});return t}(t);ot.find=pt;ot.expr=pt.selectors;ot.expr[":"]=ot.expr.pseudos;ot.unique=pt.uniqueSort;ot.text=pt.getText;ot.isXMLDoc=pt.isXML;ot.contains=pt.contains;var ct=ot.expr.match.needsContext,dt=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,ft=/^.[^:#\[\.,]*$/;ot.filter=function(e,t,i){var r=t[0];i&&(e=":not("+e+")");return 1===t.length&&1===r.nodeType?ot.find.matchesSelector(r,e)?[r]:[]:ot.find.matches(e,ot.grep(t,function(e){return 1===e.nodeType}))};ot.fn.extend({find:function(e){var t,i=[],r=this,n=r.length;if("string"!=typeof e)return this.pushStack(ot(e).filter(function(){for(t=0;n>t;t++)if(ot.contains(r[t],this))return!0}));for(t=0;n>t;t++)ot.find(e,r[t],i);i=this.pushStack(n>1?ot.unique(i):i);i.selector=this.selector?this.selector+" "+e:e;return i},filter:function(e){return this.pushStack(n(this,e||[],!1))},not:function(e){return this.pushStack(n(this,e||[],!0))},is:function(e){return!!n(this,"string"==typeof e&&ct.test(e)?ot(e):e||[],!1).length}});var ht,Et=t.document,mt=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,gt=ot.fn.init=function(e,t){var i,r;if(!e)return this;if("string"==typeof e){i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:mt.exec(e);if(!i||!i[1]&&t)return!t||t.jquery?(t||ht).find(e):this.constructor(t).find(e);if(i[1]){t=t instanceof ot?t[0]:t;ot.merge(this,ot.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:Et,!0));if(dt.test(i[1])&&ot.isPlainObject(t))for(i in t)ot.isFunction(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}r=Et.getElementById(i[2]);if(r&&r.parentNode){if(r.id!==i[2])return ht.find(e);this.length=1;this[0]=r}this.context=Et;this.selector=e;return this}if(e.nodeType){this.context=this[0]=e;this.length=1;return this}if(ot.isFunction(e))return"undefined"!=typeof ht.ready?ht.ready(e):e(ot);if(void 0!==e.selector){this.selector=e.selector;this.context=e.context}return ot.makeArray(e,this)};gt.prototype=ot.fn;ht=ot(Et);var vt=/^(?:parents|prev(?:Until|All))/,xt={children:!0,contents:!0,next:!0,prev:!0};ot.extend({dir:function(e,t,i){for(var r=[],n=e[t];n&&9!==n.nodeType&&(void 0===i||1!==n.nodeType||!ot(n).is(i));){1===n.nodeType&&r.push(n);n=n[t]}return r},sibling:function(e,t){for(var i=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&i.push(e);return i}});ot.fn.extend({has:function(e){var t,i=ot(e,this),r=i.length;return this.filter(function(){for(t=0;r>t;t++)if(ot.contains(this,i[t]))return!0})},closest:function(e,t){for(var i,r=0,n=this.length,o=[],s=ct.test(e)||"string"!=typeof e?ot(e,t||this.context):0;n>r;r++)for(i=this[r];i&&i!==t;i=i.parentNode)if(i.nodeType<11&&(s?s.index(i)>-1:1===i.nodeType&&ot.find.matchesSelector(i,e))){o.push(i);break}return this.pushStack(o.length>1?ot.unique(o):o)},index:function(e){return e?"string"==typeof e?ot.inArray(this[0],ot(e)):ot.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(ot.unique(ot.merge(this.get(),ot(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});ot.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return ot.dir(e,"parentNode")},parentsUntil:function(e,t,i){return ot.dir(e,"parentNode",i)},next:function(e){return o(e,"nextSibling")},prev:function(e){return o(e,"previousSibling")},nextAll:function(e){return ot.dir(e,"nextSibling")},prevAll:function(e){return ot.dir(e,"previousSibling")},nextUntil:function(e,t,i){return ot.dir(e,"nextSibling",i)},prevUntil:function(e,t,i){return ot.dir(e,"previousSibling",i)},siblings:function(e){return ot.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return ot.sibling(e.firstChild)},contents:function(e){return ot.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:ot.merge([],e.childNodes)}},function(e,t){ot.fn[e]=function(i,r){var n=ot.map(this,t,i);"Until"!==e.slice(-5)&&(r=i);r&&"string"==typeof r&&(n=ot.filter(r,n));if(this.length>1){xt[e]||(n=ot.unique(n));vt.test(e)&&(n=n.reverse())}return this.pushStack(n)}});var Nt=/\S+/g,Tt={};ot.Callbacks=function(e){e="string"==typeof e?Tt[e]||s(e):ot.extend({},e);var t,i,r,n,o,a,l=[],u=!e.once&&[],p=function(s){i=e.memory&&s;r=!0;o=a||0;a=0;n=l.length;t=!0;for(;l&&n>o;o++)if(l[o].apply(s[0],s[1])===!1&&e.stopOnFalse){i=!1;break}t=!1;l&&(u?u.length&&p(u.shift()):i?l=[]:c.disable())},c={add:function(){if(l){var r=l.length;(function o(t){ot.each(t,function(t,i){var r=ot.type(i);"function"===r?e.unique&&c.has(i)||l.push(i):i&&i.length&&"string"!==r&&o(i)})})(arguments);if(t)n=l.length;else if(i){a=r;p(i)}}return this},remove:function(){l&&ot.each(arguments,function(e,i){for(var r;(r=ot.inArray(i,l,r))>-1;){l.splice(r,1);if(t){n>=r&&n--;o>=r&&o--}}});return this},has:function(e){return e?ot.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){l=[];n=0;return this},disable:function(){l=u=i=void 0;return this},disabled:function(){return!l},lock:function(){u=void 0;i||c.disable();return this},locked:function(){return!u},fireWith:function(e,i){if(l&&(!r||u)){i=i||[];i=[e,i.slice?i.slice():i];t?u.push(i):p(i)}return this},fire:function(){c.fireWith(this,arguments);return this},fired:function(){return!!r}};return c};ot.extend({Deferred:function(e){var t=[["resolve","done",ot.Callbacks("once memory"),"resolved"],["reject","fail",ot.Callbacks("once memory"),"rejected"],["notify","progress",ot.Callbacks("memory")]],i="pending",r={state:function(){return i},always:function(){n.done(arguments).fail(arguments);return this},then:function(){var e=arguments;return ot.Deferred(function(i){ot.each(t,function(t,o){var s=ot.isFunction(e[t])&&e[t];n[o[1]](function(){var e=s&&s.apply(this,arguments);e&&ot.isFunction(e.promise)?e.promise().done(i.resolve).fail(i.reject).progress(i.notify):i[o[0]+"With"](this===r?i.promise():this,s?[e]:arguments)})});e=null}).promise()},promise:function(e){return null!=e?ot.extend(e,r):r}},n={};r.pipe=r.then;ot.each(t,function(e,o){var s=o[2],a=o[3];r[o[1]]=s.add;a&&s.add(function(){i=a},t[1^e][2].disable,t[2][2].lock);n[o[0]]=function(){n[o[0]+"With"](this===n?r:this,arguments);return this};n[o[0]+"With"]=s.fireWith});r.promise(n);e&&e.call(n,n);return n},when:function(e){var t,i,r,n=0,o=$.call(arguments),s=o.length,a=1!==s||e&&ot.isFunction(e.promise)?s:0,l=1===a?e:ot.Deferred(),u=function(e,i,r){return function(n){i[e]=this;r[e]=arguments.length>1?$.call(arguments):n;r===t?l.notifyWith(i,r):--a||l.resolveWith(i,r)}};if(s>1){t=new Array(s);i=new Array(s);r=new Array(s);for(;s>n;n++)o[n]&&ot.isFunction(o[n].promise)?o[n].promise().done(u(n,r,o)).fail(l.reject).progress(u(n,i,t)):--a}a||l.resolveWith(r,o);return l.promise()}});var Lt;ot.fn.ready=function(e){ot.ready.promise().done(e);return this};ot.extend({isReady:!1,readyWait:1,holdReady:function(e){e?ot.readyWait++:ot.ready(!0)},ready:function(e){if(e===!0?!--ot.readyWait:!ot.isReady){if(!Et.body)return setTimeout(ot.ready);ot.isReady=!0;if(!(e!==!0&&--ot.readyWait>0)){Lt.resolveWith(Et,[ot]);if(ot.fn.triggerHandler){ot(Et).triggerHandler("ready");ot(Et).off("ready")}}}}});ot.ready.promise=function(e){if(!Lt){Lt=ot.Deferred();if("complete"===Et.readyState)setTimeout(ot.ready);else if(Et.addEventListener){Et.addEventListener("DOMContentLoaded",l,!1);t.addEventListener("load",l,!1)}else{Et.attachEvent("onreadystatechange",l);t.attachEvent("onload",l);var i=!1;try{i=null==t.frameElement&&Et.documentElement}catch(r){}i&&i.doScroll&&function n(){if(!ot.isReady){try{i.doScroll("left")}catch(e){return setTimeout(n,50)}a();ot.ready()}}()}}return Lt.promise(e)};var It,yt="undefined";for(It in ot(rt))break;rt.ownLast="0"!==It;rt.inlineBlockNeedsLayout=!1;ot(function(){var e,t,i,r;i=Et.getElementsByTagName("body")[0];if(i&&i.style){t=Et.createElement("div");r=Et.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";i.appendChild(r).appendChild(t);if(typeof t.style.zoom!==yt){t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";rt.inlineBlockNeedsLayout=e=3===t.offsetWidth;e&&(i.style.zoom=1)}i.removeChild(r)}});(function(){var e=Et.createElement("div");if(null==rt.deleteExpando){rt.deleteExpando=!0;try{delete e.test}catch(t){rt.deleteExpando=!1}}e=null})();ot.acceptData=function(e){var t=ot.noData[(e.nodeName+" ").toLowerCase()],i=+e.nodeType||1;return 1!==i&&9!==i?!1:!t||t!==!0&&e.getAttribute("classid")===t};var At=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,St=/([A-Z])/g;ot.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){e=e.nodeType?ot.cache[e[ot.expando]]:e[ot.expando];return!!e&&!p(e)},data:function(e,t,i){return c(e,t,i)},removeData:function(e,t){return d(e,t)},_data:function(e,t,i){return c(e,t,i,!0)},_removeData:function(e,t){return d(e,t,!0)}});ot.fn.extend({data:function(e,t){var i,r,n,o=this[0],s=o&&o.attributes;if(void 0===e){if(this.length){n=ot.data(o);if(1===o.nodeType&&!ot._data(o,"parsedAttrs")){i=s.length;for(;i--;)if(s[i]){r=s[i].name;if(0===r.indexOf("data-")){r=ot.camelCase(r.slice(5));u(o,r,n[r])}}ot._data(o,"parsedAttrs",!0)}}return n}return"object"==typeof e?this.each(function(){ot.data(this,e)}):arguments.length>1?this.each(function(){ot.data(this,e,t)}):o?u(o,e,ot.data(o,e)):void 0},removeData:function(e){return this.each(function(){ot.removeData(this,e)})}});ot.extend({queue:function(e,t,i){var r;if(e){t=(t||"fx")+"queue";r=ot._data(e,t);i&&(!r||ot.isArray(i)?r=ot._data(e,t,ot.makeArray(i)):r.push(i));return r||[]}},dequeue:function(e,t){t=t||"fx";var i=ot.queue(e,t),r=i.length,n=i.shift(),o=ot._queueHooks(e,t),s=function(){ot.dequeue(e,t)};if("inprogress"===n){n=i.shift();r--}if(n){"fx"===t&&i.unshift("inprogress");delete o.stop;n.call(e,s,o)}!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var i=t+"queueHooks";return ot._data(e,i)||ot._data(e,i,{empty:ot.Callbacks("once memory").add(function(){ot._removeData(e,t+"queue");ot._removeData(e,i)})})}});ot.fn.extend({queue:function(e,t){var i=2;if("string"!=typeof e){t=e;e="fx";i--}return arguments.length<i?ot.queue(this[0],e):void 0===t?this:this.each(function(){var i=ot.queue(this,e,t);ot._queueHooks(this,e);"fx"===e&&"inprogress"!==i[0]&&ot.dequeue(this,e)})},dequeue:function(e){return this.each(function(){ot.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var i,r=1,n=ot.Deferred(),o=this,s=this.length,a=function(){--r||n.resolveWith(o,[o])};if("string"!=typeof e){t=e;e=void 0}e=e||"fx";for(;s--;){i=ot._data(o[s],e+"queueHooks");if(i&&i.empty){r++;i.empty.add(a)}}a();return n.promise(t)}});var Ct=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Rt=["Top","Right","Bottom","Left"],bt=function(e,t){e=t||e;return"none"===ot.css(e,"display")||!ot.contains(e.ownerDocument,e)},Ot=ot.access=function(e,t,i,r,n,o,s){var a=0,l=e.length,u=null==i;if("object"===ot.type(i)){n=!0;for(a in i)ot.access(e,t,a,i[a],!0,o,s)}else if(void 0!==r){n=!0;ot.isFunction(r)||(s=!0);if(u)if(s){t.call(e,r);t=null}else{u=t;t=function(e,t,i){return u.call(ot(e),i)}}if(t)for(;l>a;a++)t(e[a],i,s?r:r.call(e[a],a,t(e[a],i)))}return n?e:u?t.call(e):l?t(e[0],i):o},Pt=/^(?:checkbox|radio)$/i;(function(){var e=Et.createElement("input"),t=Et.createElement("div"),i=Et.createDocumentFragment();t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";rt.leadingWhitespace=3===t.firstChild.nodeType;rt.tbody=!t.getElementsByTagName("tbody").length;rt.htmlSerialize=!!t.getElementsByTagName("link").length;rt.html5Clone="<:nav></:nav>"!==Et.createElement("nav").cloneNode(!0).outerHTML;e.type="checkbox";e.checked=!0;i.appendChild(e);rt.appendChecked=e.checked;t.innerHTML="<textarea>x</textarea>";rt.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue;i.appendChild(t);t.innerHTML="<input type='radio' checked='checked' name='t'/>";rt.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked;rt.noCloneEvent=!0;if(t.attachEvent){t.attachEvent("onclick",function(){rt.noCloneEvent=!1});t.cloneNode(!0).click()}if(null==rt.deleteExpando){rt.deleteExpando=!0;try{delete t.test}catch(r){rt.deleteExpando=!1}}})();(function(){var e,i,r=Et.createElement("div");for(e in{submit:!0,change:!0,focusin:!0}){i="on"+e;if(!(rt[e+"Bubbles"]=i in t)){r.setAttribute(i,"t");rt[e+"Bubbles"]=r.attributes[i].expando===!1}}r=null})();var Dt=/^(?:input|select|textarea)$/i,wt=/^key/,_t=/^(?:mouse|pointer|contextmenu)|click/,Mt=/^(?:focusinfocus|focusoutblur)$/,kt=/^([^.]*)(?:\.(.+)|)$/;ot.event={global:{},add:function(e,t,i,r,n){var o,s,a,l,u,p,c,d,f,h,E,m=ot._data(e);if(m){if(i.handler){l=i;i=l.handler;n=l.selector}i.guid||(i.guid=ot.guid++);(s=m.events)||(s=m.events={});if(!(p=m.handle)){p=m.handle=function(e){return typeof ot===yt||e&&ot.event.triggered===e.type?void 0:ot.event.dispatch.apply(p.elem,arguments)};p.elem=e}t=(t||"").match(Nt)||[""];a=t.length;for(;a--;){o=kt.exec(t[a])||[];f=E=o[1];h=(o[2]||"").split(".").sort();if(f){u=ot.event.special[f]||{};f=(n?u.delegateType:u.bindType)||f;u=ot.event.special[f]||{};c=ot.extend({type:f,origType:E,data:r,handler:i,guid:i.guid,selector:n,needsContext:n&&ot.expr.match.needsContext.test(n),namespace:h.join(".")},l);if(!(d=s[f])){d=s[f]=[];d.delegateCount=0;u.setup&&u.setup.call(e,r,h,p)!==!1||(e.addEventListener?e.addEventListener(f,p,!1):e.attachEvent&&e.attachEvent("on"+f,p))}if(u.add){u.add.call(e,c);c.handler.guid||(c.handler.guid=i.guid)}n?d.splice(d.delegateCount++,0,c):d.push(c);ot.event.global[f]=!0}}e=null}},remove:function(e,t,i,r,n){var o,s,a,l,u,p,c,d,f,h,E,m=ot.hasData(e)&&ot._data(e);if(m&&(p=m.events)){t=(t||"").match(Nt)||[""];u=t.length;for(;u--;){a=kt.exec(t[u])||[];f=E=a[1];h=(a[2]||"").split(".").sort();if(f){c=ot.event.special[f]||{};f=(r?c.delegateType:c.bindType)||f;d=p[f]||[];a=a[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)");l=o=d.length;for(;o--;){s=d[o];if(!(!n&&E!==s.origType||i&&i.guid!==s.guid||a&&!a.test(s.namespace)||r&&r!==s.selector&&("**"!==r||!s.selector))){d.splice(o,1);s.selector&&d.delegateCount--;c.remove&&c.remove.call(e,s)}}if(l&&!d.length){c.teardown&&c.teardown.call(e,h,m.handle)!==!1||ot.removeEvent(e,f,m.handle);delete p[f]}}else for(f in p)ot.event.remove(e,f+t[u],i,r,!0)}if(ot.isEmptyObject(p)){delete m.handle;ot._removeData(e,"events")}}},trigger:function(e,i,r,n){var o,s,a,l,u,p,c,d=[r||Et],f=it.call(e,"type")?e.type:e,h=it.call(e,"namespace")?e.namespace.split("."):[];a=p=r=r||Et;if(3!==r.nodeType&&8!==r.nodeType&&!Mt.test(f+ot.event.triggered)){if(f.indexOf(".")>=0){h=f.split(".");f=h.shift();h.sort()}s=f.indexOf(":")<0&&"on"+f;e=e[ot.expando]?e:new ot.Event(f,"object"==typeof e&&e);e.isTrigger=n?2:3;e.namespace=h.join(".");e.namespace_re=e.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;e.result=void 0;e.target||(e.target=r);i=null==i?[e]:ot.makeArray(i,[e]);u=ot.event.special[f]||{};if(n||!u.trigger||u.trigger.apply(r,i)!==!1){if(!n&&!u.noBubble&&!ot.isWindow(r)){l=u.delegateType||f;Mt.test(l+f)||(a=a.parentNode);for(;a;a=a.parentNode){d.push(a);p=a}p===(r.ownerDocument||Et)&&d.push(p.defaultView||p.parentWindow||t)}c=0;for(;(a=d[c++])&&!e.isPropagationStopped();){e.type=c>1?l:u.bindType||f;o=(ot._data(a,"events")||{})[e.type]&&ot._data(a,"handle");o&&o.apply(a,i);o=s&&a[s];if(o&&o.apply&&ot.acceptData(a)){e.result=o.apply(a,i);e.result===!1&&e.preventDefault()}}e.type=f;if(!n&&!e.isDefaultPrevented()&&(!u._default||u._default.apply(d.pop(),i)===!1)&&ot.acceptData(r)&&s&&r[f]&&!ot.isWindow(r)){p=r[s];p&&(r[s]=null);ot.event.triggered=f;try{r[f]()}catch(E){}ot.event.triggered=void 0;p&&(r[s]=p)}return e.result}}},dispatch:function(e){e=ot.event.fix(e);var t,i,r,n,o,s=[],a=$.call(arguments),l=(ot._data(this,"events")||{})[e.type]||[],u=ot.event.special[e.type]||{};a[0]=e;e.delegateTarget=this;if(!u.preDispatch||u.preDispatch.call(this,e)!==!1){s=ot.event.handlers.call(this,e,l);t=0;for(;(n=s[t++])&&!e.isPropagationStopped();){e.currentTarget=n.elem;o=0;for(;(r=n.handlers[o++])&&!e.isImmediatePropagationStopped();)if(!e.namespace_re||e.namespace_re.test(r.namespace)){e.handleObj=r;e.data=r.data;i=((ot.event.special[r.origType]||{}).handle||r.handler).apply(n.elem,a);if(void 0!==i&&(e.result=i)===!1){e.preventDefault();e.stopPropagation()}}}u.postDispatch&&u.postDispatch.call(this,e);return e.result}},handlers:function(e,t){var i,r,n,o,s=[],a=t.delegateCount,l=e.target;if(a&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){n=[];for(o=0;a>o;o++){r=t[o];i=r.selector+" ";void 0===n[i]&&(n[i]=r.needsContext?ot(i,this).index(l)>=0:ot.find(i,this,null,[l]).length);n[i]&&n.push(r)}n.length&&s.push({elem:l,handlers:n})}a<t.length&&s.push({elem:this,handlers:t.slice(a)});return s},fix:function(e){if(e[ot.expando])return e;var t,i,r,n=e.type,o=e,s=this.fixHooks[n];s||(this.fixHooks[n]=s=_t.test(n)?this.mouseHooks:wt.test(n)?this.keyHooks:{});r=s.props?this.props.concat(s.props):this.props;e=new ot.Event(o);t=r.length;for(;t--;){i=r[t];e[i]=o[i]}e.target||(e.target=o.srcElement||Et);3===e.target.nodeType&&(e.target=e.target.parentNode);e.metaKey=!!e.metaKey;return s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode);return e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var i,r,n,o=t.button,s=t.fromElement;if(null==e.pageX&&null!=t.clientX){r=e.target.ownerDocument||Et;n=r.documentElement;i=r.body;e.pageX=t.clientX+(n&&n.scrollLeft||i&&i.scrollLeft||0)-(n&&n.clientLeft||i&&i.clientLeft||0);e.pageY=t.clientY+(n&&n.scrollTop||i&&i.scrollTop||0)-(n&&n.clientTop||i&&i.clientTop||0)}!e.relatedTarget&&s&&(e.relatedTarget=s===e.target?t.toElement:s);e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0);return e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==E()&&this.focus)try{this.focus();return!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){if(this===E()&&this.blur){this.blur();return!1}},delegateType:"focusout"},click:{trigger:function(){if(ot.nodeName(this,"input")&&"checkbox"===this.type&&this.click){this.click();return!1}},_default:function(e){return ot.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,i,r){var n=ot.extend(new ot.Event,i,{type:e,isSimulated:!0,originalEvent:{}});r?ot.event.trigger(n,null,t):ot.event.dispatch.call(t,n);n.isDefaultPrevented()&&i.preventDefault()}};ot.removeEvent=Et.removeEventListener?function(e,t,i){e.removeEventListener&&e.removeEventListener(t,i,!1)}:function(e,t,i){var r="on"+t;if(e.detachEvent){typeof e[r]===yt&&(e[r]=null);e.detachEvent(r,i)}};ot.Event=function(e,t){if(!(this instanceof ot.Event))return new ot.Event(e,t);if(e&&e.type){this.originalEvent=e;this.type=e.type;this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?f:h}else this.type=e;t&&ot.extend(this,t);this.timeStamp=e&&e.timeStamp||ot.now();this[ot.expando]=!0};ot.Event.prototype={isDefaultPrevented:h,isPropagationStopped:h,isImmediatePropagationStopped:h,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=f;e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=f;if(e){e.stopPropagation&&e.stopPropagation();e.cancelBubble=!0}},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=f;e&&e.stopImmediatePropagation&&e.stopImmediatePropagation();this.stopPropagation()}};ot.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){ot.event.special[e]={delegateType:t,bindType:t,handle:function(e){var i,r=this,n=e.relatedTarget,o=e.handleObj;if(!n||n!==r&&!ot.contains(r,n)){e.type=o.origType;i=o.handler.apply(this,arguments);e.type=t}return i}}});rt.submitBubbles||(ot.event.special.submit={setup:function(){if(ot.nodeName(this,"form"))return!1;ot.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,i=ot.nodeName(t,"input")||ot.nodeName(t,"button")?t.form:void 0;if(i&&!ot._data(i,"submitBubbles")){ot.event.add(i,"submit._submit",function(e){e._submit_bubble=!0});ot._data(i,"submitBubbles",!0)}});return void 0},postDispatch:function(e){if(e._submit_bubble){delete e._submit_bubble;this.parentNode&&!e.isTrigger&&ot.event.simulate("submit",this.parentNode,e,!0)}},teardown:function(){if(ot.nodeName(this,"form"))return!1;ot.event.remove(this,"._submit");return void 0}});rt.changeBubbles||(ot.event.special.change={setup:function(){if(Dt.test(this.nodeName)){if("checkbox"===this.type||"radio"===this.type){ot.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)});ot.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1);ot.event.simulate("change",this,e,!0)})}return!1}ot.event.add(this,"beforeactivate._change",function(e){var t=e.target;if(Dt.test(t.nodeName)&&!ot._data(t,"changeBubbles")){ot.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||ot.event.simulate("change",this.parentNode,e,!0)});ot._data(t,"changeBubbles",!0)}})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){ot.event.remove(this,"._change");return!Dt.test(this.nodeName)}});rt.focusinBubbles||ot.each({focus:"focusin",blur:"focusout"},function(e,t){var i=function(e){ot.event.simulate(t,e.target,ot.event.fix(e),!0)};ot.event.special[t]={setup:function(){var r=this.ownerDocument||this,n=ot._data(r,t);n||r.addEventListener(e,i,!0);ot._data(r,t,(n||0)+1)},teardown:function(){var r=this.ownerDocument||this,n=ot._data(r,t)-1;if(n)ot._data(r,t,n);else{r.removeEventListener(e,i,!0);ot._removeData(r,t)}}}});ot.fn.extend({on:function(e,t,i,r,n){var o,s;if("object"==typeof e){if("string"!=typeof t){i=i||t;t=void 0}for(o in e)this.on(o,t,i,e[o],n);return this}if(null==i&&null==r){r=t;i=t=void 0}else if(null==r)if("string"==typeof t){r=i;i=void 0}else{r=i;i=t;t=void 0}if(r===!1)r=h;else if(!r)return this;if(1===n){s=r;r=function(e){ot().off(e);return s.apply(this,arguments)};r.guid=s.guid||(s.guid=ot.guid++)}return this.each(function(){ot.event.add(this,e,r,i,t)})},one:function(e,t,i,r){return this.on(e,t,i,r,1)},off:function(e,t,i){var r,n;if(e&&e.preventDefault&&e.handleObj){r=e.handleObj;ot(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler);return this}if("object"==typeof e){for(n in e)this.off(n,t,e[n]);return this}if(t===!1||"function"==typeof t){i=t;t=void 0}i===!1&&(i=h);return this.each(function(){ot.event.remove(this,e,i,t)})},trigger:function(e,t){return this.each(function(){ot.event.trigger(e,t,this)})},triggerHandler:function(e,t){var i=this[0];return i?ot.event.trigger(e,t,i,!0):void 0}});var Gt="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Bt=/ jQuery\d+="(?:null|\d+)"/g,Ut=new RegExp("<(?:"+Gt+")[\\s/>]","i"),Vt=/^\s+/,Ft=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Ht=/<([\w:]+)/,jt=/<tbody/i,Wt=/<|&#?\w+;/,qt=/<(?:script|style|link)/i,zt=/checked\s*(?:[^=]|=\s*.checked.)/i,Xt=/^$|\/(?:java|ecma)script/i,Yt=/^true\/(.*)/,Kt=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,$t={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:rt.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Qt=m(Et),Zt=Qt.appendChild(Et.createElement("div"));$t.optgroup=$t.option;$t.tbody=$t.tfoot=$t.colgroup=$t.caption=$t.thead;$t.th=$t.td;ot.extend({clone:function(e,t,i){var r,n,o,s,a,l=ot.contains(e.ownerDocument,e);if(rt.html5Clone||ot.isXMLDoc(e)||!Ut.test("<"+e.nodeName+">"))o=e.cloneNode(!0);else{Zt.innerHTML=e.outerHTML;Zt.removeChild(o=Zt.firstChild)}if(!(rt.noCloneEvent&&rt.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||ot.isXMLDoc(e))){r=g(o);a=g(e);for(s=0;null!=(n=a[s]);++s)r[s]&&y(n,r[s])}if(t)if(i){a=a||g(e);r=r||g(o);for(s=0;null!=(n=a[s]);s++)I(n,r[s])}else I(e,o);r=g(o,"script");r.length>0&&L(r,!l&&g(e,"script"));r=a=n=null;return o},buildFragment:function(e,t,i,r){for(var n,o,s,a,l,u,p,c=e.length,d=m(t),f=[],h=0;c>h;h++){o=e[h];if(o||0===o)if("object"===ot.type(o))ot.merge(f,o.nodeType?[o]:o);else if(Wt.test(o)){a=a||d.appendChild(t.createElement("div"));l=(Ht.exec(o)||["",""])[1].toLowerCase();p=$t[l]||$t._default;a.innerHTML=p[1]+o.replace(Ft,"<$1></$2>")+p[2];n=p[0];for(;n--;)a=a.lastChild;!rt.leadingWhitespace&&Vt.test(o)&&f.push(t.createTextNode(Vt.exec(o)[0]));if(!rt.tbody){o="table"!==l||jt.test(o)?"<table>"!==p[1]||jt.test(o)?0:a:a.firstChild;n=o&&o.childNodes.length;for(;n--;)ot.nodeName(u=o.childNodes[n],"tbody")&&!u.childNodes.length&&o.removeChild(u)
}ot.merge(f,a.childNodes);a.textContent="";for(;a.firstChild;)a.removeChild(a.firstChild);a=d.lastChild}else f.push(t.createTextNode(o))}a&&d.removeChild(a);rt.appendChecked||ot.grep(g(f,"input"),v);h=0;for(;o=f[h++];)if(!r||-1===ot.inArray(o,r)){s=ot.contains(o.ownerDocument,o);a=g(d.appendChild(o),"script");s&&L(a);if(i){n=0;for(;o=a[n++];)Xt.test(o.type||"")&&i.push(o)}}a=null;return d},cleanData:function(e,t){for(var i,r,n,o,s=0,a=ot.expando,l=ot.cache,u=rt.deleteExpando,p=ot.event.special;null!=(i=e[s]);s++)if(t||ot.acceptData(i)){n=i[a];o=n&&l[n];if(o){if(o.events)for(r in o.events)p[r]?ot.event.remove(i,r):ot.removeEvent(i,r,o.handle);if(l[n]){delete l[n];u?delete i[a]:typeof i.removeAttribute!==yt?i.removeAttribute(a):i[a]=null;K.push(n)}}}}});ot.fn.extend({text:function(e){return Ot(this,function(e){return void 0===e?ot.text(this):this.empty().append((this[0]&&this[0].ownerDocument||Et).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=x(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=x(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var i,r=e?ot.filter(e,this):this,n=0;null!=(i=r[n]);n++){t||1!==i.nodeType||ot.cleanData(g(i));if(i.parentNode){t&&ot.contains(i.ownerDocument,i)&&L(g(i,"script"));i.parentNode.removeChild(i)}}return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){1===e.nodeType&&ot.cleanData(g(e,!1));for(;e.firstChild;)e.removeChild(e.firstChild);e.options&&ot.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){e=null==e?!1:e;t=null==t?e:t;return this.map(function(){return ot.clone(this,e,t)})},html:function(e){return Ot(this,function(e){var t=this[0]||{},i=0,r=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Bt,""):void 0;if(!("string"!=typeof e||qt.test(e)||!rt.htmlSerialize&&Ut.test(e)||!rt.leadingWhitespace&&Vt.test(e)||$t[(Ht.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(Ft,"<$1></$2>");try{for(;r>i;i++){t=this[i]||{};if(1===t.nodeType){ot.cleanData(g(t,!1));t.innerHTML=e}}t=0}catch(n){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];this.domManip(arguments,function(t){e=this.parentNode;ot.cleanData(g(this));e&&e.replaceChild(t,this)});return e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=Q.apply([],e);var i,r,n,o,s,a,l=0,u=this.length,p=this,c=u-1,d=e[0],f=ot.isFunction(d);if(f||u>1&&"string"==typeof d&&!rt.checkClone&&zt.test(d))return this.each(function(i){var r=p.eq(i);f&&(e[0]=d.call(this,i,r.html()));r.domManip(e,t)});if(u){a=ot.buildFragment(e,this[0].ownerDocument,!1,this);i=a.firstChild;1===a.childNodes.length&&(a=i);if(i){o=ot.map(g(a,"script"),N);n=o.length;for(;u>l;l++){r=a;if(l!==c){r=ot.clone(r,!0,!0);n&&ot.merge(o,g(r,"script"))}t.call(this[l],r,l)}if(n){s=o[o.length-1].ownerDocument;ot.map(o,T);for(l=0;n>l;l++){r=o[l];Xt.test(r.type||"")&&!ot._data(r,"globalEval")&&ot.contains(s,r)&&(r.src?ot._evalUrl&&ot._evalUrl(r.src):ot.globalEval((r.text||r.textContent||r.innerHTML||"").replace(Kt,"")))}}a=i=null}}return this}});ot.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){ot.fn[e]=function(e){for(var i,r=0,n=[],o=ot(e),s=o.length-1;s>=r;r++){i=r===s?this:this.clone(!0);ot(o[r])[t](i);Z.apply(n,i.get())}return this.pushStack(n)}});var Jt,ei={};(function(){var e;rt.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,i,r;i=Et.getElementsByTagName("body")[0];if(i&&i.style){t=Et.createElement("div");r=Et.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";i.appendChild(r).appendChild(t);if(typeof t.style.zoom!==yt){t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1";t.appendChild(Et.createElement("div")).style.width="5px";e=3!==t.offsetWidth}i.removeChild(r);return e}}})();var ti,ii,ri=/^margin/,ni=new RegExp("^("+Ct+")(?!px)[a-z%]+$","i"),oi=/^(top|right|bottom|left)$/;if(t.getComputedStyle){ti=function(e){return e.ownerDocument.defaultView.opener?e.ownerDocument.defaultView.getComputedStyle(e,null):t.getComputedStyle(e,null)};ii=function(e,t,i){var r,n,o,s,a=e.style;i=i||ti(e);s=i?i.getPropertyValue(t)||i[t]:void 0;if(i){""!==s||ot.contains(e.ownerDocument,e)||(s=ot.style(e,t));if(ni.test(s)&&ri.test(t)){r=a.width;n=a.minWidth;o=a.maxWidth;a.minWidth=a.maxWidth=a.width=s;s=i.width;a.width=r;a.minWidth=n;a.maxWidth=o}}return void 0===s?s:s+""}}else if(Et.documentElement.currentStyle){ti=function(e){return e.currentStyle};ii=function(e,t,i){var r,n,o,s,a=e.style;i=i||ti(e);s=i?i[t]:void 0;null==s&&a&&a[t]&&(s=a[t]);if(ni.test(s)&&!oi.test(t)){r=a.left;n=e.runtimeStyle;o=n&&n.left;o&&(n.left=e.currentStyle.left);a.left="fontSize"===t?"1em":s;s=a.pixelLeft+"px";a.left=r;o&&(n.left=o)}return void 0===s?s:s+""||"auto"}}(function(){function e(){var e,i,r,n;i=Et.getElementsByTagName("body")[0];if(i&&i.style){e=Et.createElement("div");r=Et.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";i.appendChild(r).appendChild(e);e.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute";o=s=!1;l=!0;if(t.getComputedStyle){o="1%"!==(t.getComputedStyle(e,null)||{}).top;s="4px"===(t.getComputedStyle(e,null)||{width:"4px"}).width;n=e.appendChild(Et.createElement("div"));n.style.cssText=e.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0";n.style.marginRight=n.style.width="0";e.style.width="1px";l=!parseFloat((t.getComputedStyle(n,null)||{}).marginRight);e.removeChild(n)}e.innerHTML="<table><tr><td></td><td>t</td></tr></table>";n=e.getElementsByTagName("td");n[0].style.cssText="margin:0;border:0;padding:0;display:none";a=0===n[0].offsetHeight;if(a){n[0].style.display="";n[1].style.display="none";a=0===n[0].offsetHeight}i.removeChild(r)}}var i,r,n,o,s,a,l;i=Et.createElement("div");i.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";n=i.getElementsByTagName("a")[0];r=n&&n.style;if(r){r.cssText="float:left;opacity:.5";rt.opacity="0.5"===r.opacity;rt.cssFloat=!!r.cssFloat;i.style.backgroundClip="content-box";i.cloneNode(!0).style.backgroundClip="";rt.clearCloneStyle="content-box"===i.style.backgroundClip;rt.boxSizing=""===r.boxSizing||""===r.MozBoxSizing||""===r.WebkitBoxSizing;ot.extend(rt,{reliableHiddenOffsets:function(){null==a&&e();return a},boxSizingReliable:function(){null==s&&e();return s},pixelPosition:function(){null==o&&e();return o},reliableMarginRight:function(){null==l&&e();return l}})}})();ot.swap=function(e,t,i,r){var n,o,s={};for(o in t){s[o]=e.style[o];e.style[o]=t[o]}n=i.apply(e,r||[]);for(o in t)e.style[o]=s[o];return n};var si=/alpha\([^)]*\)/i,ai=/opacity\s*=\s*([^)]*)/,li=/^(none|table(?!-c[ea]).+)/,ui=new RegExp("^("+Ct+")(.*)$","i"),pi=new RegExp("^([+-])=("+Ct+")","i"),ci={position:"absolute",visibility:"hidden",display:"block"},di={letterSpacing:"0",fontWeight:"400"},fi=["Webkit","O","Moz","ms"];ot.extend({cssHooks:{opacity:{get:function(e,t){if(t){var i=ii(e,"opacity");return""===i?"1":i}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":rt.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,i,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var n,o,s,a=ot.camelCase(t),l=e.style;t=ot.cssProps[a]||(ot.cssProps[a]=R(l,a));s=ot.cssHooks[t]||ot.cssHooks[a];if(void 0===i)return s&&"get"in s&&void 0!==(n=s.get(e,!1,r))?n:l[t];o=typeof i;if("string"===o&&(n=pi.exec(i))){i=(n[1]+1)*n[2]+parseFloat(ot.css(e,t));o="number"}if(null!=i&&i===i){"number"!==o||ot.cssNumber[a]||(i+="px");rt.clearCloneStyle||""!==i||0!==t.indexOf("background")||(l[t]="inherit");if(!(s&&"set"in s&&void 0===(i=s.set(e,i,r))))try{l[t]=i}catch(u){}}}},css:function(e,t,i,r){var n,o,s,a=ot.camelCase(t);t=ot.cssProps[a]||(ot.cssProps[a]=R(e.style,a));s=ot.cssHooks[t]||ot.cssHooks[a];s&&"get"in s&&(o=s.get(e,!0,i));void 0===o&&(o=ii(e,t,r));"normal"===o&&t in di&&(o=di[t]);if(""===i||i){n=parseFloat(o);return i===!0||ot.isNumeric(n)?n||0:o}return o}});ot.each(["height","width"],function(e,t){ot.cssHooks[t]={get:function(e,i,r){return i?li.test(ot.css(e,"display"))&&0===e.offsetWidth?ot.swap(e,ci,function(){return D(e,t,r)}):D(e,t,r):void 0},set:function(e,i,r){var n=r&&ti(e);return O(e,i,r?P(e,t,r,rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,n),n):0)}}});rt.opacity||(ot.cssHooks.opacity={get:function(e,t){return ai.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var i=e.style,r=e.currentStyle,n=ot.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||i.filter||"";i.zoom=1;if((t>=1||""===t)&&""===ot.trim(o.replace(si,""))&&i.removeAttribute){i.removeAttribute("filter");if(""===t||r&&!r.filter)return}i.filter=si.test(o)?o.replace(si,n):o+" "+n}});ot.cssHooks.marginRight=C(rt.reliableMarginRight,function(e,t){return t?ot.swap(e,{display:"inline-block"},ii,[e,"marginRight"]):void 0});ot.each({margin:"",padding:"",border:"Width"},function(e,t){ot.cssHooks[e+t]={expand:function(i){for(var r=0,n={},o="string"==typeof i?i.split(" "):[i];4>r;r++)n[e+Rt[r]+t]=o[r]||o[r-2]||o[0];return n}};ri.test(e)||(ot.cssHooks[e+t].set=O)});ot.fn.extend({css:function(e,t){return Ot(this,function(e,t,i){var r,n,o={},s=0;if(ot.isArray(t)){r=ti(e);n=t.length;for(;n>s;s++)o[t[s]]=ot.css(e,t[s],!1,r);return o}return void 0!==i?ot.style(e,t,i):ot.css(e,t)},e,t,arguments.length>1)},show:function(){return b(this,!0)},hide:function(){return b(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){bt(this)?ot(this).show():ot(this).hide()})}});ot.Tween=w;w.prototype={constructor:w,init:function(e,t,i,r,n,o){this.elem=e;this.prop=i;this.easing=n||"swing";this.options=t;this.start=this.now=this.cur();this.end=r;this.unit=o||(ot.cssNumber[i]?"":"px")},cur:function(){var e=w.propHooks[this.prop];return e&&e.get?e.get(this):w.propHooks._default.get(this)},run:function(e){var t,i=w.propHooks[this.prop];this.pos=t=this.options.duration?ot.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e;this.now=(this.end-this.start)*t+this.start;this.options.step&&this.options.step.call(this.elem,this.now,this);i&&i.set?i.set(this):w.propHooks._default.set(this);return this}};w.prototype.init.prototype=w.prototype;w.propHooks={_default:{get:function(e){var t;if(null!=e.elem[e.prop]&&(!e.elem.style||null==e.elem.style[e.prop]))return e.elem[e.prop];t=ot.css(e.elem,e.prop,"");return t&&"auto"!==t?t:0},set:function(e){ot.fx.step[e.prop]?ot.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[ot.cssProps[e.prop]]||ot.cssHooks[e.prop])?ot.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}};w.propHooks.scrollTop=w.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}};ot.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}};ot.fx=w.prototype.init;ot.fx.step={};var hi,Ei,mi=/^(?:toggle|show|hide)$/,gi=new RegExp("^(?:([+-])=|)("+Ct+")([a-z%]*)$","i"),vi=/queueHooks$/,xi=[G],Ni={"*":[function(e,t){var i=this.createTween(e,t),r=i.cur(),n=gi.exec(t),o=n&&n[3]||(ot.cssNumber[e]?"":"px"),s=(ot.cssNumber[e]||"px"!==o&&+r)&&gi.exec(ot.css(i.elem,e)),a=1,l=20;if(s&&s[3]!==o){o=o||s[3];n=n||[];s=+r||1;do{a=a||".5";s/=a;ot.style(i.elem,e,s+o)}while(a!==(a=i.cur()/r)&&1!==a&&--l)}if(n){s=i.start=+s||+r||0;i.unit=o;i.end=n[1]?s+(n[1]+1)*n[2]:+n[2]}return i}]};ot.Animation=ot.extend(U,{tweener:function(e,t){if(ot.isFunction(e)){t=e;e=["*"]}else e=e.split(" ");for(var i,r=0,n=e.length;n>r;r++){i=e[r];Ni[i]=Ni[i]||[];Ni[i].unshift(t)}},prefilter:function(e,t){t?xi.unshift(e):xi.push(e)}});ot.speed=function(e,t,i){var r=e&&"object"==typeof e?ot.extend({},e):{complete:i||!i&&t||ot.isFunction(e)&&e,duration:e,easing:i&&t||t&&!ot.isFunction(t)&&t};r.duration=ot.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in ot.fx.speeds?ot.fx.speeds[r.duration]:ot.fx.speeds._default;(null==r.queue||r.queue===!0)&&(r.queue="fx");r.old=r.complete;r.complete=function(){ot.isFunction(r.old)&&r.old.call(this);r.queue&&ot.dequeue(this,r.queue)};return r};ot.fn.extend({fadeTo:function(e,t,i,r){return this.filter(bt).css("opacity",0).show().end().animate({opacity:t},e,i,r)},animate:function(e,t,i,r){var n=ot.isEmptyObject(e),o=ot.speed(t,i,r),s=function(){var t=U(this,ot.extend({},e),o);(n||ot._data(this,"finish"))&&t.stop(!0)};s.finish=s;return n||o.queue===!1?this.each(s):this.queue(o.queue,s)},stop:function(e,t,i){var r=function(e){var t=e.stop;delete e.stop;t(i)};if("string"!=typeof e){i=t;t=e;e=void 0}t&&e!==!1&&this.queue(e||"fx",[]);return this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=ot.timers,s=ot._data(this);if(n)s[n]&&s[n].stop&&r(s[n]);else for(n in s)s[n]&&s[n].stop&&vi.test(n)&&r(s[n]);for(n=o.length;n--;)if(o[n].elem===this&&(null==e||o[n].queue===e)){o[n].anim.stop(i);t=!1;o.splice(n,1)}(t||!i)&&ot.dequeue(this,e)})},finish:function(e){e!==!1&&(e=e||"fx");return this.each(function(){var t,i=ot._data(this),r=i[e+"queue"],n=i[e+"queueHooks"],o=ot.timers,s=r?r.length:0;i.finish=!0;ot.queue(this,e,[]);n&&n.stop&&n.stop.call(this,!0);for(t=o.length;t--;)if(o[t].elem===this&&o[t].queue===e){o[t].anim.stop(!0);o.splice(t,1)}for(t=0;s>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete i.finish})}});ot.each(["toggle","show","hide"],function(e,t){var i=ot.fn[t];ot.fn[t]=function(e,r,n){return null==e||"boolean"==typeof e?i.apply(this,arguments):this.animate(M(t,!0),e,r,n)}});ot.each({slideDown:M("show"),slideUp:M("hide"),slideToggle:M("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){ot.fn[e]=function(e,i,r){return this.animate(t,e,i,r)}});ot.timers=[];ot.fx.tick=function(){var e,t=ot.timers,i=0;hi=ot.now();for(;i<t.length;i++){e=t[i];e()||t[i]!==e||t.splice(i--,1)}t.length||ot.fx.stop();hi=void 0};ot.fx.timer=function(e){ot.timers.push(e);e()?ot.fx.start():ot.timers.pop()};ot.fx.interval=13;ot.fx.start=function(){Ei||(Ei=setInterval(ot.fx.tick,ot.fx.interval))};ot.fx.stop=function(){clearInterval(Ei);Ei=null};ot.fx.speeds={slow:600,fast:200,_default:400};ot.fn.delay=function(e,t){e=ot.fx?ot.fx.speeds[e]||e:e;t=t||"fx";return this.queue(t,function(t,i){var r=setTimeout(t,e);i.stop=function(){clearTimeout(r)}})};(function(){var e,t,i,r,n;t=Et.createElement("div");t.setAttribute("className","t");t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";r=t.getElementsByTagName("a")[0];i=Et.createElement("select");n=i.appendChild(Et.createElement("option"));e=t.getElementsByTagName("input")[0];r.style.cssText="top:1px";rt.getSetAttribute="t"!==t.className;rt.style=/top/.test(r.getAttribute("style"));rt.hrefNormalized="/a"===r.getAttribute("href");rt.checkOn=!!e.value;rt.optSelected=n.selected;rt.enctype=!!Et.createElement("form").enctype;i.disabled=!0;rt.optDisabled=!n.disabled;e=Et.createElement("input");e.setAttribute("value","");rt.input=""===e.getAttribute("value");e.value="t";e.setAttribute("type","radio");rt.radioValue="t"===e.value})();var Ti=/\r/g;ot.fn.extend({val:function(e){var t,i,r,n=this[0];if(arguments.length){r=ot.isFunction(e);return this.each(function(i){var n;if(1===this.nodeType){n=r?e.call(this,i,ot(this).val()):e;null==n?n="":"number"==typeof n?n+="":ot.isArray(n)&&(n=ot.map(n,function(e){return null==e?"":e+""}));t=ot.valHooks[this.type]||ot.valHooks[this.nodeName.toLowerCase()];t&&"set"in t&&void 0!==t.set(this,n,"value")||(this.value=n)}})}if(n){t=ot.valHooks[n.type]||ot.valHooks[n.nodeName.toLowerCase()];if(t&&"get"in t&&void 0!==(i=t.get(n,"value")))return i;i=n.value;return"string"==typeof i?i.replace(Ti,""):null==i?"":i}}});ot.extend({valHooks:{option:{get:function(e){var t=ot.find.attr(e,"value");return null!=t?t:ot.trim(ot.text(e))}},select:{get:function(e){for(var t,i,r=e.options,n=e.selectedIndex,o="select-one"===e.type||0>n,s=o?null:[],a=o?n+1:r.length,l=0>n?a:o?n:0;a>l;l++){i=r[l];if(!(!i.selected&&l!==n||(rt.optDisabled?i.disabled:null!==i.getAttribute("disabled"))||i.parentNode.disabled&&ot.nodeName(i.parentNode,"optgroup"))){t=ot(i).val();if(o)return t;s.push(t)}}return s},set:function(e,t){for(var i,r,n=e.options,o=ot.makeArray(t),s=n.length;s--;){r=n[s];if(ot.inArray(ot.valHooks.option.get(r),o)>=0)try{r.selected=i=!0}catch(a){r.scrollHeight}else r.selected=!1}i||(e.selectedIndex=-1);return n}}}});ot.each(["radio","checkbox"],function(){ot.valHooks[this]={set:function(e,t){return ot.isArray(t)?e.checked=ot.inArray(ot(e).val(),t)>=0:void 0}};rt.checkOn||(ot.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Li,Ii,yi=ot.expr.attrHandle,Ai=/^(?:checked|selected)$/i,Si=rt.getSetAttribute,Ci=rt.input;ot.fn.extend({attr:function(e,t){return Ot(this,ot.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){ot.removeAttr(this,e)})}});ot.extend({attr:function(e,t,i){var r,n,o=e.nodeType;if(e&&3!==o&&8!==o&&2!==o){if(typeof e.getAttribute===yt)return ot.prop(e,t,i);if(1!==o||!ot.isXMLDoc(e)){t=t.toLowerCase();r=ot.attrHooks[t]||(ot.expr.match.bool.test(t)?Ii:Li)}if(void 0===i){if(r&&"get"in r&&null!==(n=r.get(e,t)))return n;n=ot.find.attr(e,t);return null==n?void 0:n}if(null!==i){if(r&&"set"in r&&void 0!==(n=r.set(e,i,t)))return n;e.setAttribute(t,i+"");return i}ot.removeAttr(e,t)}},removeAttr:function(e,t){var i,r,n=0,o=t&&t.match(Nt);if(o&&1===e.nodeType)for(;i=o[n++];){r=ot.propFix[i]||i;ot.expr.match.bool.test(i)?Ci&&Si||!Ai.test(i)?e[r]=!1:e[ot.camelCase("default-"+i)]=e[r]=!1:ot.attr(e,i,"");e.removeAttribute(Si?i:r)}},attrHooks:{type:{set:function(e,t){if(!rt.radioValue&&"radio"===t&&ot.nodeName(e,"input")){var i=e.value;e.setAttribute("type",t);i&&(e.value=i);return t}}}}});Ii={set:function(e,t,i){t===!1?ot.removeAttr(e,i):Ci&&Si||!Ai.test(i)?e.setAttribute(!Si&&ot.propFix[i]||i,i):e[ot.camelCase("default-"+i)]=e[i]=!0;return i}};ot.each(ot.expr.match.bool.source.match(/\w+/g),function(e,t){var i=yi[t]||ot.find.attr;yi[t]=Ci&&Si||!Ai.test(t)?function(e,t,r){var n,o;if(!r){o=yi[t];yi[t]=n;n=null!=i(e,t,r)?t.toLowerCase():null;yi[t]=o}return n}:function(e,t,i){return i?void 0:e[ot.camelCase("default-"+t)]?t.toLowerCase():null}});Ci&&Si||(ot.attrHooks.value={set:function(e,t,i){if(!ot.nodeName(e,"input"))return Li&&Li.set(e,t,i);e.defaultValue=t;return void 0}});if(!Si){Li={set:function(e,t,i){var r=e.getAttributeNode(i);r||e.setAttributeNode(r=e.ownerDocument.createAttribute(i));r.value=t+="";return"value"===i||t===e.getAttribute(i)?t:void 0}};yi.id=yi.name=yi.coords=function(e,t,i){var r;return i?void 0:(r=e.getAttributeNode(t))&&""!==r.value?r.value:null};ot.valHooks.button={get:function(e,t){var i=e.getAttributeNode(t);return i&&i.specified?i.value:void 0},set:Li.set};ot.attrHooks.contenteditable={set:function(e,t,i){Li.set(e,""===t?!1:t,i)}};ot.each(["width","height"],function(e,t){ot.attrHooks[t]={set:function(e,i){if(""===i){e.setAttribute(t,"auto");return i}}}})}rt.style||(ot.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var Ri=/^(?:input|select|textarea|button|object)$/i,bi=/^(?:a|area)$/i;ot.fn.extend({prop:function(e,t){return Ot(this,ot.prop,e,t,arguments.length>1)},removeProp:function(e){e=ot.propFix[e]||e;return this.each(function(){try{this[e]=void 0;delete this[e]}catch(t){}})}});ot.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,i){var r,n,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s){o=1!==s||!ot.isXMLDoc(e);if(o){t=ot.propFix[t]||t;n=ot.propHooks[t]}return void 0!==i?n&&"set"in n&&void 0!==(r=n.set(e,i,t))?r:e[t]=i:n&&"get"in n&&null!==(r=n.get(e,t))?r:e[t]}},propHooks:{tabIndex:{get:function(e){var t=ot.find.attr(e,"tabindex");return t?parseInt(t,10):Ri.test(e.nodeName)||bi.test(e.nodeName)&&e.href?0:-1}}}});rt.hrefNormalized||ot.each(["href","src"],function(e,t){ot.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}});rt.optSelected||(ot.propHooks.selected={get:function(e){var t=e.parentNode;if(t){t.selectedIndex;t.parentNode&&t.parentNode.selectedIndex}return null}});ot.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){ot.propFix[this.toLowerCase()]=this});rt.enctype||(ot.propFix.enctype="encoding");var Oi=/[\t\r\n\f]/g;ot.fn.extend({addClass:function(e){var t,i,r,n,o,s,a=0,l=this.length,u="string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).addClass(e.call(this,t,this.className))});if(u){t=(e||"").match(Nt)||[];for(;l>a;a++){i=this[a];r=1===i.nodeType&&(i.className?(" "+i.className+" ").replace(Oi," "):" ");if(r){o=0;for(;n=t[o++];)r.indexOf(" "+n+" ")<0&&(r+=n+" ");s=ot.trim(r);i.className!==s&&(i.className=s)}}}return this},removeClass:function(e){var t,i,r,n,o,s,a=0,l=this.length,u=0===arguments.length||"string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).removeClass(e.call(this,t,this.className))});if(u){t=(e||"").match(Nt)||[];for(;l>a;a++){i=this[a];r=1===i.nodeType&&(i.className?(" "+i.className+" ").replace(Oi," "):"");if(r){o=0;for(;n=t[o++];)for(;r.indexOf(" "+n+" ")>=0;)r=r.replace(" "+n+" "," ");s=e?ot.trim(r):"";i.className!==s&&(i.className=s)}}}return this},toggleClass:function(e,t){var i=typeof e;return"boolean"==typeof t&&"string"===i?t?this.addClass(e):this.removeClass(e):this.each(ot.isFunction(e)?function(i){ot(this).toggleClass(e.call(this,i,this.className,t),t)}:function(){if("string"===i)for(var t,r=0,n=ot(this),o=e.match(Nt)||[];t=o[r++];)n.hasClass(t)?n.removeClass(t):n.addClass(t);else if(i===yt||"boolean"===i){this.className&&ot._data(this,"__className__",this.className);this.className=this.className||e===!1?"":ot._data(this,"__className__")||""}})},hasClass:function(e){for(var t=" "+e+" ",i=0,r=this.length;r>i;i++)if(1===this[i].nodeType&&(" "+this[i].className+" ").replace(Oi," ").indexOf(t)>=0)return!0;return!1}});ot.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){ot.fn[t]=function(e,i){return arguments.length>0?this.on(t,null,e,i):this.trigger(t)}});ot.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,i){return this.on(e,null,t,i)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,i,r){return this.on(t,e,i,r)},undelegate:function(e,t,i){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",i)}});var Pi=ot.now(),Di=/\?/,wi=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;ot.parseJSON=function(e){if(t.JSON&&t.JSON.parse)return t.JSON.parse(e+"");var i,r=null,n=ot.trim(e+"");return n&&!ot.trim(n.replace(wi,function(e,t,n,o){i&&t&&(r=0);if(0===r)return e;i=n||t;r+=!o-!n;return""}))?Function("return "+n)():ot.error("Invalid JSON: "+e)};ot.parseXML=function(e){var i,r;if(!e||"string"!=typeof e)return null;try{if(t.DOMParser){r=new DOMParser;i=r.parseFromString(e,"text/xml")}else{i=new ActiveXObject("Microsoft.XMLDOM");i.async="false";i.loadXML(e)}}catch(n){i=void 0}i&&i.documentElement&&!i.getElementsByTagName("parsererror").length||ot.error("Invalid XML: "+e);return i};var _i,Mi,ki=/#.*$/,Gi=/([?&])_=[^&]*/,Bi=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ui=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Vi=/^(?:GET|HEAD)$/,Fi=/^\/\//,Hi=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,ji={},Wi={},qi="*/".concat("*");try{Mi=location.href}catch(zi){Mi=Et.createElement("a");Mi.href="";Mi=Mi.href}_i=Hi.exec(Mi.toLowerCase())||[];ot.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Mi,type:"GET",isLocal:Ui.test(_i[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":qi,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":ot.parseJSON,"text xml":ot.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?H(H(e,ot.ajaxSettings),t):H(ot.ajaxSettings,e)},ajaxPrefilter:V(ji),ajaxTransport:V(Wi),ajax:function(e,t){function i(e,t,i,r){var n,p,g,v,N,L=t;if(2!==x){x=2;a&&clearTimeout(a);u=void 0;s=r||"";T.readyState=e>0?4:0;n=e>=200&&300>e||304===e;i&&(v=j(c,T,i));v=W(c,v,T,n);if(n){if(c.ifModified){N=T.getResponseHeader("Last-Modified");N&&(ot.lastModified[o]=N);N=T.getResponseHeader("etag");N&&(ot.etag[o]=N)}if(204===e||"HEAD"===c.type)L="nocontent";else if(304===e)L="notmodified";else{L=v.state;p=v.data;g=v.error;n=!g}}else{g=L;if(e||!L){L="error";0>e&&(e=0)}}T.status=e;T.statusText=(t||L)+"";n?h.resolveWith(d,[p,L,T]):h.rejectWith(d,[T,L,g]);T.statusCode(m);m=void 0;l&&f.trigger(n?"ajaxSuccess":"ajaxError",[T,c,n?p:g]);E.fireWith(d,[T,L]);if(l){f.trigger("ajaxComplete",[T,c]);--ot.active||ot.event.trigger("ajaxStop")}}}if("object"==typeof e){t=e;e=void 0}t=t||{};var r,n,o,s,a,l,u,p,c=ot.ajaxSetup({},t),d=c.context||c,f=c.context&&(d.nodeType||d.jquery)?ot(d):ot.event,h=ot.Deferred(),E=ot.Callbacks("once memory"),m=c.statusCode||{},g={},v={},x=0,N="canceled",T={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!p){p={};for(;t=Bi.exec(s);)p[t[1].toLowerCase()]=t[2]}t=p[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?s:null},setRequestHeader:function(e,t){var i=e.toLowerCase();if(!x){e=v[i]=v[i]||e;g[e]=t}return this},overrideMimeType:function(e){x||(c.mimeType=e);return this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else T.always(e[T.status]);return this},abort:function(e){var t=e||N;u&&u.abort(t);i(0,t);return this}};h.promise(T).complete=E.add;T.success=T.done;T.error=T.fail;c.url=((e||c.url||Mi)+"").replace(ki,"").replace(Fi,_i[1]+"//");c.type=t.method||t.type||c.method||c.type;c.dataTypes=ot.trim(c.dataType||"*").toLowerCase().match(Nt)||[""];if(null==c.crossDomain){r=Hi.exec(c.url.toLowerCase());c.crossDomain=!(!r||r[1]===_i[1]&&r[2]===_i[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(_i[3]||("http:"===_i[1]?"80":"443")))}c.data&&c.processData&&"string"!=typeof c.data&&(c.data=ot.param(c.data,c.traditional));F(ji,c,t,T);if(2===x)return T;l=ot.event&&c.global;l&&0===ot.active++&&ot.event.trigger("ajaxStart");c.type=c.type.toUpperCase();c.hasContent=!Vi.test(c.type);o=c.url;if(!c.hasContent){if(c.data){o=c.url+=(Di.test(o)?"&":"?")+c.data;delete c.data}c.cache===!1&&(c.url=Gi.test(o)?o.replace(Gi,"$1_="+Pi++):o+(Di.test(o)?"&":"?")+"_="+Pi++)}if(c.ifModified){ot.lastModified[o]&&T.setRequestHeader("If-Modified-Since",ot.lastModified[o]);ot.etag[o]&&T.setRequestHeader("If-None-Match",ot.etag[o])}(c.data&&c.hasContent&&c.contentType!==!1||t.contentType)&&T.setRequestHeader("Content-Type",c.contentType);T.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+("*"!==c.dataTypes[0]?", "+qi+"; q=0.01":""):c.accepts["*"]);for(n in c.headers)T.setRequestHeader(n,c.headers[n]);if(c.beforeSend&&(c.beforeSend.call(d,T,c)===!1||2===x))return T.abort();N="abort";for(n in{success:1,error:1,complete:1})T[n](c[n]);u=F(Wi,c,t,T);if(u){T.readyState=1;l&&f.trigger("ajaxSend",[T,c]);c.async&&c.timeout>0&&(a=setTimeout(function(){T.abort("timeout")},c.timeout));try{x=1;u.send(g,i)}catch(L){if(!(2>x))throw L;i(-1,L)}}else i(-1,"No Transport");return T},getJSON:function(e,t,i){return ot.get(e,t,i,"json")},getScript:function(e,t){return ot.get(e,void 0,t,"script")}});ot.each(["get","post"],function(e,t){ot[t]=function(e,i,r,n){if(ot.isFunction(i)){n=n||r;r=i;i=void 0}return ot.ajax({url:e,type:t,dataType:n,data:i,success:r})}});ot._evalUrl=function(e){return ot.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})};ot.fn.extend({wrapAll:function(e){if(ot.isFunction(e))return this.each(function(t){ot(this).wrapAll(e.call(this,t))});if(this[0]){var t=ot(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]);t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return this.each(ot.isFunction(e)?function(t){ot(this).wrapInner(e.call(this,t))}:function(){var t=ot(this),i=t.contents();i.length?i.wrapAll(e):t.append(e)})},wrap:function(e){var t=ot.isFunction(e);return this.each(function(i){ot(this).wrapAll(t?e.call(this,i):e)})},unwrap:function(){return this.parent().each(function(){ot.nodeName(this,"body")||ot(this).replaceWith(this.childNodes)}).end()}});ot.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||!rt.reliableHiddenOffsets()&&"none"===(e.style&&e.style.display||ot.css(e,"display"))};ot.expr.filters.visible=function(e){return!ot.expr.filters.hidden(e)};var Xi=/%20/g,Yi=/\[\]$/,Ki=/\r?\n/g,$i=/^(?:submit|button|image|reset|file)$/i,Qi=/^(?:input|select|textarea|keygen)/i;ot.param=function(e,t){var i,r=[],n=function(e,t){t=ot.isFunction(t)?t():null==t?"":t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};void 0===t&&(t=ot.ajaxSettings&&ot.ajaxSettings.traditional);if(ot.isArray(e)||e.jquery&&!ot.isPlainObject(e))ot.each(e,function(){n(this.name,this.value)});else for(i in e)q(i,e[i],t,n);return r.join("&").replace(Xi,"+")};ot.fn.extend({serialize:function(){return ot.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=ot.prop(this,"elements");return e?ot.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!ot(this).is(":disabled")&&Qi.test(this.nodeName)&&!$i.test(e)&&(this.checked||!Pt.test(e))}).map(function(e,t){var i=ot(this).val();return null==i?null:ot.isArray(i)?ot.map(i,function(e){return{name:t.name,value:e.replace(Ki,"\r\n")}}):{name:t.name,value:i.replace(Ki,"\r\n")}}).get()}});ot.ajaxSettings.xhr=void 0!==t.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&z()||X()}:z;var Zi=0,Ji={},er=ot.ajaxSettings.xhr();t.attachEvent&&t.attachEvent("onunload",function(){for(var e in Ji)Ji[e](void 0,!0)});rt.cors=!!er&&"withCredentials"in er;er=rt.ajax=!!er;er&&ot.ajaxTransport(function(e){if(!e.crossDomain||rt.cors){var t;return{send:function(i,r){var n,o=e.xhr(),s=++Zi;o.open(e.type,e.url,e.async,e.username,e.password);if(e.xhrFields)for(n in e.xhrFields)o[n]=e.xhrFields[n];e.mimeType&&o.overrideMimeType&&o.overrideMimeType(e.mimeType);e.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");for(n in i)void 0!==i[n]&&o.setRequestHeader(n,i[n]+"");o.send(e.hasContent&&e.data||null);t=function(i,n){var a,l,u;if(t&&(n||4===o.readyState)){delete Ji[s];t=void 0;o.onreadystatechange=ot.noop;if(n)4!==o.readyState&&o.abort();else{u={};a=o.status;"string"==typeof o.responseText&&(u.text=o.responseText);try{l=o.statusText
}catch(p){l=""}a||!e.isLocal||e.crossDomain?1223===a&&(a=204):a=u.text?200:404}}u&&r(a,l,u,o.getAllResponseHeaders())};e.async?4===o.readyState?setTimeout(t):o.onreadystatechange=Ji[s]=t:t()},abort:function(){t&&t(void 0,!0)}}}});ot.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){ot.globalEval(e);return e}}});ot.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1);if(e.crossDomain){e.type="GET";e.global=!1}});ot.ajaxTransport("script",function(e){if(e.crossDomain){var t,i=Et.head||ot("head")[0]||Et.documentElement;return{send:function(r,n){t=Et.createElement("script");t.async=!0;e.scriptCharset&&(t.charset=e.scriptCharset);t.src=e.url;t.onload=t.onreadystatechange=function(e,i){if(i||!t.readyState||/loaded|complete/.test(t.readyState)){t.onload=t.onreadystatechange=null;t.parentNode&&t.parentNode.removeChild(t);t=null;i||n(200,"success")}};i.insertBefore(t,i.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var tr=[],ir=/(=)\?(?=&|$)|\?\?/;ot.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=tr.pop()||ot.expando+"_"+Pi++;this[e]=!0;return e}});ot.ajaxPrefilter("json jsonp",function(e,i,r){var n,o,s,a=e.jsonp!==!1&&(ir.test(e.url)?"url":"string"==typeof e.data&&!(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&ir.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0]){n=e.jsonpCallback=ot.isFunction(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback;a?e[a]=e[a].replace(ir,"$1"+n):e.jsonp!==!1&&(e.url+=(Di.test(e.url)?"&":"?")+e.jsonp+"="+n);e.converters["script json"]=function(){s||ot.error(n+" was not called");return s[0]};e.dataTypes[0]="json";o=t[n];t[n]=function(){s=arguments};r.always(function(){t[n]=o;if(e[n]){e.jsonpCallback=i.jsonpCallback;tr.push(n)}s&&ot.isFunction(o)&&o(s[0]);s=o=void 0});return"script"}});ot.parseHTML=function(e,t,i){if(!e||"string"!=typeof e)return null;if("boolean"==typeof t){i=t;t=!1}t=t||Et;var r=dt.exec(e),n=!i&&[];if(r)return[t.createElement(r[1])];r=ot.buildFragment([e],t,n);n&&n.length&&ot(n).remove();return ot.merge([],r.childNodes)};var rr=ot.fn.load;ot.fn.load=function(e,t,i){if("string"!=typeof e&&rr)return rr.apply(this,arguments);var r,n,o,s=this,a=e.indexOf(" ");if(a>=0){r=ot.trim(e.slice(a,e.length));e=e.slice(0,a)}if(ot.isFunction(t)){i=t;t=void 0}else t&&"object"==typeof t&&(o="POST");s.length>0&&ot.ajax({url:e,type:o,dataType:"html",data:t}).done(function(e){n=arguments;s.html(r?ot("<div>").append(ot.parseHTML(e)).find(r):e)}).complete(i&&function(e,t){s.each(i,n||[e.responseText,t,e])});return this};ot.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ot.fn[t]=function(e){return this.on(t,e)}});ot.expr.filters.animated=function(e){return ot.grep(ot.timers,function(t){return e===t.elem}).length};var nr=t.document.documentElement;ot.offset={setOffset:function(e,t,i){var r,n,o,s,a,l,u,p=ot.css(e,"position"),c=ot(e),d={};"static"===p&&(e.style.position="relative");a=c.offset();o=ot.css(e,"top");l=ot.css(e,"left");u=("absolute"===p||"fixed"===p)&&ot.inArray("auto",[o,l])>-1;if(u){r=c.position();s=r.top;n=r.left}else{s=parseFloat(o)||0;n=parseFloat(l)||0}ot.isFunction(t)&&(t=t.call(e,i,a));null!=t.top&&(d.top=t.top-a.top+s);null!=t.left&&(d.left=t.left-a.left+n);"using"in t?t.using.call(e,d):c.css(d)}};ot.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){ot.offset.setOffset(this,e,t)});var t,i,r={top:0,left:0},n=this[0],o=n&&n.ownerDocument;if(o){t=o.documentElement;if(!ot.contains(t,n))return r;typeof n.getBoundingClientRect!==yt&&(r=n.getBoundingClientRect());i=Y(o);return{top:r.top+(i.pageYOffset||t.scrollTop)-(t.clientTop||0),left:r.left+(i.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}}},position:function(){if(this[0]){var e,t,i={top:0,left:0},r=this[0];if("fixed"===ot.css(r,"position"))t=r.getBoundingClientRect();else{e=this.offsetParent();t=this.offset();ot.nodeName(e[0],"html")||(i=e.offset());i.top+=ot.css(e[0],"borderTopWidth",!0);i.left+=ot.css(e[0],"borderLeftWidth",!0)}return{top:t.top-i.top-ot.css(r,"marginTop",!0),left:t.left-i.left-ot.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||nr;e&&!ot.nodeName(e,"html")&&"static"===ot.css(e,"position");)e=e.offsetParent;return e||nr})}});ot.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var i=/Y/.test(t);ot.fn[e]=function(r){return Ot(this,function(e,r,n){var o=Y(e);if(void 0===n)return o?t in o?o[t]:o.document.documentElement[r]:e[r];o?o.scrollTo(i?ot(o).scrollLeft():n,i?n:ot(o).scrollTop()):e[r]=n;return void 0},e,r,arguments.length,null)}});ot.each(["top","left"],function(e,t){ot.cssHooks[t]=C(rt.pixelPosition,function(e,i){if(i){i=ii(e,t);return ni.test(i)?ot(e).position()[t]+"px":i}})});ot.each({Height:"height",Width:"width"},function(e,t){ot.each({padding:"inner"+e,content:t,"":"outer"+e},function(i,r){ot.fn[r]=function(r,n){var o=arguments.length&&(i||"boolean"!=typeof r),s=i||(r===!0||n===!0?"margin":"border");return Ot(this,function(t,i,r){var n;if(ot.isWindow(t))return t.document.documentElement["client"+e];if(9===t.nodeType){n=t.documentElement;return Math.max(t.body["scroll"+e],n["scroll"+e],t.body["offset"+e],n["offset"+e],n["client"+e])}return void 0===r?ot.css(t,i,s):ot.style(t,i,r,s)},t,o?r:void 0,o,null)}})});ot.fn.size=function(){return this.length};ot.fn.andSelf=ot.fn.addBack;"function"==typeof e&&e.amd&&e("jquery",[],function(){return ot});var or=t.jQuery,sr=t.$;ot.noConflict=function(e){t.$===ot&&(t.$=sr);e&&t.jQuery===ot&&(t.jQuery=or);return ot};typeof i===yt&&(t.jQuery=t.$=ot);return ot})},{}],16:[function(t,i){(function(t){function r(){try{return l in t&&t[l]}catch(e){return!1}}function n(e){return e.replace(/^d/,"___$&").replace(h,"___")}var o,s={},a=t.document,l="localStorage",u="script";s.disabled=!1;s.version="1.3.17";s.set=function(){};s.get=function(){};s.has=function(e){return void 0!==s.get(e)};s.remove=function(){};s.clear=function(){};s.transact=function(e,t,i){if(null==i){i=t;t=null}null==t&&(t={});var r=s.get(e,t);i(r);s.set(e,r)};s.getAll=function(){};s.forEach=function(){};s.serialize=function(e){return JSON.stringify(e)};s.deserialize=function(e){if("string"!=typeof e)return void 0;try{return JSON.parse(e)}catch(t){return e||void 0}};if(r()){o=t[l];s.set=function(e,t){if(void 0===t)return s.remove(e);o.setItem(e,s.serialize(t));return t};s.get=function(e,t){var i=s.deserialize(o.getItem(e));return void 0===i?t:i};s.remove=function(e){o.removeItem(e)};s.clear=function(){o.clear()};s.getAll=function(){var e={};s.forEach(function(t,i){e[t]=i});return e};s.forEach=function(e){for(var t=0;t<o.length;t++){var i=o.key(t);e(i,s.get(i))}}}else if(a.documentElement.addBehavior){var p,c;try{c=new ActiveXObject("htmlfile");c.open();c.write("<"+u+">document.w=window</"+u+'><iframe src="/favicon.ico"></iframe>');c.close();p=c.w.frames[0].document;o=p.createElement("div")}catch(d){o=a.createElement("div");p=a.body}var f=function(e){return function(){var t=Array.prototype.slice.call(arguments,0);t.unshift(o);p.appendChild(o);o.addBehavior("#default#userData");o.load(l);var i=e.apply(s,t);p.removeChild(o);return i}},h=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");s.set=f(function(e,t,i){t=n(t);if(void 0===i)return s.remove(t);e.setAttribute(t,s.serialize(i));e.save(l);return i});s.get=f(function(e,t,i){t=n(t);var r=s.deserialize(e.getAttribute(t));return void 0===r?i:r});s.remove=f(function(e,t){t=n(t);e.removeAttribute(t);e.save(l)});s.clear=f(function(e){var t=e.XMLDocument.documentElement.attributes;e.load(l);for(var i,r=0;i=t[r];r++)e.removeAttribute(i.name);e.save(l)});s.getAll=function(){var e={};s.forEach(function(t,i){e[t]=i});return e};s.forEach=f(function(e,t){for(var i,r=e.XMLDocument.documentElement.attributes,n=0;i=r[n];++n)t(i.name,s.deserialize(e.getAttribute(i.name)))})}try{var E="__storejs__";s.set(E,E);s.get(E)!=E&&(s.disabled=!0);s.remove(E)}catch(d){s.disabled=!0}s.enabled=!s.disabled;"undefined"!=typeof i&&i.exports&&this.module!==i?i.exports=s:"function"==typeof e&&e.amd?e(s):t.store=s})(Function("return this")())},{}],17:[function(e,t){t.exports={name:"yasgui-utils",version:"1.5.0",description:"Utils for YASGUI libs",main:"src/main.js",repository:{type:"git",url:"git://github.com/YASGUI/Utils.git"},licenses:[{type:"MIT",url:"http://yasgui.github.io/license.txt"}],author:"Laurens Rietveld",maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],bugs:{url:"https://github.com/YASGUI/Utils/issues"},homepage:"https://github.com/YASGUI/Utils",dependencies:{store:"^1.3.14"}}},{}],18:[function(e,t){window.console=window.console||{log:function(){}};t.exports={storage:e("./storage.js"),svg:e("./svg.js"),version:{"yasgui-utils":e("../package.json").version}}},{"../package.json":17,"./storage.js":19,"./svg.js":20}],19:[function(e,t){{var i=e("store"),r={day:function(){return 864e5},month:function(){30*r.day()},year:function(){12*r.month()}};t.exports={set:function(e,t,n){if(i.enabled&&e&&t){"string"==typeof n&&(n=r[n]());t.documentElement&&(t=(new XMLSerializer).serializeToString(t.documentElement));i.set(e,{val:t,exp:n,time:(new Date).getTime()})}},remove:function(e){i.enabled&&e&&i.remove(e)},get:function(e){if(!i.enabled)return null;if(e){var t=i.get(e);return t?t.exp&&(new Date).getTime()-t.time>t.exp?null:t.val:null}return null}}}},{store:16}],20:[function(e,t){t.exports={draw:function(e,i){if(e){var r=t.exports.getElement(i);r&&(e.append?e.append(r):e.appendChild(r))}},getElement:function(e){if(e&&0==e.indexOf("<svg")){var t=new DOMParser,i=t.parseFromString(e,"text/xml"),r=i.documentElement,n=document.createElement("div");n.className="svgImg";n.appendChild(r);return n}return!1}}},{}],21:[function(e,t){t.exports={name:"yasgui-yasqe",description:"Yet Another SPARQL Query Editor",version:"2.3.7",main:"src/main.js",licenses:[{type:"MIT",url:"http://yasqe.yasgui.org/license.txt"}],author:"Laurens Rietveld",homepage:"http://yasqe.yasgui.org",devDependencies:{browserify:"^6.1.0",gulp:"~3.6.0","gulp-bump":"^0.1.11","gulp-concat":"^2.4.1","gulp-connect":"^2.0.5","gulp-embedlr":"^0.5.2","gulp-filter":"^1.0.2","gulp-git":"^0.5.2","gulp-jsvalidate":"^0.2.0","gulp-livereload":"^1.3.1","gulp-minify-css":"0.3.11","gulp-notify":"^2.0.1","gulp-rename":"^1.2.0","gulp-streamify":"0.0.5","gulp-tag-version":"^1.1.0","gulp-uglify":"^1.0.1","require-dir":"^0.1.0","run-sequence":"^1.0.1","vinyl-buffer":"^1.0.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","gulp-sourcemaps":"^1.2.8",exorcist:"^0.1.6","vinyl-transform":"0.0.1","gulp-sass":"^1.2.2","bootstrap-sass":"^3.3.1","browserify-transform-tools":"^1.2.1","gulp-cssimport":"^1.3.1"},bugs:"https://github.com/YASGUI/YASQE/issues/",keywords:["JavaScript","SPARQL","Editor","Semantic Web","Linked Data"],maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],repository:{type:"git",url:"https://github.com/YASGUI/YASQE.git"},dependencies:{jquery:"~ 1.11.0",codemirror:"^4.7.0","yasgui-utils":"^1.4.1"},optionalShim:{codemirror:{require:"codemirror",global:"CodeMirror"},jquery:{require:"jquery",global:"jQuery"},"../../lib/codemirror":{require:"codemirror",global:"CodeMirror"}}}},{}],22:[function(e,t){"use strict";var i=e("jquery"),r=e("../utils.js"),n=e("yasgui-utils"),o=e("../../lib/trie.js");t.exports=function(e,t){var a={},l={},u={};t.on("cursorActivity",function(){d(!0)});t.on("change",function(){var e=[];for(var r in a)a[r].is(":visible")&&e.push(a[r]);if(e.length>0){var n=i(t.getWrapperElement()).find(".CodeMirror-vscrollbar"),o=0;n.is(":visible")&&(o=n.outerWidth());e.forEach(function(e){e.css("right",o)})}});var p=function(e,i){u[e.name]=new o;for(var s=0;s<i.length;s++)u[e.name].insert(i[s]);var a=r.getPersistencyId(t,e.persistent);a&&n.storage.set(a,i,"month")},c=function(e,i){var o=l[e]=new i(t,e);o.name=e;if(o.bulk){var s=function(e){e&&e instanceof Array&&e.length>0&&p(o,e)};if(o.get instanceof Array)s(o.get);else{var a=null,u=r.getPersistencyId(t,o.persistent);u&&(a=n.storage.get(u));a&&a.length>0?s(a):o.get instanceof Function&&(o.async?o.get(null,s):s(o.get()))}}},d=function(r){if(!t.somethingSelected()){var n=function(i){if(r&&(!i.autoShow||!i.bulk&&i.async))return!1;var n={closeCharacters:/(?=a)b/,completeSingle:!1};!i.bulk&&i.async&&(n.async=!0);{var o=function(e,t){return f(i,t)};e.showHint(t,o,n)}return!0};for(var o in l)if(-1!=i.inArray(o,t.options.autocompleters)){var s=l[o];if(s.isValidCompletionPosition)if(s.isValidCompletionPosition()){if(!s.callbacks||!s.callbacks.validPosition||s.callbacks.validPosition(t,s)!==!1){var a=n(s);if(a)break}}else s.callbacks&&s.callbacks.invalidPosition&&s.callbacks.invalidPosition(t,s)}}},f=function(e,i){var r=function(t){var i=t.autocompletionString||t.string,r=[];if(u[e.name])r=u[e.name].autoComplete(i);else if("function"==typeof e.get&&0==e.async)r=e.get(i);else if("object"==typeof e.get)for(var n=i.length,o=0;o<e.get.length;o++){var s=e.get[o];s.slice(0,n)==i&&r.push(s)}return h(r,e,t)},n=t.getCompleteToken();e.preProcessToken&&(n=e.preProcessToken(n));if(n){if(e.bulk||!e.async)return r(n);var o=function(t){i(h(t,e,n))};e.get(n,o)}},h=function(e,i,r){for(var n=[],o=0;o<e.length;o++){var a=e[o];i.postProcessToken&&(a=i.postProcessToken(r,a));n.push({text:a,displayText:a,hint:s})}var l=t.getCursor(),u={completionToken:r.string,list:n,from:{line:l.line,ch:r.start},to:{line:l.line,ch:r.end}};if(i.callbacks)for(var p in i.callbacks)i.callbacks[p]&&t.on(u,p,i.callbacks[p]);return u};return{init:c,completers:l,notifications:{getEl:function(e){return i(a[e.name])},show:function(e,t){if(!t.autoshow){a[t.name]||(a[t.name]=i("<div class='completionNotification'></div>"));a[t.name].show().text("Press "+(-1!=navigator.userAgent.indexOf("Mac OS X")?"CMD":"CTRL")+" - <spacebar> to autocomplete").appendTo(i(e.getWrapperElement()))}},hide:function(e,t){a[t.name]&&a[t.name].hide()}},autoComplete:d,getTrie:function(e){return"string"==typeof e?u[e]:u[e.name]}}};var s=function(e,t,i){i.text!=e.getTokenAt(e.getCursor()).string&&e.replaceRange(i.text,t.from,t.to)}},{"../../lib/trie.js":4,"../utils.js":35,jquery:15,"yasgui-utils":18}],23:[function(e,t){"use strict";e("jquery");t.exports=function(i,r){return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(i)},get:function(t,r){return e("./utils").fetchFromLov(i,this,t,r)},preProcessToken:function(e){return t.exports.preProcessToken(i,e)},postProcessToken:function(e,r){return t.exports.postProcessToken(i,e,r)},async:!0,bulk:!1,autoShow:!1,persistent:r,callbacks:{validPosition:i.autocompleters.notifications.show,invalidPosition:i.autocompleters.notifications.hide}}};t.exports.isValidCompletionPosition=function(e){var t=e.getCompleteToken();if(0==t.string.indexOf("?"))return!1;var i=e.getCursor(),r=e.getPreviousNonWsToken(i.line,t);return"a"==r.string?!0:"rdf:type"==r.string?!0:"rdfs:domain"==r.string?!0:"rdfs:range"==r.string?!0:!1};t.exports.preProcessToken=function(t,i){return e("./utils.js").preprocessResourceTokenForCompletion(t,i)};t.exports.postProcessToken=function(t,i,r){return e("./utils.js").postprocessResourceTokenForCompletion(t,i,r)}},{"./utils":26,"./utils.js":26,jquery:15}],24:[function(e,t){"use strict";var i=e("jquery"),r={"string-2":"prefixed",atom:"var"};t.exports=function(e,r){e.on("change",function(){t.exports.appendPrefixIfNeeded(e,r)});return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(e)},get:function(e,t){i.get("http://prefix.cc/popular/all.file.json",function(e){var i=[];for(var r in e)if("bif"!=r){var n=r+": <"+e[r]+">";i.push(n)}i.sort();t(i)})},preProcessToken:function(i){return t.exports.preprocessPrefixTokenForCompletion(e,i)},async:!0,bulk:!0,autoShow:!0,persistent:r}};t.exports.isValidCompletionPosition=function(e){var t=e.getCursor(),r=e.getTokenAt(t);if(e.getLine(t.line).length>t.ch)return!1;"ws"!=r.type&&(r=e.getCompleteToken());if(0==!r.string.indexOf("a")&&-1==i.inArray("PNAME_NS",r.state.possibleCurrent))return!1;var n=e.getPreviousNonWsToken(t.line,r);return n&&"PREFIX"==n.string.toUpperCase()?!0:!1};t.exports.preprocessPrefixTokenForCompletion=function(e,t){var i=e.getPreviousNonWsToken(e.getCursor().line,t);i&&i.string&&":"==i.string.slice(-1)&&(t={start:i.start,end:t.end,string:i.string+" "+t.string,state:t.state});return t};t.exports.appendPrefixIfNeeded=function(e,t){if(e.autocompleters.getTrie(t)&&e.options.autocompleters&&-1!=e.options.autocompleters.indexOf(t)){var i=e.getCursor(),n=e.getTokenAt(i);if("prefixed"==r[n.type]){var o=n.string.indexOf(":");if(-1!==o){var s=e.getPreviousNonWsToken(i.line,n).string.toUpperCase(),a=e.getTokenAt({line:i.line,ch:n.start});if("PREFIX"!=s&&("ws"==a.type||null==a.type)){var l=n.string.substring(0,o+1),u=e.getPrefixesFromQuery();if(null==u[l.slice(0,-1)]){var p=e.autocompleters.getTrie(t).autoComplete(l);p.length>0&&e.addPrefixes(p[0])}}}}}}},{jquery:15}],25:[function(e,t){"use strict";var i=e("jquery");t.exports=function(i,r){return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(i)},get:function(t,r){return e("./utils").fetchFromLov(i,this,t,r)},preProcessToken:function(e){return t.exports.preProcessToken(i,e)},postProcessToken:function(e,r){return t.exports.postProcessToken(i,e,r)},async:!0,bulk:!1,autoShow:!1,persistent:r,callbacks:{validPosition:i.autocompleters.notifications.show,invalidPosition:i.autocompleters.notifications.hide}}};t.exports.isValidCompletionPosition=function(e){var t=e.getCompleteToken();if(0==t.string.length)return!1;if(0==t.string.indexOf("?"))return!1;if(i.inArray("a",t.state.possibleCurrent)>=0)return!0;var r=e.getCursor(),n=e.getPreviousNonWsToken(r.line,t);return"rdfs:subPropertyOf"==n.string?!0:!1};t.exports.preProcessToken=function(t,i){return e("./utils.js").preprocessResourceTokenForCompletion(t,i)};t.exports.postProcessToken=function(t,i,r){return e("./utils.js").postprocessResourceTokenForCompletion(t,i,r)}},{"./utils":26,"./utils.js":26,jquery:15}],26:[function(e,t){"use strict";var i=e("jquery"),r=(e("./utils.js"),e("yasgui-utils")),n=function(e,t){var i=e.getPrefixesFromQuery();if(0==!t.string.indexOf("<")){t.tokenPrefix=t.string.substring(0,t.string.indexOf(":")+1);null!=i[t.tokenPrefix.slice(0,-1)]&&(t.tokenPrefixUri=i[t.tokenPrefix.slice(0,-1)])}t.autocompletionString=t.string.trim();if(0==!t.string.indexOf("<")&&t.string.indexOf(":")>-1)for(var r in i)if(0==t.string.indexOf(r)){t.autocompletionString=i[r];t.autocompletionString+=t.string.substring(r.length+1);break}0==t.autocompletionString.indexOf("<")&&(t.autocompletionString=t.autocompletionString.substring(1));-1!==t.autocompletionString.indexOf(">",t.length-1)&&(t.autocompletionString=t.autocompletionString.substring(0,t.autocompletionString.length-1));return t},o=function(e,t,i){i=t.tokenPrefix&&t.autocompletionString&&t.tokenPrefixUri?t.tokenPrefix+i.substring(t.tokenPrefixUri.length):"<"+i+">";return i},s=function(t,n,o,s){if(!o||!o.string||0==o.string.trim().length){t.autocompleters.notifications.getEl(n).empty().append("Nothing to autocomplete yet!");return!1}var a=50,l={q:o.autocompletionString,page:1};l.type="classes"==n.name?"class":"property";var u=[],p="",c=function(){p="http://lov.okfn.org/dataset/lov/api/v2/autocomplete/terms?"+i.param(l)};c();var d=function(){l.page++;c()},f=function(){i.get(p,function(e){for(var r=0;r<e.results.length;r++)u.push(i.isArray(e.results[r].uri)&&e.results[r].uri.length>0?e.results[r].uri[0]:e.results[r].uri);if(u.length<e.total_results&&u.length<a){d();f()}else{u.length>0?t.autocompleters.notifications.hide(t,n):t.autocompleters.notifications.getEl(n).text("0 matches found...");s(u)}}).fail(function(){t.autocompleters.notifications.getEl(n).empty().append("Failed fetching suggestions..")})};t.autocompleters.notifications.getEl(n).empty().append(i("<span>Fetchting autocompletions </span>")).append(i(r.svg.getElement(e("../imgs.js").loader)).addClass("notificationLoader"));f()};t.exports={fetchFromLov:s,preprocessResourceTokenForCompletion:n,postprocessResourceTokenForCompletion:o}},{"../imgs.js":29,"./utils.js":26,jquery:15,"yasgui-utils":18}],27:[function(e,t){"use strict";var i=e("jquery");t.exports=function(e){return{isValidCompletionPosition:function(){var t=e.getTokenAt(e.getCursor());if("ws"!=t.type){t=e.getCompleteToken(t);if(t&&0==t.string.indexOf("?"))return!0}return!1},get:function(t){if(0==t.trim().length)return[];var r={};i(e.getWrapperElement()).find(".cm-atom").each(function(){var e=this.innerHTML;if(0==e.indexOf("?")){var n=i(this).next(),o=n.attr("class");o&&n.attr("class").indexOf("cm-atom")>=0&&(e+=n.text());if(e.length<=1)return;if(0!==e.indexOf(t))return;if(e==t)return;r[e]=!0}});var n=[];for(var o in r)n.push(o);n.sort();return n},async:!1,bulk:!1,autoShow:!0}}},{jquery:15}],28:[function(e){var t=e("jquery"),i=e("./main.js");i.defaults=t.extend(!0,{},i.defaults,{mode:"sparql11",value:"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nSELECT * WHERE {\n ?sub ?pred ?obj .\n} \nLIMIT 10",highlightSelectionMatches:{showToken:/\w/},tabMode:"indent",lineNumbers:!0,lineWrapping:!0,foldGutter:{rangeFinder:i.fold.brace},gutters:["gutterErrorBar","CodeMirror-linenumbers","CodeMirror-foldgutter"],matchBrackets:!0,fixedGutter:!0,syntaxErrorCheck:!0,extraKeys:{"Ctrl-Space":i.autoComplete,"Cmd-Space":i.autoComplete,"Ctrl-D":i.deleteLine,"Ctrl-K":i.deleteLine,"Cmd-D":i.deleteLine,"Cmd-K":i.deleteLine,"Ctrl-/":i.commentLines,"Cmd-/":i.commentLines,"Ctrl-Alt-Down":i.copyLineDown,"Ctrl-Alt-Up":i.copyLineUp,"Cmd-Alt-Down":i.copyLineDown,"Cmd-Alt-Up":i.copyLineUp,"Shift-Ctrl-F":i.doAutoFormat,"Shift-Cmd-F":i.doAutoFormat,"Ctrl-]":i.indentMore,"Cmd-]":i.indentMore,"Ctrl-[":i.indentLess,"Cmd-[":i.indentLess,"Ctrl-S":i.storeQuery,"Cmd-S":i.storeQuery,"Ctrl-Enter":i.executeQuery,"Cmd-Enter":i.executeQuery,F11:function(e){e.setOption("fullScreen",!e.getOption("fullScreen"))},Esc:function(e){e.getOption("fullScreen")&&e.setOption("fullScreen",!1)}},cursorHeight:.9,createShareLink:i.createShareLink,consumeShareLink:i.consumeShareLink,persistent:function(e){return"yasqe_"+t(e.getWrapperElement()).closest("[id]").attr("id")+"_queryVal"},sparql:{showQueryButton:!1,endpoint:"http://dbpedia.org/sparql",requestMethod:"POST",acceptHeaderGraph:"text/turtle,*/*;q=0.9",acceptHeaderSelect:"application/sparql-results+json,*/*;q=0.9",acceptHeaderUpdate:"text/plain,*/*;q=0.9",namedGraphs:[],defaultGraphs:[],args:[],headers:{},callbacks:{beforeSend:null,complete:null,error:null,success:null},handlers:{}}})},{"./main.js":30,jquery:15}],29:[function(e,t){"use strict";t.exports={loader:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" fill="black"> <circle cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(45 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.125s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(90 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.25s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(135 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.375s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(225 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.625s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(270 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.75s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(315 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.875s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle></svg>',query:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 80 80" enable-background="new 0 0 80 80" xml:space="preserve"><g ></g><g > <path d="M64.622,2.411H14.995c-6.627,0-12,5.373-12,12v49.897c0,6.627,5.373,12,12,12h49.627c6.627,0,12-5.373,12-12V14.411 C76.622,7.783,71.249,2.411,64.622,2.411z M24.125,63.906V15.093L61,39.168L24.125,63.906z"/></g></svg>',queryInvalid:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 73.627 73.897" enable-background="new 0 0 80 80" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="warning.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" inkscape:zoom="3.1936344" inkscape:cx="36.8135" inkscape:cy="36.9485" inkscape:window-x="2625" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="svg2" /><g transform="translate(-2.995,-2.411)" /><g transform="translate(-2.995,-2.411)" ><path d="M 64.622,2.411 H 14.995 c -6.627,0 -12,5.373 -12,12 v 49.897 c 0,6.627 5.373,12 12,12 h 49.627 c 6.627,0 12,-5.373 12,-12 V 14.411 c 0,-6.628 -5.373,-12 -12,-12 z M 24.125,63.906 V 15.093 L 61,39.168 24.125,63.906 z" inkscape:connector-curvature="0" /></g><path d="M 66.129381,65.903784 H 49.769875 c -1.64721,0 -2.889385,-0.581146 -3.498678,-1.63595 -0.609293,-1.055608 -0.491079,-2.422161 0.332391,-3.848223 l 8.179753,-14.167069 c 0.822934,-1.42633 1.9477,-2.211737 3.166018,-2.211737 1.218319,0 2.343086,0.785407 3.166019,2.211737 l 8.179751,14.167069 c 0.823472,1.426062 0.941686,2.792615 0.33239,3.848223 -0.609023,1.054804 -1.851197,1.63595 -3.498138,1.63595 z M 59.618815,60.91766 c 0,-0.850276 -0.68944,-1.539719 -1.539717,-1.539719 -0.850276,0 -1.539718,0.689443 -1.539718,1.539719 0,0.850277 0.689442,1.539718 1.539718,1.539718 0.850277,0 1.539717,-0.689441 1.539717,-1.539718 z m 0.04155,-9.265919 c 0,-0.873061 -0.707939,-1.580998 -1.580999,-1.580998 -0.873061,0 -1.580999,0.707937 -1.580999,1.580998 l 0.373403,5.610965 h 0.0051 c 0.05415,0.619747 0.568548,1.10761 1.202504,1.10761 0.586239,0 1.075443,-0.415756 1.188563,-0.968489 0.0092,-0.04476 0.0099,-0.09248 0.01392,-0.138854 h 0.01072 l 0.367776,-5.611232 z" inkscape:connector-curvature="0" style="fill:#aa8800" /></svg>',download:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="tiny" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" xml:space="preserve"><g ></g><g > <path fill-rule="evenodd" fill="#000000" d="M88,84v-2c0-2.961-0.859-4-4-4H16c-2.961,0-4,0.98-4,4v2c0,3.102,1.039,4,4,4h68 C87.02,88,88,87.039,88,84z M58,12H42c-5,0-6,0.941-6,6v22H16l34,34l34-34H64V18C64,12.941,62.939,12,58,12z"/></g></svg>',share:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xml:space="preserve"><path d="M36.764,50c0,0.308-0.07,0.598-0.088,0.905l32.247,16.119c2.76-2.338,6.293-3.797,10.195-3.797 C87.89,63.228,95,70.338,95,79.109C95,87.89,87.89,95,79.118,95c-8.78,0-15.882-7.11-15.882-15.891c0-0.316,0.07-0.598,0.088-0.905 L31.077,62.085c-2.769,2.329-6.293,3.788-10.195,3.788C12.11,65.873,5,58.771,5,50c0-8.78,7.11-15.891,15.882-15.891 c3.902,0,7.427,1.468,10.195,3.797l32.247-16.119c-0.018-0.308-0.088-0.598-0.088-0.914C63.236,12.11,70.338,5,79.118,5 C87.89,5,95,12.11,95,20.873c0,8.78-7.11,15.891-15.882,15.891c-3.911,0-7.436-1.468-10.195-3.806L36.676,49.086 C36.693,49.394,36.764,49.684,36.764,50z"/></svg>',warning:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" viewBox="0 0 66.399998 66.399998" enable-background="new 0 0 69.3 69.3" xml:space="preserve" height="100%" width="100%" inkscape:version="0.48.4 r9939" ><g transform="translate(-1.5,-1.5)" style="fill:#ff0000"><path d="M 34.7,1.5 C 16.4,1.5 1.5,16.4 1.5,34.7 1.5,53 16.4,67.9 34.7,67.9 53,67.9 67.9,53 67.9,34.7 67.9,16.4 53,1.5 34.7,1.5 z m 0,59.4 C 20.2,60.9 8.5,49.1 8.5,34.7 8.5,20.2 20.3,8.5 34.7,8.5 c 14.4,0 26.2,11.8 26.2,26.2 0,14.4 -11.8,26.2 -26.2,26.2 z" inkscape:connector-curvature="0" style="fill:#ff0000" /><path d="m 34.6,47.1 c -1.4,0 -2.5,0.5 -3.5,1.5 -0.9,1 -1.4,2.2 -1.4,3.6 0,1.6 0.5,2.8 1.5,3.8 1,0.9 2.1,1.3 3.4,1.3 1.3,0 2.4,-0.5 3.4,-1.4 1,-0.9 1.5,-2.2 1.5,-3.7 0,-1.4 -0.5,-2.6 -1.4,-3.6 -0.9,-1 -2.1,-1.5 -3.5,-1.5 z" inkscape:connector-curvature="0" style="fill:#ff0000" /><path d="m 34.8,13.9 c -1.5,0 -2.8,0.5 -3.7,1.6 -0.9,1 -1.4,2.4 -1.4,4.2 0,1.1 0.1,2.9 0.2,5.6 l 0.8,13.1 c 0.2,1.8 0.4,3.2 0.9,4.1 0.5,1.2 1.5,1.8 2.9,1.8 1.3,0 2.3,-0.7 2.9,-1.9 0.5,-1 0.7,-2.3 0.9,-4 L 39.4,25 c 0.1,-1.3 0.2,-2.5 0.2,-3.8 0,-2.2 -0.3,-3.9 -0.8,-5.1 -0.5,-1 -1.6,-2.2 -4,-2.2 z" inkscape:connector-curvature="0" style="fill:#ff0000" /></g></svg>',fullscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="640" inkscape:window-height="480" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="0" inkscape:current-layer="Layer_1" /><path d="m -7.962963,-10 v 38.889 l 16.667,-16.667 16.667,16.667 5.555,-5.555 -16.667,-16.667 16.667,-16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 92.037037,-10 v 38.889 l -16.667,-16.667 -16.666,16.667 -5.556,-5.555 16.666,-16.667 -16.666,-16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M -7.962963,90 V 51.111 l 16.667,16.666 16.667,-16.666 5.555,5.556 -16.667,16.666 16.667,16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M 92.037037,90 V 51.111 l -16.667,16.666 -16.666,-16.666 -5.556,5.556 16.666,16.666 -16.666,16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>',smallscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="Layer_1" /><path d="m 30.926037,28.889 0,-38.889 -16.667,16.667 -16.667,-16.667 -5.555,5.555 16.667,16.667 -16.667,16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,28.889 0,-38.889 16.667,16.667 16.666,-16.667 5.556,5.555 -16.666,16.667 16.666,16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 30.926037,51.111 0,38.889 -16.667,-16.666 -16.667,16.666 -5.555,-5.556 16.667,-16.666 -16.667,-16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,51.111 0,38.889 16.667,-16.666 16.666,16.666 5.556,-5.556 -16.666,-16.666 16.666,-16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>'}
},{}],30:[function(e,t){"use strict";window.console=window.console||{log:function(){}};var i=e("jquery"),r=e("codemirror"),n=e("./utils.js"),o=e("yasgui-utils"),s=e("./imgs.js");e("../lib/deparam.js");e("codemirror/addon/fold/foldcode.js");e("codemirror/addon/fold/foldgutter.js");e("codemirror/addon/fold/xml-fold.js");e("codemirror/addon/fold/brace-fold.js");e("codemirror/addon/hint/show-hint.js");e("codemirror/addon/search/searchcursor.js");e("codemirror/addon/edit/matchbrackets.js");e("codemirror/addon/runmode/runmode.js");e("codemirror/addon/display/fullscreen.js");e("../lib/flint.js");var a=t.exports=function(e,t){var n=i("<div>",{"class":"yasqe"}).appendTo(i(e));t=l(t);var o=u(r(n[0],t));d(o);return o},l=function(e){var t=i.extend(!0,{},a.defaults,e);return t},u=function(t){t.autocompleters=e("./autocompleters/autocompleterBase.js")(a,t);t.options.autocompleters&&t.options.autocompleters.forEach(function(e){a.Autocompleters[e]&&t.autocompleters.init(e,a.Autocompleters[e])});t.getCompleteToken=function(i,r){return e("./tokenUtils.js").getCompleteToken(t,i,r)};t.getPreviousNonWsToken=function(i,r){return e("./tokenUtils.js").getPreviousNonWsToken(t,i,r)};t.getNextNonWsToken=function(i,r){return e("./tokenUtils.js").getNextNonWsToken(t,i,r)};t.query=function(e){a.executeQuery(t,e)};t.getUrlArguments=function(e){return a.getUrlArguments(t,e)};t.getPrefixesFromQuery=function(){return e("./prefixUtils.js").getPrefixesFromQuery(t)};t.addPrefixes=function(i){return e("./prefixUtils.js").addPrefixes(t,i)};t.removePrefixes=function(i){return e("./prefixUtils.js").removePrefixes(t,i)};t.getValueWithoutComments=function(){var e="";a.runMode(t.getValue(),"sparql11",function(t,i){"comment"!=i&&(e+=t)});return e};t.getQueryType=function(){return t.queryType};t.getQueryMode=function(){var e=t.getQueryType();return"INSERT"==e||"DELETE"==e||"LOAD"==e||"CLEAR"==e||"CREATE"==e||"DROP"==e||"COPY"==e||"MOVE"==e||"ADD"==e?"update":"query"};t.setCheckSyntaxErrors=function(e){t.options.syntaxErrorCheck=e;h(t)};t.enableCompleter=function(e){p(t.options,e);a.Autocompleters[e]&&t.autocompleters.init(e,a.Autocompleters[e])};t.disableCompleter=function(e){c(t.options,e)};return t},p=function(e,t){e.autocompleters||(e.autocompleters=[]);e.autocompleters.push(t)},c=function(e,t){if("object"==typeof e.autocompleters){var r=i.inArray(t,e.autocompleters);if(r>=0){e.autocompleters.splice(r,1);c(e,t)}}},d=function(e){var t=n.getPersistencyId(e,e.options.persistent);if(t){var r=o.storage.get(t);r&&e.setValue(r)}a.drawButtons(e);e.on("blur",function(e){a.storeQuery(e)});e.on("change",function(e){h(e);a.updateQueryButton(e);a.positionButtons(e)});e.on("changes",function(){h(e);a.updateQueryButton(e);a.positionButtons(e)});e.on("cursorActivity",function(e){f(e)});e.prevQueryValid=!1;h(e);a.positionButtons(e);if(e.options.consumeShareLink){var s=i.deparam(window.location.search.substring(1));e.options.consumeShareLink(e,s)}},f=function(e){e.cursor=i(".CodeMirror-cursor");e.buttons&&e.buttons.is(":visible")&&e.cursor.length>0&&(n.elementsOverlap(e.cursor,e.buttons)?e.buttons.find("svg").attr("opacity","0.2"):e.buttons.find("svg").attr("opacity","1.0"))},h=function(t,r){t.queryValid=!0;t.clearGutter("gutterErrorBar");for(var n=null,a=0;a<t.lineCount();++a){var l=!1;t.prevQueryValid||(l=!0);var u=t.getTokenAt({line:a,ch:t.getLine(a).length},l),n=u.state;t.queryType=n.queryType;if(0==n.OK){if(!t.options.syntaxErrorCheck){i(t.getWrapperElement).find(".sp-error").css("color","black");return}var p=o.svg.getElement(s.warning);n.possibleCurrent&&n.possibleCurrent.length>0&&e("./tooltip")(t,p,function(){var e=[];n.possibleCurrent.forEach(function(t){e.push("<strong style='text-decoration:underline'>"+i("<div/>").text(t).html()+"</strong>")});return"This line is invalid. Expected: "+e.join(", ")});p.style.marginTop="2px";p.style.marginLeft="2px";p.className="parseErrorIcon";t.setGutterMarker(a,"gutterErrorBar",p);t.queryValid=!1;break}}t.prevQueryValid=t.queryValid;if(r&&null!=n&&void 0!=n.stack){var c=n.stack,d=n.stack.length;d>1?t.queryValid=!1:1==d&&"solutionModifier"!=c[0]&&"?limitOffsetClauses"!=c[0]&&"?offsetClause"!=c[0]&&(t.queryValid=!1)}};i.extend(a,r);a.Autocompleters={};a.registerAutocompleter=function(e,t){a.Autocompleters[e]=t;p(a.defaults,e)};a.autoComplete=function(e){e.autocompleters.autoComplete(!1)};a.registerAutocompleter("prefixes",e("./autocompleters/prefixes.js"));a.registerAutocompleter("properties",e("./autocompleters/properties.js"));a.registerAutocompleter("classes",e("./autocompleters/classes.js"));a.registerAutocompleter("variables",e("./autocompleters/variables.js"));a.positionButtons=function(e){var t=i(e.getWrapperElement()).find(".CodeMirror-vscrollbar"),r=0;t.is(":visible")&&(r=t.outerWidth());e.buttons.is(":visible")&&e.buttons.css("right",r+6)};a.createShareLink=function(e){var t=i.deparam(window.location.search.substring(1));t.query=e.getValue();return t};a.consumeShareLink=function(e,t){t.query&&e.setValue(t.query)};a.drawButtons=function(e){e.buttons=i("<div class='yasqe_buttons'></div>").appendTo(i(e.getWrapperElement()));if(e.options.createShareLink){var t=i(o.svg.getElement(s.share));t.click(function(r){r.stopPropagation();var n=i("<div class='yasqe_sharePopup'></div>").appendTo(e.buttons);i("html").click(function(){n&&n.remove()});n.click(function(e){e.stopPropagation()});var o=i("<textarea></textarea>").val(location.protocol+"//"+location.host+location.pathname+"?"+i.param(e.options.createShareLink(e)));o.focus(function(){var e=i(this);e.select();e.mouseup(function(){e.unbind("mouseup");return!1})});n.empty().append(o);var s=t.position();n.css("top",s.top+t.outerHeight()+"px").css("left",s.left+t.outerWidth()-n.outerWidth()+"px")}).addClass("yasqe_share").attr("title","Share your query").appendTo(e.buttons)}var r=i("<div>",{"class":"fullscreenToggleBtns"}).append(i(o.svg.getElement(s.fullscreen)).addClass("yasqe_fullscreenBtn").attr("title","Set editor full screen").click(function(){e.setOption("fullScreen",!0)})).append(i(o.svg.getElement(s.smallscreen)).addClass("yasqe_smallscreenBtn").attr("title","Set editor to normale size").click(function(){e.setOption("fullScreen",!1)}));e.buttons.append(r);if(e.options.sparql.showQueryButton){i("<div>",{"class":"yasqe_queryButton"}).click(function(){if(i(this).hasClass("query_busy")){e.xhr&&e.xhr.abort();a.updateQueryButton(e)}else e.query()}).appendTo(e.buttons);a.updateQueryButton(e)}};var E={busy:"loader",valid:"query",error:"queryInvalid"};a.updateQueryButton=function(e,t){var r=i(e.getWrapperElement()).find(".yasqe_queryButton");if(0!=r.length){if(!t){t="valid";e.queryValid===!1&&(t="error")}if(t!=e.queryStatus&&("busy"==t||"valid"==t||"error"==t)){r.empty().removeClass(function(e,t){return t.split(" ").filter(function(e){return 0==e.indexOf("query_")}).join(" ")}).addClass("query_"+t);o.svg.draw(r,s[E[t]]);e.queryStatus=t}}};a.fromTextArea=function(e,t){t=l(t);var n=(i("<div>",{"class":"yasqe"}).insertBefore(i(e)).append(i(e)),u(r.fromTextArea(e,t)));d(n);return n};a.storeQuery=function(e){var t=n.getPersistencyId(e,e.options.persistent);t&&o.storage.set(t,e.getValue(),"month")};a.commentLines=function(e){for(var t=e.getCursor(!0).line,i=e.getCursor(!1).line,r=Math.min(t,i),n=Math.max(t,i),o=!0,s=r;n>=s;s++){var a=e.getLine(s);if(0==a.length||"#"!=a.substring(0,1)){o=!1;break}}for(var s=r;n>=s;s++)o?e.replaceRange("",{line:s,ch:0},{line:s,ch:1}):e.replaceRange("#",{line:s,ch:0})};a.copyLineUp=function(e){var t=e.getCursor(),i=e.lineCount();e.replaceRange("\n",{line:i-1,ch:e.getLine(i-1).length});for(var r=i;r>t.line;r--){var n=e.getLine(r-1);e.replaceRange(n,{line:r,ch:0},{line:r,ch:e.getLine(r).length})}};a.copyLineDown=function(e){a.copyLineUp(e);var t=e.getCursor();t.line++;e.setCursor(t)};a.doAutoFormat=function(e){if(e.somethingSelected()){var t={line:e.getCursor(!1).line,ch:e.getSelection().length};m(e,e.getCursor(!0),t)}else{var i=e.lineCount(),r=e.getTextArea().value.length;m(e,{line:0,ch:0},{line:i,ch:r})}};var m=function(e,t,i){var r=e.indexFromPos(t),n=e.indexFromPos(i),o=g(e.getValue(),r,n);e.operation(function(){e.replaceRange(o,t,i);for(var n=e.posFromIndex(r).line,s=e.posFromIndex(r+o.length).line,a=n;s>=a;a++)e.indentLine(a,"smart")})},g=function(e,t,n){e=e.substring(t,n);var o=[["keyword","ws","prefixed","ws","uri"],["keyword","ws","uri"]],s=["{",".",";"],a=["}"],l=function(e){for(var t=0;t<o.length;t++)if(c.valueOf().toString()==o[t].valueOf().toString())return 1;for(var t=0;t<s.length;t++)if(e==s[t])return 1;for(var t=0;t<a.length;t++)if(""!=i.trim(p)&&e==a[t])return-1;return 0},u="",p="",c=[];r.runMode(e,"sparql11",function(e,t){c.push(t);var i=l(e,t);if(0!=i){if(1==i){u+=e+"\n";p=""}else{u+="\n"+e;p=e}c=[]}else{p+=e;u+=e}1==c.length&&"sp-ws"==c[0]&&(c=[])});return i.trim(u.replace(/\n\s*\n/g,"\n"))};e("./sparql.js"),e("./defaults.js");a.version={CodeMirror:r.version,YASQE:e("../package.json").version,jquery:i.fn.jquery,"yasgui-utils":o.version}},{"../lib/deparam.js":2,"../lib/flint.js":3,"../package.json":21,"./autocompleters/autocompleterBase.js":22,"./autocompleters/classes.js":23,"./autocompleters/prefixes.js":24,"./autocompleters/properties.js":25,"./autocompleters/variables.js":27,"./defaults.js":28,"./imgs.js":29,"./prefixUtils.js":31,"./sparql.js":32,"./tokenUtils.js":33,"./tooltip":34,"./utils.js":35,codemirror:14,"codemirror/addon/display/fullscreen.js":5,"codemirror/addon/edit/matchbrackets.js":6,"codemirror/addon/fold/brace-fold.js":7,"codemirror/addon/fold/foldcode.js":8,"codemirror/addon/fold/foldgutter.js":9,"codemirror/addon/fold/xml-fold.js":10,"codemirror/addon/hint/show-hint.js":11,"codemirror/addon/runmode/runmode.js":12,"codemirror/addon/search/searchcursor.js":13,jquery:15,"yasgui-utils":18}],31:[function(e,t){"use strict";var i=function(e,t){var i=e.getPrefixesFromQuery();if("string"==typeof t)r(e,t);else for(var n in t)n in i||r(e,n+": <"+t[n]+">")},r=function(e,t){for(var i=null,r=0,n=e.lineCount(),o=0;n>o;o++){var a=e.getNextNonWsToken(o);if(null!=a&&("PREFIX"==a.string||"BASE"==a.string)){i=a;r=o}}if(null==i)e.replaceRange("PREFIX "+t+"\n",{line:0,ch:0});else{var l=s(e,r);e.replaceRange("\n"+l+"PREFIX "+t,{line:r})}},n=function(e,t){var i=function(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")};for(var r in t)e.setValue(e.getValue().replace(new RegExp("PREFIX\\s*"+r+":\\s*"+i("<"+t[r]+">")+"\\s*","ig"),""))},o=function(e){for(var t={},i=!0,r=function(n,s){if(i){s||(s=1);var a=e.getNextNonWsToken(o,s);if(a){-1==a.state.possibleCurrent.indexOf("PREFIX")&&-1==a.state.possibleNext.indexOf("PREFIX")&&(i=!1);if("PREFIX"==a.string.toUpperCase()){var l=e.getNextNonWsToken(o,a.end+1);if(l){var u=e.getNextNonWsToken(o,l.end+1);if(u){var p=u.string;0==p.indexOf("<")&&(p=p.substring(1));">"==p.slice(-1)&&(p=p.substring(0,p.length-1));t[l.string.slice(0,-1)]=p;r(n,u.end+1)}else r(n,l.end+1)}else r(n,a.end+1)}else r(n,a.end+1)}}},n=e.lineCount(),o=0;n>o&&i;o++)r(o);return t},s=function(e,t,i){void 0==i&&(i=1);var r=e.getTokenAt({line:t,ch:i});return null==r||void 0==r||"ws"!=r.type?"":r.string+s(e,t,r.end+1)};t.exports={addPrefixes:i,getPrefixesFromQuery:o,removePrefixes:n}},{}],32:[function(e){"use strict";var t=e("jquery"),i=e("./main.js");i.executeQuery=function(e,n){var o="function"==typeof n?n:null,s="object"==typeof n?n:{};e.options.sparql&&(s=t.extend({},e.options.sparql,s));s.handlers&&t.extend(!0,s.callbacks,s.handlers);if(s.endpoint&&0!=s.endpoint.length){var a={url:"function"==typeof s.endpoint?s.endpoint(e):s.endpoint,type:"function"==typeof s.requestMethod?s.requestMethod(e):s.requestMethod,headers:{Accept:r(e,s)}},l=!1;if(s.callbacks)for(var u in s.callbacks)if(s.callbacks[u]){l=!0;a[u]=s.callbacks[u]}a.data=e.getUrlArguments(s);if(l||o){o&&(a.complete=o);s.headers&&!t.isEmptyObject(s.headers)&&t.extend(a.headers,s.headers);i.updateQueryButton(e,"busy");var p=function(){i.updateQueryButton(e)};a.complete=a.complete?[p,a.complete]:p;e.xhr=t.ajax(a)}}};i.getUrlArguments=function(e,i){var r=e.getQueryMode(),n=[{name:e.getQueryMode(),value:e.getValue()}];if(i.namedGraphs&&i.namedGraphs.length>0)for(var o="query"==r?"named-graph-uri":"using-named-graph-uri ",s=0;s<i.namedGraphs.length;s++)n.push({name:o,value:i.namedGraphs[s]});if(i.defaultGraphs&&i.defaultGraphs.length>0)for(var o="query"==r?"default-graph-uri":"using-graph-uri ",s=0;s<i.defaultGraphs.length;s++)n.push({name:o,value:i.defaultGraphs[s]});i.args&&i.args.length>0&&t.merge(n,i.args);return n};var r=function(e,t){var i=null;if(!t.acceptHeader||t.acceptHeaderGraph||t.acceptHeaderSelect||t.acceptHeaderUpdate)if("update"==e.getQueryMode())i="function"==typeof t.acceptHeader?t.acceptHeaderUpdate(e):t.acceptHeaderUpdate;else{var r=e.getQueryType();i="DESCRIBE"==r||"CONSTRUCT"==r?"function"==typeof t.acceptHeaderGraph?t.acceptHeaderGraph(e):t.acceptHeaderGraph:"function"==typeof t.acceptHeaderSelect?t.acceptHeaderSelect(e):t.acceptHeaderSelect}else i="function"==typeof t.acceptHeader?t.acceptHeader(e):t.acceptHeader;return i}},{"./main.js":30,jquery:15}],33:[function(e,t){"use strict";var i=function(e,t,r){r||(r=e.getCursor());t||(t=e.getTokenAt(r));var n=e.getTokenAt({line:r.line,ch:t.start});if(null!=n.type&&"ws"!=n.type&&null!=t.type&&"ws"!=t.type){t.start=n.start;t.string=n.string+t.string;return i(e,t,{line:r.line,ch:n.start})}if(null!=t.type&&"ws"==t.type){t.start=t.start+1;t.string=t.string.substring(1);return t}return t},r=function(e,t,i){var n=e.getTokenAt({line:t,ch:i.start});null!=n&&"ws"==n.type&&(n=r(e,t,n));return n},n=function(e,t,i){void 0==i&&(i=1);var r=e.getTokenAt({line:t,ch:i});return null==r||void 0==r||r.end<i?null:"ws"==r.type?n(e,t,r.end+1):r};t.exports={getPreviousNonWsToken:r,getCompleteToken:i,getNextNonWsToken:n}},{}],34:[function(e,t){"use strict";{var i=e("jquery");e("./utils.js")}t.exports=function(e,t,r){var n,t=i(t);t.hover(function(){"function"==typeof r&&(r=r());n=i("<div>").addClass("yasqe_tooltip").html(r).appendTo(t);o()},function(){i(".yasqe_tooltip").remove()});var o=function(){if(i(e.getWrapperElement()).offset().top>=n.offset().top){n.css("bottom","auto");n.css("top","26px")}}}},{"./utils.js":35,jquery:15}],35:[function(e,t){"use strict";var i=e("jquery"),r=function(e,t){var i=!1;try{void 0!==e[t]&&(i=!0)}catch(r){}return i},n=function(e,t){var i=null;t&&(i="string"==typeof t?t:t(e));return i},o=function(){function e(e){var t,r,n;t=i(e).offset();r=i(e).width();n=i(e).height();return[[t.left,t.left+r],[t.top,t.top+n]]}function t(e,t){var i,r;i=e[0]<t[0]?e:t;r=e[0]<t[0]?t:e;return i[1]>r[0]||i[0]===r[0]}return function(i,r){var n=e(i),o=e(r);return t(n[0],o[0])&&t(n[1],o[1])}}();t.exports={keyExists:r,getPersistencyId:n,elementsOverlap:o}},{jquery:15}]},{},[1])(1)});
//# sourceMappingURL=yasqe.bundled.min.js.map |
ajax/libs/forerunnerdb/1.3.40/fdb-core+persist.min.js | boneskull/cdnjs | !function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){{var d=a("../lib/Core");a("../lib/Persist")}"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":4,"../lib/Persist":23}],2:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m;d=a("./Shared");var n=function(a){this.init.apply(this,arguments)};n.prototype.init=function(a){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._deferQueue={insert:[],update:[],remove:[],upsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._subsetOf(this)},d.addModule("Collection",n),d.mixin(n.prototype,"Mixin.Common"),d.mixin(n.prototype,"Mixin.Events"),d.mixin(n.prototype,"Mixin.ChainReactor"),d.mixin(n.prototype,"Mixin.CRUD"),d.mixin(n.prototype,"Mixin.Constants"),d.mixin(n.prototype,"Mixin.Triggers"),d.mixin(n.prototype,"Mixin.Sorting"),d.mixin(n.prototype,"Mixin.Matching"),d.mixin(n.prototype,"Mixin.Updating"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Crc"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n.prototype.crc=k,d.synthesize(n.prototype,"state"),d.synthesize(n.prototype,"name"),n.prototype.data=function(){return this._data},n.prototype.drop=function(a){var b;if("dropped"===this._state)return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log("Dropping collection "+this._name),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},n.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey!==a&&(this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex()),this):this._primaryKey},n.prototype._onInsert=function(a,b){this.emit("insert",a,b)},n.prototype._onUpdate=function(a){this.emit("update",a)},n.prototype._onRemove=function(a){this.emit("remove",a)},d.synthesize(n.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&this.primaryKey(a.primaryKey()),this.$super.apply(this,arguments)}),n.prototype.setData=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this.emit("setData",this._data,e)}return c&&c(!1),this},n.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw'ForerunnerDB.Collection "'+this.name()+'": Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: '+d[this._primaryKey]}else h.set(d[k],d);e=JSON.stringify(d),i.set(d[k],e),j.set(e,d)}},n.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},n.prototype.truncate=function(){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this.deferEmit("change",{type:"truncate"}),this},n.prototype.upsert=function(a,b){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(a.length>f)return this._deferQueue.upsert=e.concat(a),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a);break;case"update":g.result=this.update(c,a)}return g}return b&&b(),{}},n.prototype.update=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';b=this.decouple(b),b=this.transformIn(b),this.debug()&&console.log('Updating some collection data for collection "'+this.name()+'"');var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},h=f.updateObject(i,e.update,e.query,e.options,""),f.processTrigger(e,f.TYPE_UPDATE,f.PHASE_BEFORE,d,i)!==!1?(h=f.updateObject(d,i,e.query,e.options,""),f.processTrigger(e,f.TYPE_UPDATE,f.PHASE_AFTER,d,i)):h=!1):h=f.updateObject(d,b,a,c,""),h};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:d},c),g.time("Resolve chains"),this._onUpdate(e),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},n.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw'ForerunnerDB.Collection "'+this.name()+'": Primary key violation in update! Key violated: '+a[this._primaryKey];return!0},n.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)},n.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q=!1,r=!1;for(p in b)if(b.hasOwnProperty(p)){if(g=!1,"$"===p.substr(0,1))switch(p){case"$key":case"$index":case"$data":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)r=this.updateObject(a,b.$each[j],c,d,e),r&&(q=!0);q=q||r;break;default:g=!0,r=this.updateObject(a,b[p],c,d,e,p),q=q||r}if(this._isPositionalKey(p)&&(g=!0,p=p.substr(0,p.length-2),m=new h(e+"."+p),a[p]&&a[p]instanceof Array&&a[p].length)){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],m.value(c)[0],"",{})&&i.push(j);for(j=0;j<i.length;j++)r=this.updateObject(a[p][i[j]],b[p+".$"],c,d,e+"."+p,f),q=q||r}if(!g)if(f||"object"!=typeof b[p])switch(f){case"$inc":this._updateIncrement(a,p,b[p]),q=!0;break;case"$cast":switch(b[p]){case"array":a[p]instanceof Array||(this._updateProperty(a,p,b.$data||[]),q=!0);break;case"object":(!(a[p]instanceof Object)||a[p]instanceof Array)&&(this._updateProperty(a,p,b.$data||{}),q=!0);break;case"number":"number"!=typeof a[p]&&(this._updateProperty(a,p,Number(a[p])),q=!0);break;case"string":"string"!=typeof a[p]&&(this._updateProperty(a,p,String(a[p])),q=!0);break;default:throw'ForerunnerDB.Collection "'+this.name()+'": Cannot update cast to unknown type: '+b[p]}break;case"$push":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot push to a key that is not an array! ('+p+")";if(void 0!==b[p].$position&&b[p].$each instanceof Array)for(l=b[p].$position,k=b[p].$each.length,j=0;k>j;j++)this._updateSplicePush(a[p],l+j,b[p].$each[j]);else if(b[p].$each instanceof Array)for(k=b[p].$each.length,j=0;k>j;j++)this._updatePush(a[p],b[p].$each[j]);else this._updatePush(a[p],b[p]);q=!0;break;case"$pull":if(a[p]instanceof Array){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],b[p],"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[p],i[k]),q=!0}break;case"$pullAll":if(a[p]instanceof Array){if(!(b[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot pullAll without being given an array of values to pull! ('+p+")";if(i=a[p],k=i.length,k>0)for(;k--;){for(l=0;l<b[p].length;l++)i[k]===b[p][l]&&(this._updatePull(a[p],k),k--,q=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot addToSet on a key that is not an array! ('+p+")";var s,t,u,v,w=a[p],x=w.length,y=!0,z=d&&d.$addToSet;for(b[p].$key?(u=!1,v=new h(b[p].$key),t=v.value(b[p])[0],delete b[p].$key):z&&z.key?(u=!1,v=new h(z.key),t=v.value(b[p])[0]):(t=JSON.stringify(b[p]),u=!0),s=0;x>s;s++)if(u){if(JSON.stringify(w[s])===t){y=!1;break}}else if(t===v.value(w[s])[0]){y=!1;break}y&&(this._updatePush(a[p],b[p]),q=!0);break;case"$splicePush":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush with a key that is not an array! ('+p+")";if(l=b.$index,void 0===l)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush without a $index integer value!';delete b.$index,l>a[p].length&&(l=a[p].length),this._updateSplicePush(a[p],l,b[p]),q=!0;break;case"$move":if(!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot move on a key that is not an array! ('+p+")";for(j=0;j<a[p].length;j++)if(this._match(a[p][j],b[p],"",{})){var A=b.$index;if(void 0===A)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot move without a $index integer value!';delete b.$index,this._updateSpliceMove(a[p],j,A),q=!0;break}break;case"$mul":this._updateMultiply(a,p,b[p]),q=!0;break;case"$rename":this._updateRename(a,p,b[p]),q=!0;break;case"$overwrite":this._updateOverwrite(a,p,b[p]),q=!0;break;case"$unset":this._updateUnset(a,p),q=!0;break;case"$clear":this._updateClear(a,p),q=!0;break;case"$pop":if(!(a[p]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot pop from a key that is not an array! ('+p+")";this._updatePop(a[p],b[p])&&(q=!0);break;default:a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}else if(null!==a[p]&&"object"==typeof a[p])if(n=a[p]instanceof Array,o=b[p]instanceof Array,n||o)if(!o&&n)for(j=0;j<a[p].length;j++)r=this.updateObject(a[p][j],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0);else r=this.updateObject(a[p],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}return q},n.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},n.prototype.remove=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';var d,e,f,g,h,i,j,k,l=this;if(a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);this.chainSend("remove",{query:a,dataSet:d},b),(!b||b&&!b.noEmit)&&this._onRemove(d),this.deferEmit("change",{type:"remove",data:d})}return c&&c(!1,d),d},n.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)},n.prototype.deferEmit=function(){var a,b=this;this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(a=arguments,this._changeTimeout&&clearTimeout(this._changeTimeout),this._changeTimeout=setTimeout(function(){b.debug()&&console.log("ForerunnerDB.Collection: Emitting "+a[0]),b.emit.apply(b,a)},100))},n.prototype.processQueue=function(a,b){var c=this._deferQueue[a],d=this._deferThreshold[a],e=this._deferTime[a];if(c.length){var f,g=this;c.length&&(f=c.length>d?c.splice(0,d):c.splice(0,c.length),this[a](f)),setTimeout(function(){g.processQueue(a,b)},e)}else b&&b()},n.prototype.insert=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},n.prototype._insertHandle=function(a,b,c){var d,e,f=this._deferQueue.insert,g=this._deferThreshold.insert,h=[],i=[];if(a instanceof Array){if(a.length>g)return this._deferQueue.insert=f.concat(a),void this.processQueue("insert",c);for(e=0;e<a.length;e++)d=this._insert(a[e],b+e),d===!0?h.push(a[e]):i.push({doc:a[e],reason:d})}else d=this._insert(a,b),d===!0?h.push(a):i.push({doc:a,reason:d});return this.chainSend("insert",a,{index:b}),this._onInsert(h,i),c&&c(),this.deferEmit("change",{type:"insert",data:h}),{inserted:h,failed:i}},n.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this;if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a)},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return!1;e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},n.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},n.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},n.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},n.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=JSON.stringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},n.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=JSON.stringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},n.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},n.prototype.indexOfDocById=function(a){return this._data.indexOf(this._primaryIndex.get(a[this._primaryKey]))},n.prototype.subset=function(a,b){var c=this.find(a,b);return(new n)._subsetOf(this).primaryKey(this._primaryKey).setData(c)},n.prototype.subsetOf=function(){return this.__subsetOf},n.prototype._subsetOf=function(a){return this.__subsetOf=a,this},n.prototype.distinct=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},n.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},n.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new n,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=JSON.stringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},n.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},n.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},n.prototype.find=function(a,b){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';a=a||{},b=this.options(b);var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C=this._metrics.create("find"),D=this.primaryKey(),E=this,F=!0,G={},H=[],I=[],J=[],K={},L=function(b){return E._match(b,a,"and",K)};if(C.start(),a){if(C.time("analyseQuery"),c=this._analyseQuery(a,b,C),C.time("analyseQuery"),C.data("analysis",c),c.hasJoin&&c.queriesJoin){for(C.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],G[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i);C.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(C.data("index.potential",c.indexMatch),C.data("index.used",c.indexMatch[0].index),C.time("indexLookup"),e=c.indexMatch[0].lookup,C.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(F=!1)):C.flag("usedIndex",!1),F&&(e&&e.length?(d=e.length,C.time("tableScan: "+d),e=e.filter(L)):(d=this._data.length,C.time("tableScan: "+d),e=this._data.filter(L)),b.$orderBy&&(C.time("sort"),e=this.sort(b.$orderBy,e),C.time("sort")),C.time("tableScan: "+d)),b.$limit&&e&&e.length>b.$limit&&(e.length=b.$limit,C.data("limit",b.$limit)),b.$decouple&&(C.time("decouple"),e=this.decouple(e),C.time("decouple"),C.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(s=k,l=this._db.collection(k),m=b.$join[f][k],t=0;t<e.length;t++){o={},p=!1,q=!1;for(n in m)if(m.hasOwnProperty(n))if("$"===n.substr(0,1))switch(n){case"$as":s=m[n];break;case"$multi":p=m[n];break;case"$require":q=m[n]}else o[n]=new h(m[n]).value(e[t])[0];r=l.find(o),!q||q&&r[0]?e[t][s]=p===!1?r[0]:r:H.push(e[t])}C.data("flag.join",!0)}if(H.length){for(C.time("removalQueue"),v=0;v<H.length;v++)u=e.indexOf(H[v]),u>-1&&e.splice(u,1);C.time("removalQueue")}if(b.$transform){for(C.time("transform"),v=0;v<e.length;v++)e.splice(v,1,b.$transform(e[v]));C.time("transform"),C.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(C.time("transformOut"),e=this.transformOut(e),C.time("transformOut")),C.data("results",e.length)}else e=[];C.time("scanFields");for(v in b)b.hasOwnProperty(v)&&0!==v.indexOf("$")&&(1===b[v]?I.push(v):0===b[v]&&J.push(v));if(C.time("scanFields"),I.length||J.length){for(C.data("flag.limitFields",!0),C.data("limitFields.on",I),C.data("limitFields.off",J),C.time("limitFields"),v=0;v<e.length;v++){B=e[v];for(w in B)B.hasOwnProperty(w)&&(I.length&&w!==D&&-1===I.indexOf(w)&&delete B[w],J.length&&J.indexOf(w)>-1&&delete B[w])}C.time("limitFields")}if(b.$elemMatch){C.data("flag.elemMatch",!0),C.time("projection-elemMatch");for(v in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(v))for(y=new h(v),w=0;w<e.length;w++)if(z=y.value(e[w])[0],z&&z.length)for(x=0;x<z.length;x++)if(E._match(z[x],b.$elemMatch[v],"",{})){y.set(e[w],v,[z[x]]);break}C.time("projection-elemMatch")}if(b.$elemsMatch){C.data("flag.elemsMatch",!0),C.time("projection-elemsMatch");for(v in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(v))for(y=new h(v),w=0;w<e.length;w++)if(z=y.value(e[w])[0],z&&z.length){for(A=[],x=0;x<z.length;x++)E._match(z[x],b.$elemsMatch[v],"",{})&&A.push(z[x]);y.set(e[w],v,A)}C.time("projection-elemsMatch")}return C.stop(),e.__fdbOp=C,e},n.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},n.prototype.indexOf=function(a){var b=this.find(a,{$decouple:!1})[0];return b?this._data.indexOf(b):void 0},n.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},n.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformIn(a[b]);return c}return this._transformIn(a)}return a},n.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformOut(a[b]);return c}return this._transformOut(a)}return a},n.prototype.sort=function(a,b){b=b||[];var c,d,e=[];for(c in a)a.hasOwnProperty(c)&&(d={},d[c]=a[c],d.___fdbKey=c,e.push(d));return e.length<2?this._sort(a,b):this._bucketSort(e,b)},n.prototype._bucketSort=function(a,b){var c,d,e,f=a.shift(),g=[];if(a.length>0){b=this._sort(f,b),d=this.bucket(f.___fdbKey,b);for(e in d)d.hasOwnProperty(e)&&(c=[].concat(a),g=g.concat(this._bucketSort(c,d[e])));return g}return this._sort(f,b)},n.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw'ForerunnerDB.Collection "'+this.name()+'": $orderBy clause has invalid direction: '+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},n.prototype.bucket=function(a,b){var c,d={};for(c=0;c<b.length;c++)d[b[c][a]]=d[b[c][a]]||[],d[b[c][a]].push(b[c]);return d},n.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},q=[],r=[];if(c.time("checkIndexes"),m=new h,n=m.countKeys(a)){void 0!==a[this._primaryKey]&&(c.time("checkIndexMatch: Primary Key"),p.indexMatch.push({lookup:this._primaryIndex.lookup(a,b),keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key"));for(o in this._indexById)if(this._indexById.hasOwnProperty(o)&&(j=this._indexById[o],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),p.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),p.indexMatch.length>1&&(c.time("findOptimalIndex"),p.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(p.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(q.push(e),r.push("$as"in b.$join[d][e]?b.$join[d][e].$as:e));for(g=0;g<r.length;g++)f=this._queryReferencesCollection(a,r[g],""),f&&(p.joinQueries[q[g]]=f,p.queriesJoin=!0);p.joinsOn=q,p.queriesOn=p.queriesOn.concat(q)}return p},n.prototype._queryReferencesCollection=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesCollection(a[d],b,c)}return!1},n.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},n.prototype.findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=this.find(a),k=j.length,l=this._db.collection("__FDB_temp_"+this.objectId()),m={parents:k,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(e=0;k>e;e++)if(f=i.value(j[e])[0]){if(l.setData(f),g=l.find(c,d),d.returnFirst&&g.length)return g[0];m.subDocs.push(g),m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.noStats?m.subDocs:(m.pathFound||(m.err="No objects found in the parent documents with a matching path of: "+b),m)},n.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},n.prototype.ensureIndex=function(a,b){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot operate in a dropped state!';this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:this._indexById[c.id()]?{err:"Index with those keys already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},n.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},n.prototype.lastOp=function(){return this._metrics.list()},n.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw'ForerunnerDB.Collection "'+this.name()+'": Collection diffing requires that both collections have the same primary key!';for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},n.prototype.collateAdd=new l({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e);break;case"update":e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f);break;case"remove":e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),n.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l({object:function(a){return this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=a.name;if(b){if(!this._collection[b]){if(a&&a.autoCreate===!1&&a&&a.throwError!==!1)throw'ForerunnerDB.Db "'+this.name()+'": Cannot get collection '+b+" because it does not exist and auto-create has been disabled!";this.debug()&&console.log("Creating collection "+b)}return this._collection[b]=this._collection[b]||new n(b).db(this),void 0!==a.primaryKey&&this._collection[b].primaryKey(a.primaryKey),this._collection[b]}if(!a||a&&a.throwError!==!1)throw'ForerunnerDB.Db "'+this.name()+'": Cannot get collection with undefined name!'}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(b in this._collection)this._collection.hasOwnProperty(b)&&(a?a.exec(b)&&c.push({name:b,count:this._collection[b].count()}):c.push({name:b,count:this._collection[b].count()}));return c.sort(function(a,b){return a.name.localeCompare(b.name)}),c},d.finishModule("Collection"),b.exports=n},{"./Crc":5,"./IndexBinaryTree":7,"./IndexHashMap":8,"./KeyValueStore":9,"./Metrics":10,"./Overload":21,"./Path":22,"./ReactorIO":24,"./Shared":25}],3:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw'ForerunnerDB.CollectionGroup "'+this.name()+'": All collections in a collection group must have the same primary key!'}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g)._subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(){if("dropped"!==this._state){var a,b,c;if(this._debug&&console.log("Dropping collection group "+this._name),this._state="dropped",this._collections&&this._collections.length)for(b=[].concat(this._collections),a=0;a<b.length;a++)this.removeCollection(b[a]);if(this._view&&this._view.length)for(c=[].concat(this._view),a=0;a<c.length;a++)this._removeView(c[a]);this.emit("drop",this)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){return a?(this._collectionGroup[a]=this._collectionGroup[a]||new h(a).db(this),this._collectionGroup[a]):this._collectionGroup;
},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":2,"./Shared":25}],4:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),g=a("./Overload");var h=function(a){this.init.apply(this,arguments)};h.prototype.init=function(){this._db={},this._debug={}},h.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),h.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},h.moduleLoaded=h.prototype.moduleLoaded,h.version=h.prototype.version,h.shared=d,h.prototype.shared=d,d.addModule("Core",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),h.prototype._isServer=!1,h.prototype.isClient=function(){return!this._isServer},h.prototype.isServer=function(){return this._isServer},h.prototype.isClient=function(){return!this._isServer},h.prototype.isServer=function(){return this._isServer},h.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=h},{"./Db.js":6,"./Metrics.js":10,"./Overload":21,"./Shared":25}],5:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],6:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a){this.init.apply(this,arguments)};j.prototype.init=function(a){this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d=d.concat("string"===e?c.peek(a):c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if("dropped"!==this._state){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"function":function(a){if("dropped"!==this._state){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean":function(a){if("dropped"!==this._state){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if("dropped"!==this._state){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a).core(this),this._db[a]},e.prototype.databases=function(a){var b,c=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(b in this._db)this._db.hasOwnProperty(b)&&(a?a.exec(b)&&c.push({name:b,collectionCount:this._db[b].collections().length}):c.push({name:b,collectionCount:this._db[b].collections().length}));return c.sort(function(a,b){return a.name.localeCompare(b.name)}),c},b.exports=j},{"./Collection.js":2,"./Crc.js":5,"./Metrics.js":10,"./Overload":21,"./Shared":25}],7:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){},g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new(f.create(2,this.sortAsc)),this._size=0,this._id=this._itemKeyHash(a,a),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree=new(f.create(2,this.sortAsc)),this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d,e=this._unique,f=this._itemKeyHash(a,this._keys);e&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._btree.get(f),void 0===d&&(d=[],this._btree.put(f,d)),d.push(a),this._size++},g.prototype.remove=function(a,b){var c,d,e,f=this._unique,g=this._itemKeyHash(a,this._keys);f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._btree.get(g),void 0!==d&&(e=d.indexOf(a),e>-1&&(1===d.length?this._btree.del(g):d.splice(e,1),this._size--))},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},g.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=g},{"./Path":22,"./Shared":25}],8:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":22,"./Shared":25}],9:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e,f=a[this._primaryKey];if(f instanceof Array){for(c=f.length,e=[],b=0;c>b;b++)d=this._data[f[b]],d&&e.push(d);return e}if(f instanceof RegExp){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.test(b)&&e.push(this._data[b]);return e}if("object"!=typeof f)return d=this._data[f],void 0!==d?[d]:[];if(f.$ne){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&b!==f.$ne&&e.push(this._data[b]);return e}if(f.$in&&f.$in instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.$in.indexOf(b)>-1&&e.push(this._data[b]);return e}if(f.$nin&&f.$nin instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&-1===f.$nin.indexOf(b)&&e.push(this._data[b]);return e}if(f.$or&&f.$or instanceof Array){for(e=[],b=0;b<f.$or.length;b++)e=e.concat(this.lookup(f.$or[b]));return e}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":25}],10:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":20,"./Shared":25}],11:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],12:[function(a,b,c){"use strict";var d={chain:function(a){this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e=this._chain,f=e.length;for(d=0;f>d;d++)e[d].chainReceive(this,a,b,c)}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],13:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload");d={store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}return void 0},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a){if(b){var c,d=JSON.stringify(a),e=[];for(c=0;b>c;c++)e.push(JSON.parse(d));return e}return JSON.parse(JSON.stringify(a))}return void 0},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}])},b.exports=d},{"./Overload":21}],14:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],15:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d;if(this._listeners[a]["*"]){var e=this._listeners[a]["*"];for(d=e.length,c=0;d>c;c++)e[c].apply(this,Array.prototype.slice.call(arguments,1))}if(b instanceof Array&&b[0]&&b[0][this._primaryKey]){var f,g,h=this._listeners[a];for(d=b.length,c=0;d>c;c++)if(h[b[c][this._primaryKey]])for(f=h[b[c][this._primaryKey]].length,g=0;f>g;g++)h[b[c][this._primaryKey]][g].apply(this,Array.prototype.slice.call(arguments,1))}}return this}};b.exports=e},{"./Overload":21}],16:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d){var e,f,g,h,i,j,k,l=typeof a,m=typeof b,n=!0;if(d=d||{},d.$rootQuery||(d.$rootQuery=b),"string"!==l&&"number"!==l||"string"!==m&&"number"!==m){for(k in b)if(b.hasOwnProperty(k)){if(e=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],d),i>-1)){if(i){if("or"===c)return!0}else n=i;e=!0}if(!e&&b[k]instanceof RegExp)if(e=!0,"object"==typeof a&&void 0!==a[k]&&b[k].test(a[k])){if("or"===c)return!0}else n=!1;if(!e)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],f,d)){if("or"===c)return!0}else n=!1;else if(g=this._match(void 0,b[k],f,d)){if("or"===c)return!0}else n=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],f,d)){if("or"===c)return!0}else n=!1;else n=!1;else if(a&&a[k]===b[k]){if("or"===c)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],f,d));h++);if(g){if("or"===c)return!0}else n=!1}else n=!1;if("and"===c&&!n)return!1}}else"number"===l?a!==b&&(n=!1):a.localeCompare(b)&&(n=!1);return n},_matchOp:function(a,b,c,d){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$ne":return b!=c;case"$or":for(var e=0;e<c.length;e++)if(this._match(b,c[e],"and",d))return!0;return!1;case"$and":for(var f=0;f<c.length;f++)if(!this._match(b,c[f],"and",d))return!1;return!0;case"$in":if(c instanceof Array){var g,h=c,i=h.length;for(g=0;i>g;g++)if(h[g]===b)return!0;return!1}throw'ForerunnerDB.Mixin.Matching "'+this.name()+'": Cannot use an $in operator on a non-array key: '+a;case"$nin":if(c instanceof Array){var j,k=c,l=k.length;for(j=0;l>j;j++)if(k[j]===b)return!1;return!0}throw'ForerunnerDB.Mixin.Matching "'+this.name()+'": Cannot use a $nin operator on a non-array key: '+a;case"$distinct":d.$rootQuery["//distinctLookup"]=d.$rootQuery["//distinctLookup"]||{};for(var m in c)if(c.hasOwnProperty(m))return d.$rootQuery["//distinctLookup"][m]=d.$rootQuery["//distinctLookup"][m]||{},d.$rootQuery["//distinctLookup"][m][b[m]]?!1:(d.$rootQuery["//distinctLookup"][m][b[m]]=!0,!0)}return-1}};b.exports=d},{}],17:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],18:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":21}],19:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log('ForerunnerDB.Mixin.Updating: Setting non-data-bound document property "'+b+'" for "'+this.name()+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log('ForerunnerDB.Mixin.Updating: Moving non-data-bound document array index from "'+b+'" to "'+c+'" for "'+this.name()+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c=!1;return a.length>0&&(1===b?(a.pop(),c=!0):-1===b&&(a.shift(),c=!0)),c}};b.exports=d},{}],20:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":22,"./Shared":25}],21:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length&&(e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),1!==arguments.length||"undefined"!==e);b++)f.push(e);if(d=f.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=f.length;b>=0;b--)if(d=f.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw'ForerunnerDB.Overload "'+this.name()+'": Overloaded method does not have a matching signature for the passed arguments: '+JSON.stringify(f)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],22:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else f.push(b?{path:g,value:a[d]}:{path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?this._parseArr(a[e],f,c,d):c.push(f));return c},e.prototype.value=function(a,b){if(void 0!==a&&"object"==typeof a){var c,d,e,f,g,h,i,j=[];for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,h=0;e>h;h++){if(f=f[d[h]],g instanceof Array){for(i=0;i<g.length;i++)j=j.concat(this.value(g,i+"."+d[h]));return j}if(!f||"object"!=typeof f)break;g=f}return[f]}return[]},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":25}],23:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("localforage");k=function(){this.init.apply(this,arguments)},k.prototype.init=function(a){a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),n.config({driver:[n.INDEXEDDB,n.WEBSQL,n.LOCALSTORAGE],name:"ForerunnerDB",storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,
k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":n.setDriver(n.LOCALSTORAGE);break;case"WEBSQL":n.setDriver(n.WEBSQL);break;case"INDEXEDDB":n.setDriver(n.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return n.driver()},k.prototype.save=function(a,b,c){var d;switch(d=function(a,b){a="object"==typeof a?"json::fdb::"+JSON.stringify(a):"raw::fdb::"+a,b&&b(!1,a)},this.mode()){case"localforage":d(b,function(b,d){n.setItem(a,d).then(function(a){c&&c(!1,a)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c,d,e;switch(e=function(a,b){if(a){switch(c=a.split("::fdb::"),c[0]){case"json":d=JSON.parse(c[1]);break;case"raw":d=c[1]}b&&b(!1,d)}else b&&b(!1,a)},this.mode()){case"localforage":n.getItem(a).then(function(a){e(a,b)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":n.removeItem(a).then(function(){b&&b(!1)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){"dropped"!==this._state&&this.drop(!0)},"function":function(a){"dropped"!==this._state&&this.drop(!0,a)},"boolean":function(a){if("dropped"!==this._state){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";if(!this._db)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when the collection is not attached to a database!";this._db.persist.drop(this._name)}f.apply(this)}},"boolean, function":function(a,b){"dropped"!==this._state&&(a&&(this._name?this._db?this._db.persist.drop(this._name,b):b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!"):b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")),f.apply(this,b))}}),e.prototype.save=function(a){this._name?this._db?this._db.persist.save(this._name,this._data,a):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;this._name?this._db?this._db.persist.load(this._name,function(c,d){c?a&&a(c):(d&&b.setData(d),a&&a(!1))}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},d.prototype.init=function(){this.persist=new k(this),i.apply(this,arguments)},d.prototype.load=function(a){var b,c,d=this._collection,e=d.keys(),f=e.length;b=function(b){b?a&&a(b):(f--,0===f&&a&&a(!1))};for(c in d)d.hasOwnProperty(c)&&d[c].load(b)},d.prototype.save=function(a){var b,c,d=this._collection,e=d.keys(),f=e.length;b=function(b){b?a&&a(b):(f--,0===f&&a&&a(!1))};for(c in d)d.hasOwnProperty(c)&&d[c].save(b)},m.finishModule("Persist"),b.exports=k},{"./Collection":2,"./CollectionGroup":3,"./Shared":25,localforage:33}],24:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain||!b.chainReceive)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return"dropped"!==this._state&&(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this)),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":25}],25:[function(a,b,c){"use strict";var d={version:"1.3.40",modules:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:function(a,b){var c=this.mixins[b];if(!c)throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])},synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:a("./Overload"),mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating")}};d.mixin(d,"Mixin.Events"),b.exports=d},{"./Mixin.CRUD":11,"./Mixin.ChainReactor":12,"./Mixin.Common":13,"./Mixin.Constants":14,"./Mixin.Events":15,"./Mixin.Matching":16,"./Mixin.Sorting":17,"./Mixin.Triggers":18,"./Mixin.Updating":19,"./Overload":21}],26:[function(a,b,c){function d(){if(!h){h=!0;for(var a,b=g.length;b;){a=g,g=[];for(var c=-1;++c<b;)a[c]();b=g.length}h=!1}}function e(){}var f=b.exports={},g=[],h=!1;f.nextTick=function(a){g.push(a),h||setTimeout(d,0)},f.title="browser",f.browser=!0,f.env={},f.argv=[],f.version="",f.versions={},f.on=e,f.addListener=e,f.once=e,f.off=e,f.removeListener=e,f.removeAllListeners=e,f.emit=e,f.binding=function(a){throw new Error("process.binding is not supported")},f.cwd=function(){return"/"},f.chdir=function(a){throw new Error("process.chdir is not supported")},f.umask=function(){return 0}},{}],27:[function(a,b,c){"use strict";function d(a){function b(a){return null===j?void l.push(a):void g(function(){var b=j?a.onFulfilled:a.onRejected;if(null===b)return void(j?a.resolve:a.reject)(k);var c;try{c=b(k)}catch(d){return void a.reject(d)}a.resolve(c)})}function c(a){try{if(a===m)throw new TypeError("A promise cannot be resolved with itself.");if(a&&("object"==typeof a||"function"==typeof a)){var b=a.then;if("function"==typeof b)return void f(b.bind(a),c,h)}j=!0,k=a,i()}catch(d){h(d)}}function h(a){j=!1,k=a,i()}function i(){for(var a=0,c=l.length;c>a;a++)b(l[a]);l=null}if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof a)throw new TypeError("not a function");var j=null,k=null,l=[],m=this;this.then=function(a,c){return new d(function(d,f){b(new e(a,c,d,f))})},f(a,c,h)}function e(a,b,c,d){this.onFulfilled="function"==typeof a?a:null,this.onRejected="function"==typeof b?b:null,this.resolve=c,this.reject=d}function f(a,b,c){var d=!1;try{a(function(a){d||(d=!0,b(a))},function(a){d||(d=!0,c(a))})}catch(e){if(d)return;d=!0,c(e)}}var g=a("asap");b.exports=d},{asap:29}],28:[function(a,b,c){"use strict";function d(a){this.then=function(b){return"function"!=typeof b?this:new e(function(c,d){f(function(){try{c(b(a))}catch(e){d(e)}})})}}var e=a("./core.js"),f=a("asap");b.exports=e,d.prototype=Object.create(e.prototype);var g=new d(!0),h=new d(!1),i=new d(null),j=new d(void 0),k=new d(0),l=new d("");e.resolve=function(a){if(a instanceof e)return a;if(null===a)return i;if(void 0===a)return j;if(a===!0)return g;if(a===!1)return h;if(0===a)return k;if(""===a)return l;if("object"==typeof a||"function"==typeof a)try{var b=a.then;if("function"==typeof b)return new e(b.bind(a))}catch(c){return new e(function(a,b){b(c)})}return new d(a)},e.from=e.cast=function(a){var b=new Error("Promise.from and Promise.cast are deprecated, use Promise.resolve instead");return b.name="Warning",console.warn(b.stack),e.resolve(a)},e.denodeify=function(a,b){return b=b||1/0,function(){var c=this,d=Array.prototype.slice.call(arguments);return new e(function(e,f){for(;d.length&&d.length>b;)d.pop();d.push(function(a,b){a?f(a):e(b)}),a.apply(c,d)})}},e.nodeify=function(a){return function(){var b=Array.prototype.slice.call(arguments),c="function"==typeof b[b.length-1]?b.pop():null;try{return a.apply(this,arguments).nodeify(c)}catch(d){if(null===c||"undefined"==typeof c)return new e(function(a,b){b(d)});f(function(){c(d)})}}},e.all=function(){var a=1===arguments.length&&Array.isArray(arguments[0]),b=Array.prototype.slice.call(a?arguments[0]:arguments);if(!a){var c=new Error("Promise.all should be called with a single array, calling it with multiple arguments is deprecated");c.name="Warning",console.warn(c.stack)}return new e(function(a,c){function d(f,g){try{if(g&&("object"==typeof g||"function"==typeof g)){var h=g.then;if("function"==typeof h)return void h.call(g,function(a){d(f,a)},c)}b[f]=g,0===--e&&a(b)}catch(i){c(i)}}if(0===b.length)return a([]);for(var e=b.length,f=0;f<b.length;f++)d(f,b[f])})},e.reject=function(a){return new e(function(b,c){c(a)})},e.race=function(a){return new e(function(b,c){a.forEach(function(a){e.resolve(a).then(b,c)})})},e.prototype.done=function(a,b){var c=arguments.length?this.then.apply(this,arguments):this;c.then(null,function(a){f(function(){throw a})})},e.prototype.nodeify=function(a){return"function"!=typeof a?this:void this.then(function(b){f(function(){a(null,b)})},function(b){f(function(){a(b)})})},e.prototype["catch"]=function(a){return this.then(null,a)}},{"./core.js":27,asap:29}],29:[function(a,b,c){(function(a){function c(){for(;e.next;){e=e.next;var a=e.task;e.task=void 0;var b=e.domain;b&&(e.domain=void 0,b.enter());try{a()}catch(d){if(i)throw b&&b.exit(),setTimeout(c,0),b&&b.enter(),d;setTimeout(function(){throw d},0)}b&&b.exit()}g=!1}function d(b){f=f.next={task:b,domain:i&&a.domain,next:null},g||(g=!0,h())}var e={task:void 0,next:null},f=e,g=!1,h=void 0,i=!1;if("undefined"!=typeof a&&a.nextTick)i=!0,h=function(){a.nextTick(c)};else if("function"==typeof setImmediate)h="undefined"!=typeof window?setImmediate.bind(window,c):function(){setImmediate(c)};else if("undefined"!=typeof MessageChannel){var j=new MessageChannel;j.port1.onmessage=c,h=function(){j.port2.postMessage(0)}}else h=function(){setTimeout(c,0)};b.exports=d}).call(this,a("_process"))},{_process:26}],30:[function(a,b,c){(function(){"use strict";function c(a){var b=this,c={db:null};if(a)for(var d in a)c[d]=a[d];return new o(function(a,d){var e=p.open(c.name,c.version);e.onerror=function(){d(e.error)},e.onupgradeneeded=function(){e.result.createObjectStore(c.storeName)},e.onsuccess=function(){c.db=e.result,b._dbInfo=c,a()}})}function d(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new o(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return m(d,b),d}function e(a,b){var c=this,d=new o(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),h=1;g.onsuccess=function(){var c=g.result;if(c){var d=a(c.value,c.key,h++);void 0!==d?b(d):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return m(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new o(function(c,e){d.ready().then(function(){var f=d._dbInfo,g=f.db.transaction(f.storeName,"readwrite"),h=g.objectStore(f.storeName);null===b&&(b=void 0);var i=h.put(b,a);g.oncomplete=function(){void 0===b&&(b=null),c(b)},g.onabort=g.onerror=function(){e(i.error)}})["catch"](e)});return m(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new o(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(a){var b=a.target.error;"QuotaExceededError"===b&&d(b)}})["catch"](d)});return m(d,b),d}function h(a){var b=this,c=new o(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){c(g.error)}})["catch"](c)});return m(c,a),c}function i(a){var b=this,c=new o(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new o(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new o(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}function m(a,b){b&&a.then(function(a){n(b,a)},function(a){b(a)})}function n(a,b){return a?setTimeout(function(){return a(null,b)},0):void 0}var o="undefined"!=typeof b&&b.exports?a("promise"):this.Promise,p=p||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(p){var q={_driver:"asyncStorage",_initStorage:c,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};"undefined"!=typeof b&&b.exports?b.exports=q:"function"==typeof define&&define.amd?define("asyncStorage",function(){return q}):this.asyncStorage=q}}).call(window)},{promise:28}],31:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={};if(b)for(var e in b)d[e]=b[e];d.keyPrefix=d.name+"/",c._dbInfo=d;var f=new m(function(b){s===r.DEFINE?a(["localforageSerializer"],b):b(s===r.EXPORT?a("./../utils/serializer"):n.localforageSerializer)});return f.then(function(a){return o=a,m.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=p.length-1;c>=0;c--){var d=p.key(c);0===d.indexOf(a)&&p.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=p.getItem(b.keyPrefix+a);return d&&(d=o.deserialize(d)),d});return l(d,b),d}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo.keyPrefix,d=b.length,e=p.length,f=0;e>f;f++){var g=p.key(f),h=p.getItem(g);if(h&&(h=o.deserialize(h)),h=a(h,g.substring(d),f+1),void 0!==h)return h}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=p.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=p.length,d=[],e=0;c>e;e++)0===p.key(e).indexOf(a.keyPrefix)&&d.push(p.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;p.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new m(function(e,f){o.serialize(b,function(b,g){if(g)f(g);else try{var h=d._dbInfo;p.setItem(h.keyPrefix+a,b),e(c)}catch(i){("QuotaExceededError"===i.name||"NS_ERROR_DOM_QUOTA_REACHED"===i.name)&&f(i),f(i)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports?a("promise"):this.Promise,n=this,o=null,p=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;p=this.localStorage}catch(q){return}var r={DEFINE:1,EXPORT:2,WINDOW:3},s=r.WINDOW;"undefined"!=typeof b&&b.exports?s=r.EXPORT:"function"==typeof define&&define.amd&&(s=r.DEFINE);var t={_driver:"localStorageWrapper",_initStorage:c,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};s===r.EXPORT?b.exports=t:s===r.DEFINE?define("localStorageWrapper",function(){return t}):this.localStorageWrapper=t}).call(window)},{"./../utils/serializer":34,promise:28}],32:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={db:null};if(b)for(var e in b)d[e]="string"!=typeof b[e]?b[e].toString():b[e];var f=new m(function(b){r===q.DEFINE?a(["localforageSerializer"],b):b(r===q.EXPORT?a("./../utils/serializer"):n.localforageSerializer)}),g=new m(function(a,e){try{d.db=p(d.name,String(d.version),d.description,d.size)}catch(f){return c.setDriver(c.LOCALSTORAGE).then(function(){return c._initStorage(b)}).then(a)["catch"](e)}d.db.transaction(function(b){b.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){c._dbInfo=d,a()},function(a,b){e(b)})})});return f.then(function(a){return o=a,g})}function d(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=o.deserialize(d)),b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function e(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var e=d.rows,f=e.length,g=0;f>g;g++){var h=e.item(g),i=h.value;if(i&&(i=o.deserialize(i)),i=a(i,h.key,g+1),void 0!==i)return void b(i)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new m(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b;o.serialize(b,function(b,g){if(g)e(g);else{var h=d._dbInfo;h.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+h.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})}})})["catch"](e)});return l(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function h(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports?a("promise"):this.Promise,n=this,o=null,p=this.openDatabase;if(p){var q={DEFINE:1,EXPORT:2,WINDOW:3},r=q.WINDOW;"undefined"!=typeof b&&b.exports?r=q.EXPORT:"function"==typeof define&&define.amd&&(r=q.DEFINE);var s={_driver:"webSQLStorage",_initStorage:c,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};r===q.DEFINE?define("webSQLStorage",function(){return s}):r===q.EXPORT?b.exports=s:this.webSQLStorage=s}}).call(window)},{"./../utils/serializer":34,promise:28}],33:[function(a,b,c){(function(){"use strict";function c(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function d(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(p(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function e(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b]===a)return!0;return!1}function f(a){this._config=d({},m,a),this._driverSet=null,this._ready=!1,this._dbInfo=null;for(var b=0;b<k.length;b++)c(this,k[b]);this.setDriver(this._config.driver)}var g="undefined"!=typeof b&&b.exports?a("promise"):this.Promise,h={},i={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},j=[i.INDEXEDDB,i.WEBSQL,i.LOCALSTORAGE],k=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],l={DEFINE:1,EXPORT:2,WINDOW:3},m={description:"",driver:j.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},n=l.WINDOW;"undefined"!=typeof b&&b.exports?n=l.EXPORT:"function"==typeof define&&define.amd&&(n=l.DEFINE);var o=function(a){var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,c={};return c[i.WEBSQL]=!!a.openDatabase,c[i.INDEXEDDB]=!!function(){if("undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent))return!1;try{return b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(c){return!1}}(),c[i.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),c}(this),p=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},q=this;f.prototype.INDEXEDDB=i.INDEXEDDB,f.prototype.LOCALSTORAGE=i.LOCALSTORAGE,f.prototype.WEBSQL=i.WEBSQL,f.prototype.config=function(a){if("object"==typeof a){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},f.prototype.defineDriver=function(a,b,c){var d=new g(function(b,c){try{var d=a._driver,f=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),i=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(f);if(e(a._driver))return void c(i);for(var j=k.concat("_initStorage"),l=0;l<j.length;l++){var m=j[l];if(!m||!a[m]||"function"!=typeof a[m])return void c(f)}var n=g.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():g.resolve(!!a._support)),n.then(function(c){o[d]=c,h[d]=a,b()},c)}catch(p){c(p)}});return d.then(b,c),d},f.prototype.driver=function(){return this._driver||null},f.prototype.ready=function(a){var b=this,c=new g(function(a,c){b._driverSet.then(function(){null===b._ready&&(b._ready=b._initStorage(b._config)),b._ready.then(a,c)})["catch"](c)});return c.then(a,a),c},f.prototype.setDriver=function(b,c,d){function f(){i._config.driver=i.driver()}var i=this;return"string"==typeof b&&(b=[b]),this._driverSet=new g(function(c,d){var f=i._getFirstSupportedDriver(b),j=new Error("No available storage method found.");if(!f)return i._driverSet=g.reject(j),void d(j);if(i._dbInfo=null,i._ready=null,e(f)){if(n===l.DEFINE)return void a([f],function(a){i._extend(a),c()});if(n===l.EXPORT){var k;switch(f){case i.INDEXEDDB:k=a("./drivers/indexeddb");break;case i.LOCALSTORAGE:k=a("./drivers/localstorage");break;case i.WEBSQL:k=a("./drivers/websql")}i._extend(k)}else i._extend(q[f])}else{if(!h[f])return i._driverSet=g.reject(j),void d(j);i._extend(h[f])}c()}),this._driverSet.then(f,f),this._driverSet.then(c,d),this._driverSet},f.prototype.supports=function(a){return!!o[a]},f.prototype._extend=function(a){d(this,a)},f.prototype._getFirstSupportedDriver=function(a){if(a&&p(a))for(var b=0;b<a.length;b++){var c=a[b];if(this.supports(c))return c}return null},f.prototype.createInstance=function(a){return new f(a)};var r=new f;n===l.DEFINE?define("localforage",function(){return r}):n===l.EXPORT?b.exports=r:this.localforage=r}).call(window)},{"./drivers/indexeddb":30,"./drivers/localstorage":31,"./drivers/websql":32,promise:28}],34:[function(a,b,c){(function(){"use strict";function a(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,f=g;a instanceof ArrayBuffer?(d=a,f+=i):(d=a.buffer,"[object Int8Array]"===c?f+=k:"[object Uint8Array]"===c?f+=l:"[object Uint8ClampedArray]"===c?f+=m:"[object Int16Array]"===c?f+=n:"[object Uint16Array]"===c?f+=p:"[object Int32Array]"===c?f+=o:"[object Uint32Array]"===c?f+=q:"[object Float32Array]"===c?f+=r:"[object Float64Array]"===c?f+=s:b(new Error("Failed to get type for BinaryArray"))),b(f+e(d))}else if("[object Blob]"===c){var h=new FileReader;h.onload=function(){var a=e(this.result);b(g+j+a)},h.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(t){window.console.error("Couldn't convert value into a JSON string: ",a),b(null,t)}}function c(a){if(a.substring(0,h)!==g)return JSON.parse(a);var b=a.substring(t),c=a.substring(h,t),e=d(b);switch(c){case i:return e;case j:return new Blob([e]);case k:return new Int8Array(e);case l:return new Uint8Array(e);case m:return new Uint8ClampedArray(e);case n:return new Int16Array(e);case p:return new Uint16Array(e);case o:return new Int32Array(e);case q:return new Uint32Array(e);case r:return new Float32Array(e);case s:return new Float64Array(e);default:throw new Error("Unkown type: "+c)}}function d(a){var b,c,d,e,g,h=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(h--,"="===a[a.length-2]&&h--);var k=new ArrayBuffer(h),l=new Uint8Array(k);for(b=0;i>b;b+=4)c=f.indexOf(a[b]),d=f.indexOf(a[b+1]),e=f.indexOf(a[b+2]),g=f.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&g;return k}function e(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=f[c[b]>>2],d+=f[(3&c[b])<<4|c[b+1]>>4],d+=f[(15&c[b+1])<<2|c[b+2]>>6],d+=f[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",g="__lfsc__:",h=g.length,i="arbf",j="blob",k="si08",l="ui08",m="uic8",n="si16",o="si32",p="ur16",q="ui32",r="fl32",s="fl64",t=h+i.length,u={serialize:a,deserialize:c,stringToBuffer:d,bufferToString:e};"undefined"!=typeof b&&b.exports?b.exports=u:"function"==typeof define&&define.amd?define("localforageSerializer",function(){return u}):this.localforageSerializer=u}).call(window)},{}]},{},[1]); |
tests/components/Dropdown.spec.js | dingchaoyan1983/ReactRedux | import React from 'react'
import Dropdown from 'components/Dropdown/Dropdown'
describe('(Component) Dropdown', () => {
it('should exist', () => {
})
})
|
ajax/libs/react/0.11.2/react-with-addons.js | viskin/cdnjs | /**
* React (with addons) v0.11.2
*/
!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.React=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule AutoFocusMixin
* @typechecks static-only
*/
"use strict";
var focusNode = _dereq_("./focusNode");
var AutoFocusMixin = {
componentDidMount: function() {
if (this.props.autoFocus) {
focusNode(this.getDOMNode());
}
}
};
module.exports = AutoFocusMixin;
},{"./focusNode":120}],2:[function(_dereq_,module,exports){
/**
* Copyright 2013 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 BeforeInputEventPlugin
* @typechecks static-only
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPropagators = _dereq_("./EventPropagators");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var SyntheticInputEvent = _dereq_("./SyntheticInputEvent");
var keyOf = _dereq_("./keyOf");
var canUseTextInputEvent = (
ExecutionEnvironment.canUseDOM &&
'TextEvent' in window &&
!('documentMode' in document || isPresto())
);
/**
* Opera <= 12 includes TextEvent in window, but does not fire
* text input events. Rely on keypress instead.
*/
function isPresto() {
var opera = window.opera;
return (
typeof opera === 'object' &&
typeof opera.version === 'function' &&
parseInt(opera.version(), 10) <= 12
);
}
var SPACEBAR_CODE = 32;
var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
var topLevelTypes = EventConstants.topLevelTypes;
// Events and their corresponding property names.
var eventTypes = {
beforeInput: {
phasedRegistrationNames: {
bubbled: keyOf({onBeforeInput: null}),
captured: keyOf({onBeforeInputCapture: null})
},
dependencies: [
topLevelTypes.topCompositionEnd,
topLevelTypes.topKeyPress,
topLevelTypes.topTextInput,
topLevelTypes.topPaste
]
}
};
// Track characters inserted via keypress and composition events.
var fallbackChars = null;
/**
* Return whether a native keypress event is assumed to be a command.
* This is required because Firefox fires `keypress` events for key commands
* (cut, copy, select-all, etc.) even though no character is inserted.
*/
function isKeypressCommand(nativeEvent) {
return (
(nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) &&
// ctrlKey && altKey is equivalent to AltGr, and is not a command.
!(nativeEvent.ctrlKey && nativeEvent.altKey)
);
}
/**
* Create an `onBeforeInput` event to match
* http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
*
* This event plugin is based on the native `textInput` event
* available in Chrome, Safari, Opera, and IE. This event fires after
* `onKeyPress` and `onCompositionEnd`, but before `onInput`.
*
* `beforeInput` is spec'd but not implemented in any browsers, and
* the `input` event does not provide any useful information about what has
* actually been added, contrary to the spec. Thus, `textInput` is the best
* available event to identify the characters that have actually been inserted
* into the target node.
*/
var BeforeInputEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var chars;
if (canUseTextInputEvent) {
switch (topLevelType) {
case topLevelTypes.topKeyPress:
/**
* If native `textInput` events are available, our goal is to make
* use of them. However, there is a special case: the spacebar key.
* In Webkit, preventing default on a spacebar `textInput` event
* cancels character insertion, but it *also* causes the browser
* to fall back to its default spacebar behavior of scrolling the
* page.
*
* Tracking at:
* https://code.google.com/p/chromium/issues/detail?id=355103
*
* To avoid this issue, use the keypress event as if no `textInput`
* event is available.
*/
var which = nativeEvent.which;
if (which !== SPACEBAR_CODE) {
return;
}
chars = String.fromCharCode(which);
break;
case topLevelTypes.topTextInput:
// Record the characters to be added to the DOM.
chars = nativeEvent.data;
// If it's a spacebar character, assume that we have already handled
// it at the keypress level and bail immediately.
if (chars === SPACEBAR_CHAR) {
return;
}
// Otherwise, carry on.
break;
default:
// For other native event types, do nothing.
return;
}
} else {
switch (topLevelType) {
case topLevelTypes.topPaste:
// If a paste event occurs after a keypress, throw out the input
// chars. Paste events should not lead to BeforeInput events.
fallbackChars = null;
break;
case topLevelTypes.topKeyPress:
/**
* As of v27, Firefox may fire keypress events even when no character
* will be inserted. A few possibilities:
*
* - `which` is `0`. Arrow keys, Esc key, etc.
*
* - `which` is the pressed key code, but no char is available.
* Ex: 'AltGr + d` in Polish. There is no modified character for
* this key combination and no character is inserted into the
* document, but FF fires the keypress for char code `100` anyway.
* No `input` event will occur.
*
* - `which` is the pressed key code, but a command combination is
* being used. Ex: `Cmd+C`. No character is inserted, and no
* `input` event will occur.
*/
if (nativeEvent.which && !isKeypressCommand(nativeEvent)) {
fallbackChars = String.fromCharCode(nativeEvent.which);
}
break;
case topLevelTypes.topCompositionEnd:
fallbackChars = nativeEvent.data;
break;
}
// If no changes have occurred to the fallback string, no relevant
// event has fired and we're done.
if (fallbackChars === null) {
return;
}
chars = fallbackChars;
}
// If no characters are being inserted, no BeforeInput event should
// be fired.
if (!chars) {
return;
}
var event = SyntheticInputEvent.getPooled(
eventTypes.beforeInput,
topLevelTargetID,
nativeEvent
);
event.data = chars;
fallbackChars = null;
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
};
module.exports = BeforeInputEventPlugin;
},{"./EventConstants":16,"./EventPropagators":21,"./ExecutionEnvironment":22,"./SyntheticInputEvent":98,"./keyOf":141}],3:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule CSSCore
* @typechecks
*/
var invariant = _dereq_("./invariant");
/**
* The CSSCore module specifies the API (and implements most of the methods)
* that should be used when dealing with the display of elements (via their
* CSS classes and visibility on screen. It is an API focused on mutating the
* display and not reading it as no logical state should be encoded in the
* display of elements.
*/
var CSSCore = {
/**
* Adds the class passed in to the element if it doesn't already have it.
*
* @param {DOMElement} element the element to set the class on
* @param {string} className the CSS className
* @return {DOMElement} the element passed in
*/
addClass: function(element, className) {
("production" !== "development" ? invariant(
!/\s/.test(className),
'CSSCore.addClass takes only a single class name. "%s" contains ' +
'multiple classes.', className
) : invariant(!/\s/.test(className)));
if (className) {
if (element.classList) {
element.classList.add(className);
} else if (!CSSCore.hasClass(element, className)) {
element.className = element.className + ' ' + className;
}
}
return element;
},
/**
* Removes the class passed in from the element
*
* @param {DOMElement} element the element to set the class on
* @param {string} className the CSS className
* @return {DOMElement} the element passed in
*/
removeClass: function(element, className) {
("production" !== "development" ? invariant(
!/\s/.test(className),
'CSSCore.removeClass takes only a single class name. "%s" contains ' +
'multiple classes.', className
) : invariant(!/\s/.test(className)));
if (className) {
if (element.classList) {
element.classList.remove(className);
} else if (CSSCore.hasClass(element, className)) {
element.className = element.className
.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1')
.replace(/\s+/g, ' ') // multiple spaces to one
.replace(/^\s*|\s*$/g, ''); // trim the ends
}
}
return element;
},
/**
* Helper to add or remove a class from an element based on a condition.
*
* @param {DOMElement} element the element to set the class on
* @param {string} className the CSS className
* @param {*} bool condition to whether to add or remove the class
* @return {DOMElement} the element passed in
*/
conditionClass: function(element, className, bool) {
return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className);
},
/**
* Tests whether the element has the class specified.
*
* @param {DOMNode|DOMWindow} element the element to set the class on
* @param {string} className the CSS className
* @returns {boolean} true if the element has the class, false if not
*/
hasClass: function(element, className) {
("production" !== "development" ? invariant(
!/\s/.test(className),
'CSS.hasClass takes only a single class name.'
) : invariant(!/\s/.test(className)));
if (element.classList) {
return !!className && element.classList.contains(className);
}
return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1;
}
};
module.exports = CSSCore;
},{"./invariant":134}],4:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule CSSProperty
*/
"use strict";
/**
* CSS properties which accept numbers but are not in units of "px".
*/
var isUnitlessNumber = {
columnCount: true,
fillOpacity: true,
flex: true,
flexGrow: true,
flexShrink: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
widows: true,
zIndex: true,
zoom: true
};
/**
* @param {string} prefix vendor-specific prefix, eg: Webkit
* @param {string} key style name, eg: transitionDuration
* @return {string} style name prefixed with `prefix`, properly camelCased, eg:
* WebkitTransitionDuration
*/
function prefixKey(prefix, key) {
return prefix + key.charAt(0).toUpperCase() + key.substring(1);
}
/**
* Support style names that may come passed in prefixed by adding permutations
* of vendor prefixes.
*/
var prefixes = ['Webkit', 'ms', 'Moz', 'O'];
// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.
Object.keys(isUnitlessNumber).forEach(function(prop) {
prefixes.forEach(function(prefix) {
isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
});
});
/**
* Most style properties can be unset by doing .style[prop] = '' but IE8
* doesn't like doing that with shorthand properties so for the properties that
* IE8 breaks on, which are listed here, we instead unset each of the
* individual properties. See http://bugs.jquery.com/ticket/12385.
* The 4-value 'clock' properties like margin, padding, border-width seem to
* behave without any problems. Curiously, list-style works too without any
* special prodding.
*/
var shorthandPropertyExpansions = {
background: {
backgroundImage: true,
backgroundPosition: true,
backgroundRepeat: true,
backgroundColor: true
},
border: {
borderWidth: true,
borderStyle: true,
borderColor: true
},
borderBottom: {
borderBottomWidth: true,
borderBottomStyle: true,
borderBottomColor: true
},
borderLeft: {
borderLeftWidth: true,
borderLeftStyle: true,
borderLeftColor: true
},
borderRight: {
borderRightWidth: true,
borderRightStyle: true,
borderRightColor: true
},
borderTop: {
borderTopWidth: true,
borderTopStyle: true,
borderTopColor: true
},
font: {
fontStyle: true,
fontVariant: true,
fontWeight: true,
fontSize: true,
lineHeight: true,
fontFamily: true
}
};
var CSSProperty = {
isUnitlessNumber: isUnitlessNumber,
shorthandPropertyExpansions: shorthandPropertyExpansions
};
module.exports = CSSProperty;
},{}],5:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule CSSPropertyOperations
* @typechecks static-only
*/
"use strict";
var CSSProperty = _dereq_("./CSSProperty");
var dangerousStyleValue = _dereq_("./dangerousStyleValue");
var hyphenateStyleName = _dereq_("./hyphenateStyleName");
var memoizeStringOnly = _dereq_("./memoizeStringOnly");
var processStyleName = memoizeStringOnly(function(styleName) {
return hyphenateStyleName(styleName);
});
/**
* Operations for dealing with CSS properties.
*/
var CSSPropertyOperations = {
/**
* Serializes a mapping of style properties for use as inline styles:
*
* > createMarkupForStyles({width: '200px', height: 0})
* "width:200px;height:0;"
*
* Undefined values are ignored so that declarative programming is easier.
* The result should be HTML-escaped before insertion into the DOM.
*
* @param {object} styles
* @return {?string}
*/
createMarkupForStyles: function(styles) {
var serialized = '';
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var styleValue = styles[styleName];
if (styleValue != null) {
serialized += processStyleName(styleName) + ':';
serialized += dangerousStyleValue(styleName, styleValue) + ';';
}
}
return serialized || null;
},
/**
* Sets the value for multiple styles on a node. If a value is specified as
* '' (empty string), the corresponding style property will be unset.
*
* @param {DOMElement} node
* @param {object} styles
*/
setValueForStyles: function(node, styles) {
var style = node.style;
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var styleValue = dangerousStyleValue(styleName, styles[styleName]);
if (styleValue) {
style[styleName] = styleValue;
} else {
var expansion = CSSProperty.shorthandPropertyExpansions[styleName];
if (expansion) {
// Shorthand property that IE8 won't like unsetting, so unset each
// component to placate it
for (var individualStyleName in expansion) {
style[individualStyleName] = '';
}
} else {
style[styleName] = '';
}
}
}
}
};
module.exports = CSSPropertyOperations;
},{"./CSSProperty":4,"./dangerousStyleValue":115,"./hyphenateStyleName":132,"./memoizeStringOnly":143}],6:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule 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" !== "development" ? 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":28,"./invariant":134,"./mixInto":147}],7:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ChangeEventPlugin
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPluginHub = _dereq_("./EventPluginHub");
var EventPropagators = _dereq_("./EventPropagators");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var ReactUpdates = _dereq_("./ReactUpdates");
var SyntheticEvent = _dereq_("./SyntheticEvent");
var isEventSupported = _dereq_("./isEventSupported");
var isTextInputElement = _dereq_("./isTextInputElement");
var keyOf = _dereq_("./keyOf");
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
change: {
phasedRegistrationNames: {
bubbled: keyOf({onChange: null}),
captured: keyOf({onChangeCapture: null})
},
dependencies: [
topLevelTypes.topBlur,
topLevelTypes.topChange,
topLevelTypes.topClick,
topLevelTypes.topFocus,
topLevelTypes.topInput,
topLevelTypes.topKeyDown,
topLevelTypes.topKeyUp,
topLevelTypes.topSelectionChange
]
}
};
/**
* For IE shims
*/
var activeElement = null;
var activeElementID = null;
var activeElementValue = null;
var activeElementValueProp = null;
/**
* SECTION: handle `change` event
*/
function shouldUseChangeEvent(elem) {
return (
elem.nodeName === 'SELECT' ||
(elem.nodeName === 'INPUT' && elem.type === 'file')
);
}
var doesChangeEventBubble = false;
if (ExecutionEnvironment.canUseDOM) {
// See `handleChange` comment below
doesChangeEventBubble = isEventSupported('change') && (
!('documentMode' in document) || document.documentMode > 8
);
}
function manualDispatchChangeEvent(nativeEvent) {
var event = SyntheticEvent.getPooled(
eventTypes.change,
activeElementID,
nativeEvent
);
EventPropagators.accumulateTwoPhaseDispatches(event);
// If change and propertychange bubbled, we'd just bind to it like all the
// other events and have it go through ReactBrowserEventEmitter. Since it
// doesn't, we manually listen for the events and so we have to enqueue and
// process the abstract event manually.
//
// Batching is necessary here in order to ensure that all event handlers run
// before the next rerender (including event handlers attached to ancestor
// elements instead of directly on the input). Without this, controlled
// components don't work properly in conjunction with event bubbling because
// the component is rerendered and the value reverted before all the event
// handlers can run. See https://github.com/facebook/react/issues/708.
ReactUpdates.batchedUpdates(runEventInBatch, event);
}
function runEventInBatch(event) {
EventPluginHub.enqueueEvents(event);
EventPluginHub.processEventQueue();
}
function startWatchingForChangeEventIE8(target, targetID) {
activeElement = target;
activeElementID = targetID;
activeElement.attachEvent('onchange', manualDispatchChangeEvent);
}
function stopWatchingForChangeEventIE8() {
if (!activeElement) {
return;
}
activeElement.detachEvent('onchange', manualDispatchChangeEvent);
activeElement = null;
activeElementID = null;
}
function getTargetIDForChangeEvent(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topChange) {
return topLevelTargetID;
}
}
function handleEventsForChangeEventIE8(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topFocus) {
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForChangeEventIE8();
startWatchingForChangeEventIE8(topLevelTarget, topLevelTargetID);
} else if (topLevelType === topLevelTypes.topBlur) {
stopWatchingForChangeEventIE8();
}
}
/**
* SECTION: handle `input` event
*/
var isInputEventSupported = false;
if (ExecutionEnvironment.canUseDOM) {
// IE9 claims to support the input event but fails to trigger it when
// deleting text, so we ignore its input events
isInputEventSupported = isEventSupported('input') && (
!('documentMode' in document) || document.documentMode > 9
);
}
/**
* (For old IE.) Replacement getter/setter for the `value` property that gets
* set on the active element.
*/
var newValueProp = {
get: function() {
return activeElementValueProp.get.call(this);
},
set: function(val) {
// Cast to a string so we can do equality checks.
activeElementValue = '' + val;
activeElementValueProp.set.call(this, val);
}
};
/**
* (For old IE.) Starts tracking propertychange events on the passed-in element
* and override the value property so that we can distinguish user events from
* value changes in JS.
*/
function startWatchingForValueChange(target, targetID) {
activeElement = target;
activeElementID = targetID;
activeElementValue = target.value;
activeElementValueProp = Object.getOwnPropertyDescriptor(
target.constructor.prototype,
'value'
);
Object.defineProperty(activeElement, 'value', newValueProp);
activeElement.attachEvent('onpropertychange', handlePropertyChange);
}
/**
* (For old IE.) Removes the event listeners from the currently-tracked element,
* if any exists.
*/
function stopWatchingForValueChange() {
if (!activeElement) {
return;
}
// delete restores the original property definition
delete activeElement.value;
activeElement.detachEvent('onpropertychange', handlePropertyChange);
activeElement = null;
activeElementID = null;
activeElementValue = null;
activeElementValueProp = null;
}
/**
* (For old IE.) Handles a propertychange event, sending a `change` event if
* the value of the active element has changed.
*/
function handlePropertyChange(nativeEvent) {
if (nativeEvent.propertyName !== 'value') {
return;
}
var value = nativeEvent.srcElement.value;
if (value === activeElementValue) {
return;
}
activeElementValue = value;
manualDispatchChangeEvent(nativeEvent);
}
/**
* If a `change` event should be fired, returns the target's ID.
*/
function getTargetIDForInputEvent(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topInput) {
// In modern browsers (i.e., not IE8 or IE9), the input event is exactly
// what we want so fall through here and trigger an abstract event
return topLevelTargetID;
}
}
// For IE8 and IE9.
function handleEventsForInputEventIE(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topFocus) {
// In IE8, we can capture almost all .value changes by adding a
// propertychange handler and looking for events with propertyName
// equal to 'value'
// In IE9, propertychange fires for most input events but is buggy and
// doesn't fire when text is deleted, but conveniently, selectionchange
// appears to fire in all of the remaining cases so we catch those and
// forward the event if the value has changed
// In either case, we don't want to call the event handler if the value
// is changed from JS so we redefine a setter for `.value` that updates
// our activeElementValue variable, allowing us to ignore those changes
//
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForValueChange();
startWatchingForValueChange(topLevelTarget, topLevelTargetID);
} else if (topLevelType === topLevelTypes.topBlur) {
stopWatchingForValueChange();
}
}
// For IE8 and IE9.
function getTargetIDForInputEventIE(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topSelectionChange ||
topLevelType === topLevelTypes.topKeyUp ||
topLevelType === topLevelTypes.topKeyDown) {
// On the selectionchange event, the target is just document which isn't
// helpful for us so just check activeElement instead.
//
// 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
// propertychange on the first input event after setting `value` from a
// script and fires only keydown, keypress, keyup. Catching keyup usually
// gets it and catching keydown lets us fire an event for the first
// keystroke if user does a key repeat (it'll be a little delayed: right
// before the second keystroke). Other input methods (e.g., paste) seem to
// fire selectionchange normally.
if (activeElement && activeElement.value !== activeElementValue) {
activeElementValue = activeElement.value;
return activeElementID;
}
}
}
/**
* SECTION: handle `click` event
*/
function shouldUseClickEvent(elem) {
// Use the `click` event to detect changes to checkbox and radio inputs.
// This approach works across all browsers, whereas `change` does not fire
// until `blur` in IE8.
return (
elem.nodeName === 'INPUT' &&
(elem.type === 'checkbox' || elem.type === 'radio')
);
}
function getTargetIDForClickEvent(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topClick) {
return topLevelTargetID;
}
}
/**
* This plugin creates an `onChange` event that normalizes change events
* across form elements. This event fires at a time when it's possible to
* change the element's value without seeing a flicker.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - select
*/
var ChangeEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var getTargetIDFunc, handleEventFunc;
if (shouldUseChangeEvent(topLevelTarget)) {
if (doesChangeEventBubble) {
getTargetIDFunc = getTargetIDForChangeEvent;
} else {
handleEventFunc = handleEventsForChangeEventIE8;
}
} else if (isTextInputElement(topLevelTarget)) {
if (isInputEventSupported) {
getTargetIDFunc = getTargetIDForInputEvent;
} else {
getTargetIDFunc = getTargetIDForInputEventIE;
handleEventFunc = handleEventsForInputEventIE;
}
} else if (shouldUseClickEvent(topLevelTarget)) {
getTargetIDFunc = getTargetIDForClickEvent;
}
if (getTargetIDFunc) {
var targetID = getTargetIDFunc(
topLevelType,
topLevelTarget,
topLevelTargetID
);
if (targetID) {
var event = SyntheticEvent.getPooled(
eventTypes.change,
targetID,
nativeEvent
);
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
}
if (handleEventFunc) {
handleEventFunc(
topLevelType,
topLevelTarget,
topLevelTargetID
);
}
}
};
module.exports = ChangeEventPlugin;
},{"./EventConstants":16,"./EventPluginHub":18,"./EventPropagators":21,"./ExecutionEnvironment":22,"./ReactUpdates":87,"./SyntheticEvent":96,"./isEventSupported":135,"./isTextInputElement":137,"./keyOf":141}],8:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ClientReactRootIndex
* @typechecks
*/
"use strict";
var nextReactRootIndex = 0;
var ClientReactRootIndex = {
createReactRootIndex: function() {
return nextReactRootIndex++;
}
};
module.exports = ClientReactRootIndex;
},{}],9:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule CompositionEventPlugin
* @typechecks static-only
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPropagators = _dereq_("./EventPropagators");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var ReactInputSelection = _dereq_("./ReactInputSelection");
var SyntheticCompositionEvent = _dereq_("./SyntheticCompositionEvent");
var getTextContentAccessor = _dereq_("./getTextContentAccessor");
var keyOf = _dereq_("./keyOf");
var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
var START_KEYCODE = 229;
var useCompositionEvent = (
ExecutionEnvironment.canUseDOM &&
'CompositionEvent' in window
);
// In IE9+, we have access to composition events, but the data supplied
// by the native compositionend event may be incorrect. In Korean, for example,
// the compositionend event contains only one character regardless of
// how many characters have been composed since compositionstart.
// We therefore use the fallback data while still using the native
// events as triggers.
var useFallbackData = (
!useCompositionEvent ||
(
'documentMode' in document &&
document.documentMode > 8 &&
document.documentMode <= 11
)
);
var topLevelTypes = EventConstants.topLevelTypes;
var currentComposition = null;
// Events and their corresponding property names.
var eventTypes = {
compositionEnd: {
phasedRegistrationNames: {
bubbled: keyOf({onCompositionEnd: null}),
captured: keyOf({onCompositionEndCapture: null})
},
dependencies: [
topLevelTypes.topBlur,
topLevelTypes.topCompositionEnd,
topLevelTypes.topKeyDown,
topLevelTypes.topKeyPress,
topLevelTypes.topKeyUp,
topLevelTypes.topMouseDown
]
},
compositionStart: {
phasedRegistrationNames: {
bubbled: keyOf({onCompositionStart: null}),
captured: keyOf({onCompositionStartCapture: null})
},
dependencies: [
topLevelTypes.topBlur,
topLevelTypes.topCompositionStart,
topLevelTypes.topKeyDown,
topLevelTypes.topKeyPress,
topLevelTypes.topKeyUp,
topLevelTypes.topMouseDown
]
},
compositionUpdate: {
phasedRegistrationNames: {
bubbled: keyOf({onCompositionUpdate: null}),
captured: keyOf({onCompositionUpdateCapture: null})
},
dependencies: [
topLevelTypes.topBlur,
topLevelTypes.topCompositionUpdate,
topLevelTypes.topKeyDown,
topLevelTypes.topKeyPress,
topLevelTypes.topKeyUp,
topLevelTypes.topMouseDown
]
}
};
/**
* Translate native top level events into event types.
*
* @param {string} topLevelType
* @return {object}
*/
function getCompositionEventType(topLevelType) {
switch (topLevelType) {
case topLevelTypes.topCompositionStart:
return eventTypes.compositionStart;
case topLevelTypes.topCompositionEnd:
return eventTypes.compositionEnd;
case topLevelTypes.topCompositionUpdate:
return eventTypes.compositionUpdate;
}
}
/**
* Does our fallback best-guess model think this event signifies that
* composition has begun?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackStart(topLevelType, nativeEvent) {
return (
topLevelType === topLevelTypes.topKeyDown &&
nativeEvent.keyCode === START_KEYCODE
);
}
/**
* Does our fallback mode think that this event is the end of composition?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackEnd(topLevelType, nativeEvent) {
switch (topLevelType) {
case topLevelTypes.topKeyUp:
// Command keys insert or clear IME input.
return (END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1);
case topLevelTypes.topKeyDown:
// Expect IME keyCode on each keydown. If we get any other
// code we must have exited earlier.
return (nativeEvent.keyCode !== START_KEYCODE);
case topLevelTypes.topKeyPress:
case topLevelTypes.topMouseDown:
case topLevelTypes.topBlur:
// Events are not possible without cancelling IME.
return true;
default:
return false;
}
}
/**
* Helper class stores information about selection and document state
* so we can figure out what changed at a later date.
*
* @param {DOMEventTarget} root
*/
function FallbackCompositionState(root) {
this.root = root;
this.startSelection = ReactInputSelection.getSelection(root);
this.startValue = this.getText();
}
/**
* Get current text of input.
*
* @return {string}
*/
FallbackCompositionState.prototype.getText = function() {
return this.root.value || this.root[getTextContentAccessor()];
};
/**
* Text that has changed since the start of composition.
*
* @return {string}
*/
FallbackCompositionState.prototype.getData = function() {
var endValue = this.getText();
var prefixLength = this.startSelection.start;
var suffixLength = this.startValue.length - this.startSelection.end;
return endValue.substr(
prefixLength,
endValue.length - suffixLength - prefixLength
);
};
/**
* This plugin creates `onCompositionStart`, `onCompositionUpdate` and
* `onCompositionEnd` events on inputs, textareas and contentEditable
* nodes.
*/
var CompositionEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var eventType;
var data;
if (useCompositionEvent) {
eventType = getCompositionEventType(topLevelType);
} else if (!currentComposition) {
if (isFallbackStart(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionStart;
}
} else if (isFallbackEnd(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionEnd;
}
if (useFallbackData) {
// The current composition is stored statically and must not be
// overwritten while composition continues.
if (!currentComposition && eventType === eventTypes.compositionStart) {
currentComposition = new FallbackCompositionState(topLevelTarget);
} else if (eventType === eventTypes.compositionEnd) {
if (currentComposition) {
data = currentComposition.getData();
currentComposition = null;
}
}
}
if (eventType) {
var event = SyntheticCompositionEvent.getPooled(
eventType,
topLevelTargetID,
nativeEvent
);
if (data) {
// Inject data generated from fallback path into the synthetic event.
// This matches the property of native CompositionEventInterface.
event.data = data;
}
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
}
};
module.exports = CompositionEventPlugin;
},{"./EventConstants":16,"./EventPropagators":21,"./ExecutionEnvironment":22,"./ReactInputSelection":63,"./SyntheticCompositionEvent":94,"./getTextContentAccessor":129,"./keyOf":141}],10:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule DOMChildrenOperations
* @typechecks static-only
*/
"use strict";
var Danger = _dereq_("./Danger");
var ReactMultiChildUpdateTypes = _dereq_("./ReactMultiChildUpdateTypes");
var getTextContentAccessor = _dereq_("./getTextContentAccessor");
var invariant = _dereq_("./invariant");
/**
* The DOM property to use when setting text content.
*
* @type {string}
* @private
*/
var textContentAccessor = getTextContentAccessor();
/**
* Inserts `childNode` as a child of `parentNode` at the `index`.
*
* @param {DOMElement} parentNode Parent node in which to insert.
* @param {DOMElement} childNode Child node to insert.
* @param {number} index Index at which to insert the child.
* @internal
*/
function insertChildAt(parentNode, childNode, index) {
// By exploiting arrays returning `undefined` for an undefined index, we can
// rely exclusively on `insertBefore(node, null)` instead of also using
// `appendChild(node)`. However, using `undefined` is not allowed by all
// browsers so we must replace it with `null`.
parentNode.insertBefore(
childNode,
parentNode.childNodes[index] || null
);
}
var updateTextContent;
if (textContentAccessor === 'textContent') {
/**
* Sets the text content of `node` to `text`.
*
* @param {DOMElement} node Node to change
* @param {string} text New text content
*/
updateTextContent = function(node, text) {
node.textContent = text;
};
} else {
/**
* Sets the text content of `node` to `text`.
*
* @param {DOMElement} node Node to change
* @param {string} text New text content
*/
updateTextContent = function(node, text) {
// In order to preserve newlines correctly, we can't use .innerText to set
// the contents (see #1080), so we empty the element then append a text node
while (node.firstChild) {
node.removeChild(node.firstChild);
}
if (text) {
var doc = node.ownerDocument || document;
node.appendChild(doc.createTextNode(text));
}
};
}
/**
* Operations for updating with DOM children.
*/
var DOMChildrenOperations = {
dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup,
updateTextContent: updateTextContent,
/**
* Updates a component's children by processing a series of updates. The
* update configurations are each expected to have a `parentNode` property.
*
* @param {array<object>} updates List of update configurations.
* @param {array<string>} markupList List of markup strings.
* @internal
*/
processUpdates: function(updates, markupList) {
var update;
// Mapping from parent IDs to initial child orderings.
var initialChildren = null;
// List of children that will be moved or removed.
var updatedChildren = null;
for (var i = 0; update = updates[i]; i++) {
if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING ||
update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) {
var updatedIndex = update.fromIndex;
var updatedChild = update.parentNode.childNodes[updatedIndex];
var parentID = update.parentID;
("production" !== "development" ? invariant(
updatedChild,
'processUpdates(): Unable to find child %s of element. This ' +
'probably means the DOM was unexpectedly mutated (e.g., by the ' +
'browser), usually due to forgetting a <tbody> when using tables, ' +
'nesting <p> or <a> tags, or using non-SVG elements in an <svg> '+
'parent. Try inspecting the child nodes of the element with React ' +
'ID `%s`.',
updatedIndex,
parentID
) : invariant(updatedChild));
initialChildren = initialChildren || {};
initialChildren[parentID] = initialChildren[parentID] || [];
initialChildren[parentID][updatedIndex] = updatedChild;
updatedChildren = updatedChildren || [];
updatedChildren.push(updatedChild);
}
}
var renderedMarkup = Danger.dangerouslyRenderMarkup(markupList);
// Remove updated children first so that `toIndex` is consistent.
if (updatedChildren) {
for (var j = 0; j < updatedChildren.length; j++) {
updatedChildren[j].parentNode.removeChild(updatedChildren[j]);
}
}
for (var k = 0; update = updates[k]; k++) {
switch (update.type) {
case ReactMultiChildUpdateTypes.INSERT_MARKUP:
insertChildAt(
update.parentNode,
renderedMarkup[update.markupIndex],
update.toIndex
);
break;
case ReactMultiChildUpdateTypes.MOVE_EXISTING:
insertChildAt(
update.parentNode,
initialChildren[update.parentID][update.fromIndex],
update.toIndex
);
break;
case ReactMultiChildUpdateTypes.TEXT_CONTENT:
updateTextContent(
update.parentNode,
update.textContent
);
break;
case ReactMultiChildUpdateTypes.REMOVE_NODE:
// Already removed by the for-loop above.
break;
}
}
}
};
module.exports = DOMChildrenOperations;
},{"./Danger":13,"./ReactMultiChildUpdateTypes":69,"./getTextContentAccessor":129,"./invariant":134}],11:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule DOMProperty
* @typechecks static-only
*/
/*jslint bitwise: true */
"use strict";
var invariant = _dereq_("./invariant");
var DOMPropertyInjection = {
/**
* Mapping from normalized, camelcased property names to a configuration that
* specifies how the associated DOM property should be accessed or rendered.
*/
MUST_USE_ATTRIBUTE: 0x1,
MUST_USE_PROPERTY: 0x2,
HAS_SIDE_EFFECTS: 0x4,
HAS_BOOLEAN_VALUE: 0x8,
HAS_NUMERIC_VALUE: 0x10,
HAS_POSITIVE_NUMERIC_VALUE: 0x20 | 0x10,
HAS_OVERLOADED_BOOLEAN_VALUE: 0x40,
/**
* Inject some specialized knowledge about the DOM. This takes a config object
* with the following properties:
*
* isCustomAttribute: function that given an attribute name will return true
* if it can be inserted into the DOM verbatim. Useful for data-* or aria-*
* attributes where it's impossible to enumerate all of the possible
* attribute names,
*
* Properties: object mapping DOM property name to one of the
* DOMPropertyInjection constants or null. If your attribute isn't in here,
* it won't get written to the DOM.
*
* DOMAttributeNames: object mapping React attribute name to the DOM
* attribute name. Attribute names not specified use the **lowercase**
* normalized name.
*
* DOMPropertyNames: similar to DOMAttributeNames but for DOM properties.
* Property names not specified use the normalized name.
*
* DOMMutationMethods: Properties that require special mutation methods. If
* `value` is undefined, the mutation method should unset the property.
*
* @param {object} domPropertyConfig the config as described above.
*/
injectDOMPropertyConfig: function(domPropertyConfig) {
var Properties = domPropertyConfig.Properties || {};
var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {};
var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {};
var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {};
if (domPropertyConfig.isCustomAttribute) {
DOMProperty._isCustomAttributeFunctions.push(
domPropertyConfig.isCustomAttribute
);
}
for (var propName in Properties) {
("production" !== "development" ? invariant(
!DOMProperty.isStandardName.hasOwnProperty(propName),
'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' +
'\'%s\' which has already been injected. You may be accidentally ' +
'injecting the same DOM property config twice, or you may be ' +
'injecting two configs that have conflicting property names.',
propName
) : invariant(!DOMProperty.isStandardName.hasOwnProperty(propName)));
DOMProperty.isStandardName[propName] = true;
var lowerCased = propName.toLowerCase();
DOMProperty.getPossibleStandardName[lowerCased] = propName;
if (DOMAttributeNames.hasOwnProperty(propName)) {
var attributeName = DOMAttributeNames[propName];
DOMProperty.getPossibleStandardName[attributeName] = propName;
DOMProperty.getAttributeName[propName] = attributeName;
} else {
DOMProperty.getAttributeName[propName] = lowerCased;
}
DOMProperty.getPropertyName[propName] =
DOMPropertyNames.hasOwnProperty(propName) ?
DOMPropertyNames[propName] :
propName;
if (DOMMutationMethods.hasOwnProperty(propName)) {
DOMProperty.getMutationMethod[propName] = DOMMutationMethods[propName];
} else {
DOMProperty.getMutationMethod[propName] = null;
}
var propConfig = Properties[propName];
DOMProperty.mustUseAttribute[propName] =
propConfig & DOMPropertyInjection.MUST_USE_ATTRIBUTE;
DOMProperty.mustUseProperty[propName] =
propConfig & DOMPropertyInjection.MUST_USE_PROPERTY;
DOMProperty.hasSideEffects[propName] =
propConfig & DOMPropertyInjection.HAS_SIDE_EFFECTS;
DOMProperty.hasBooleanValue[propName] =
propConfig & DOMPropertyInjection.HAS_BOOLEAN_VALUE;
DOMProperty.hasNumericValue[propName] =
propConfig & DOMPropertyInjection.HAS_NUMERIC_VALUE;
DOMProperty.hasPositiveNumericValue[propName] =
propConfig & DOMPropertyInjection.HAS_POSITIVE_NUMERIC_VALUE;
DOMProperty.hasOverloadedBooleanValue[propName] =
propConfig & DOMPropertyInjection.HAS_OVERLOADED_BOOLEAN_VALUE;
("production" !== "development" ? invariant(
!DOMProperty.mustUseAttribute[propName] ||
!DOMProperty.mustUseProperty[propName],
'DOMProperty: Cannot require using both attribute and property: %s',
propName
) : invariant(!DOMProperty.mustUseAttribute[propName] ||
!DOMProperty.mustUseProperty[propName]));
("production" !== "development" ? invariant(
DOMProperty.mustUseProperty[propName] ||
!DOMProperty.hasSideEffects[propName],
'DOMProperty: Properties that have side effects must use property: %s',
propName
) : invariant(DOMProperty.mustUseProperty[propName] ||
!DOMProperty.hasSideEffects[propName]));
("production" !== "development" ? invariant(
!!DOMProperty.hasBooleanValue[propName] +
!!DOMProperty.hasNumericValue[propName] +
!!DOMProperty.hasOverloadedBooleanValue[propName] <= 1,
'DOMProperty: Value can be one of boolean, overloaded boolean, or ' +
'numeric value, but not a combination: %s',
propName
) : invariant(!!DOMProperty.hasBooleanValue[propName] +
!!DOMProperty.hasNumericValue[propName] +
!!DOMProperty.hasOverloadedBooleanValue[propName] <= 1));
}
}
};
var defaultValueCache = {};
/**
* DOMProperty exports lookup objects that can be used like functions:
*
* > DOMProperty.isValid['id']
* true
* > DOMProperty.isValid['foobar']
* undefined
*
* Although this may be confusing, it performs better in general.
*
* @see http://jsperf.com/key-exists
* @see http://jsperf.com/key-missing
*/
var DOMProperty = {
ID_ATTRIBUTE_NAME: 'data-reactid',
/**
* Checks whether a property name is a standard property.
* @type {Object}
*/
isStandardName: {},
/**
* Mapping from lowercase property names to the properly cased version, used
* to warn in the case of missing properties.
* @type {Object}
*/
getPossibleStandardName: {},
/**
* Mapping from normalized names to attribute names that differ. Attribute
* names are used when rendering markup or with `*Attribute()`.
* @type {Object}
*/
getAttributeName: {},
/**
* Mapping from normalized names to properties on DOM node instances.
* (This includes properties that mutate due to external factors.)
* @type {Object}
*/
getPropertyName: {},
/**
* Mapping from normalized names to mutation methods. This will only exist if
* mutation cannot be set simply by the property or `setAttribute()`.
* @type {Object}
*/
getMutationMethod: {},
/**
* Whether the property must be accessed and mutated as an object property.
* @type {Object}
*/
mustUseAttribute: {},
/**
* Whether the property must be accessed and mutated using `*Attribute()`.
* (This includes anything that fails `<propName> in <element>`.)
* @type {Object}
*/
mustUseProperty: {},
/**
* Whether or not setting a value causes side effects such as triggering
* resources to be loaded or text selection changes. We must ensure that
* the value is only set if it has changed.
* @type {Object}
*/
hasSideEffects: {},
/**
* Whether the property should be removed when set to a falsey value.
* @type {Object}
*/
hasBooleanValue: {},
/**
* Whether the property must be numeric or parse as a
* numeric and should be removed when set to a falsey value.
* @type {Object}
*/
hasNumericValue: {},
/**
* Whether the property must be positive numeric or parse as a positive
* numeric and should be removed when set to a falsey value.
* @type {Object}
*/
hasPositiveNumericValue: {},
/**
* Whether the property can be used as a flag as well as with a value. Removed
* when strictly equal to false; present without a value when strictly equal
* to true; present with a value otherwise.
* @type {Object}
*/
hasOverloadedBooleanValue: {},
/**
* All of the isCustomAttribute() functions that have been injected.
*/
_isCustomAttributeFunctions: [],
/**
* Checks whether a property name is a custom attribute.
* @method
*/
isCustomAttribute: function(attributeName) {
for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) {
var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i];
if (isCustomAttributeFn(attributeName)) {
return true;
}
}
return false;
},
/**
* Returns the default property value for a DOM property (i.e., not an
* attribute). Most default values are '' or false, but not all. Worse yet,
* some (in particular, `type`) vary depending on the type of element.
*
* TODO: Is it better to grab all the possible properties when creating an
* element to avoid having to create the same element twice?
*/
getDefaultValueForProperty: function(nodeName, prop) {
var nodeDefaults = defaultValueCache[nodeName];
var testElement;
if (!nodeDefaults) {
defaultValueCache[nodeName] = nodeDefaults = {};
}
if (!(prop in nodeDefaults)) {
testElement = document.createElement(nodeName);
nodeDefaults[prop] = testElement[prop];
}
return nodeDefaults[prop];
},
injection: DOMPropertyInjection
};
module.exports = DOMProperty;
},{"./invariant":134}],12:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule DOMPropertyOperations
* @typechecks static-only
*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var escapeTextForBrowser = _dereq_("./escapeTextForBrowser");
var memoizeStringOnly = _dereq_("./memoizeStringOnly");
var warning = _dereq_("./warning");
function shouldIgnoreValue(name, value) {
return value == null ||
(DOMProperty.hasBooleanValue[name] && !value) ||
(DOMProperty.hasNumericValue[name] && isNaN(value)) ||
(DOMProperty.hasPositiveNumericValue[name] && (value < 1)) ||
(DOMProperty.hasOverloadedBooleanValue[name] && value === false);
}
var processAttributeNameAndPrefix = memoizeStringOnly(function(name) {
return escapeTextForBrowser(name) + '="';
});
if ("production" !== "development") {
var reactProps = {
children: true,
dangerouslySetInnerHTML: true,
key: true,
ref: true
};
var warnedProperties = {};
var warnUnknownProperty = function(name) {
if (reactProps.hasOwnProperty(name) && reactProps[name] ||
warnedProperties.hasOwnProperty(name) && warnedProperties[name]) {
return;
}
warnedProperties[name] = true;
var lowerCasedName = name.toLowerCase();
// data-* attributes should be lowercase; suggest the lowercase version
var standardName = (
DOMProperty.isCustomAttribute(lowerCasedName) ?
lowerCasedName :
DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ?
DOMProperty.getPossibleStandardName[lowerCasedName] :
null
);
// For now, only warn when we have a suggested correction. This prevents
// logging too much when using transferPropsTo.
("production" !== "development" ? warning(
standardName == null,
'Unknown DOM property ' + name + '. Did you mean ' + standardName + '?'
) : null);
};
}
/**
* Operations for dealing with DOM properties.
*/
var DOMPropertyOperations = {
/**
* Creates markup for the ID property.
*
* @param {string} id Unescaped ID.
* @return {string} Markup string.
*/
createMarkupForID: function(id) {
return processAttributeNameAndPrefix(DOMProperty.ID_ATTRIBUTE_NAME) +
escapeTextForBrowser(id) + '"';
},
/**
* Creates markup for a property.
*
* @param {string} name
* @param {*} value
* @return {?string} Markup string, or null if the property was invalid.
*/
createMarkupForProperty: function(name, value) {
if (DOMProperty.isStandardName.hasOwnProperty(name) &&
DOMProperty.isStandardName[name]) {
if (shouldIgnoreValue(name, value)) {
return '';
}
var attributeName = DOMProperty.getAttributeName[name];
if (DOMProperty.hasBooleanValue[name] ||
(DOMProperty.hasOverloadedBooleanValue[name] && value === true)) {
return escapeTextForBrowser(attributeName);
}
return processAttributeNameAndPrefix(attributeName) +
escapeTextForBrowser(value) + '"';
} else if (DOMProperty.isCustomAttribute(name)) {
if (value == null) {
return '';
}
return processAttributeNameAndPrefix(name) +
escapeTextForBrowser(value) + '"';
} else if ("production" !== "development") {
warnUnknownProperty(name);
}
return null;
},
/**
* Sets the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
* @param {*} value
*/
setValueForProperty: function(node, name, value) {
if (DOMProperty.isStandardName.hasOwnProperty(name) &&
DOMProperty.isStandardName[name]) {
var mutationMethod = DOMProperty.getMutationMethod[name];
if (mutationMethod) {
mutationMethod(node, value);
} else if (shouldIgnoreValue(name, value)) {
this.deleteValueForProperty(node, name);
} else if (DOMProperty.mustUseAttribute[name]) {
node.setAttribute(DOMProperty.getAttributeName[name], '' + value);
} else {
var propName = DOMProperty.getPropertyName[name];
if (!DOMProperty.hasSideEffects[name] || node[propName] !== value) {
node[propName] = value;
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
if (value == null) {
node.removeAttribute(name);
} else {
node.setAttribute(name, '' + value);
}
} else if ("production" !== "development") {
warnUnknownProperty(name);
}
},
/**
* Deletes the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
*/
deleteValueForProperty: function(node, name) {
if (DOMProperty.isStandardName.hasOwnProperty(name) &&
DOMProperty.isStandardName[name]) {
var mutationMethod = DOMProperty.getMutationMethod[name];
if (mutationMethod) {
mutationMethod(node, undefined);
} else if (DOMProperty.mustUseAttribute[name]) {
node.removeAttribute(DOMProperty.getAttributeName[name]);
} else {
var propName = DOMProperty.getPropertyName[name];
var defaultValue = DOMProperty.getDefaultValueForProperty(
node.nodeName,
propName
);
if (!DOMProperty.hasSideEffects[name] ||
node[propName] !== defaultValue) {
node[propName] = defaultValue;
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
node.removeAttribute(name);
} else if ("production" !== "development") {
warnUnknownProperty(name);
}
}
};
module.exports = DOMPropertyOperations;
},{"./DOMProperty":11,"./escapeTextForBrowser":118,"./memoizeStringOnly":143,"./warning":158}],13:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule Danger
* @typechecks static-only
*/
/*jslint evil: true, sub: true */
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var createNodesFromMarkup = _dereq_("./createNodesFromMarkup");
var emptyFunction = _dereq_("./emptyFunction");
var getMarkupWrap = _dereq_("./getMarkupWrap");
var invariant = _dereq_("./invariant");
var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/;
var RESULT_INDEX_ATTR = 'data-danger-index';
/**
* Extracts the `nodeName` from a string of markup.
*
* NOTE: Extracting the `nodeName` does not require a regular expression match
* because we make assumptions about React-generated markup (i.e. there are no
* spaces surrounding the opening tag and there is at least one attribute).
*
* @param {string} markup String of markup.
* @return {string} Node name of the supplied markup.
* @see http://jsperf.com/extract-nodename
*/
function getNodeName(markup) {
return markup.substring(1, markup.indexOf(' '));
}
var Danger = {
/**
* Renders markup into an array of nodes. The markup is expected to render
* into a list of root nodes. Also, the length of `resultList` and
* `markupList` should be the same.
*
* @param {array<string>} markupList List of markup strings to render.
* @return {array<DOMElement>} List of rendered nodes.
* @internal
*/
dangerouslyRenderMarkup: function(markupList) {
("production" !== "development" ? invariant(
ExecutionEnvironment.canUseDOM,
'dangerouslyRenderMarkup(...): Cannot render markup in a Worker ' +
'thread. This is likely a bug in the framework. Please report ' +
'immediately.'
) : invariant(ExecutionEnvironment.canUseDOM));
var nodeName;
var markupByNodeName = {};
// Group markup by `nodeName` if a wrap is necessary, else by '*'.
for (var i = 0; i < markupList.length; i++) {
("production" !== "development" ? invariant(
markupList[i],
'dangerouslyRenderMarkup(...): Missing markup.'
) : invariant(markupList[i]));
nodeName = getNodeName(markupList[i]);
nodeName = getMarkupWrap(nodeName) ? nodeName : '*';
markupByNodeName[nodeName] = markupByNodeName[nodeName] || [];
markupByNodeName[nodeName][i] = markupList[i];
}
var resultList = [];
var resultListAssignmentCount = 0;
for (nodeName in markupByNodeName) {
if (!markupByNodeName.hasOwnProperty(nodeName)) {
continue;
}
var markupListByNodeName = markupByNodeName[nodeName];
// This for-in loop skips the holes of the sparse array. The order of
// iteration should follow the order of assignment, which happens to match
// numerical index order, but we don't rely on that.
for (var resultIndex in markupListByNodeName) {
if (markupListByNodeName.hasOwnProperty(resultIndex)) {
var markup = markupListByNodeName[resultIndex];
// Push the requested markup with an additional RESULT_INDEX_ATTR
// attribute. If the markup does not start with a < character, it
// will be discarded below (with an appropriate console.error).
markupListByNodeName[resultIndex] = markup.replace(
OPEN_TAG_NAME_EXP,
// This index will be parsed back out below.
'$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" '
);
}
}
// Render each group of markup with similar wrapping `nodeName`.
var renderNodes = createNodesFromMarkup(
markupListByNodeName.join(''),
emptyFunction // Do nothing special with <script> tags.
);
for (i = 0; i < renderNodes.length; ++i) {
var renderNode = renderNodes[i];
if (renderNode.hasAttribute &&
renderNode.hasAttribute(RESULT_INDEX_ATTR)) {
resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR);
renderNode.removeAttribute(RESULT_INDEX_ATTR);
("production" !== "development" ? invariant(
!resultList.hasOwnProperty(resultIndex),
'Danger: Assigning to an already-occupied result index.'
) : invariant(!resultList.hasOwnProperty(resultIndex)));
resultList[resultIndex] = renderNode;
// This should match resultList.length and markupList.length when
// we're done.
resultListAssignmentCount += 1;
} else if ("production" !== "development") {
console.error(
"Danger: Discarding unexpected node:",
renderNode
);
}
}
}
// Although resultList was populated out of order, it should now be a dense
// array.
("production" !== "development" ? invariant(
resultListAssignmentCount === resultList.length,
'Danger: Did not assign to every index of resultList.'
) : invariant(resultListAssignmentCount === resultList.length));
("production" !== "development" ? invariant(
resultList.length === markupList.length,
'Danger: Expected markup to render %s nodes, but rendered %s.',
markupList.length,
resultList.length
) : invariant(resultList.length === markupList.length));
return resultList;
},
/**
* Replaces a node with a string of markup at its current position within its
* parent. The markup must render into a single root node.
*
* @param {DOMElement} oldChild Child node to replace.
* @param {string} markup Markup to render in place of the child node.
* @internal
*/
dangerouslyReplaceNodeWithMarkup: function(oldChild, markup) {
("production" !== "development" ? invariant(
ExecutionEnvironment.canUseDOM,
'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' +
'worker thread. This is likely a bug in the framework. Please report ' +
'immediately.'
) : invariant(ExecutionEnvironment.canUseDOM));
("production" !== "development" ? invariant(markup, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(markup));
("production" !== "development" ? invariant(
oldChild.tagName.toLowerCase() !== 'html',
'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the ' +
'<html> node. This is because browser quirks make this unreliable ' +
'and/or slow. If you want to render to the root you must use ' +
'server rendering. See renderComponentToString().'
) : invariant(oldChild.tagName.toLowerCase() !== 'html'));
var newChild = createNodesFromMarkup(markup, emptyFunction)[0];
oldChild.parentNode.replaceChild(newChild, oldChild);
}
};
module.exports = Danger;
},{"./ExecutionEnvironment":22,"./createNodesFromMarkup":113,"./emptyFunction":116,"./getMarkupWrap":126,"./invariant":134}],14:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule DefaultEventPluginOrder
*/
"use strict";
var keyOf = _dereq_("./keyOf");
/**
* Module that is injectable into `EventPluginHub`, that specifies a
* deterministic ordering of `EventPlugin`s. A convenient way to reason about
* plugins, without having to package every one of them. This is better than
* having plugins be ordered in the same order that they are injected because
* that ordering would be influenced by the packaging order.
* `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
* preventing default on events is convenient in `SimpleEventPlugin` handlers.
*/
var DefaultEventPluginOrder = [
keyOf({ResponderEventPlugin: null}),
keyOf({SimpleEventPlugin: null}),
keyOf({TapEventPlugin: null}),
keyOf({EnterLeaveEventPlugin: null}),
keyOf({ChangeEventPlugin: null}),
keyOf({SelectEventPlugin: null}),
keyOf({CompositionEventPlugin: null}),
keyOf({BeforeInputEventPlugin: null}),
keyOf({AnalyticsEventPlugin: null}),
keyOf({MobileSafariClickEventPlugin: null})
];
module.exports = DefaultEventPluginOrder;
},{"./keyOf":141}],15:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule EnterLeaveEventPlugin
* @typechecks static-only
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPropagators = _dereq_("./EventPropagators");
var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent");
var ReactMount = _dereq_("./ReactMount");
var keyOf = _dereq_("./keyOf");
var topLevelTypes = EventConstants.topLevelTypes;
var getFirstReactDOM = ReactMount.getFirstReactDOM;
var eventTypes = {
mouseEnter: {
registrationName: keyOf({onMouseEnter: null}),
dependencies: [
topLevelTypes.topMouseOut,
topLevelTypes.topMouseOver
]
},
mouseLeave: {
registrationName: keyOf({onMouseLeave: null}),
dependencies: [
topLevelTypes.topMouseOut,
topLevelTypes.topMouseOver
]
}
};
var extractedEvents = [null, null];
var EnterLeaveEventPlugin = {
eventTypes: eventTypes,
/**
* For almost every interaction we care about, there will be both a top-level
* `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
* we do not extract duplicate events. However, moving the mouse into the
* browser from outside will not fire a `mouseout` event. In this case, we use
* the `mouseover` top-level event.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
if (topLevelType === topLevelTypes.topMouseOver &&
(nativeEvent.relatedTarget || nativeEvent.fromElement)) {
return null;
}
if (topLevelType !== topLevelTypes.topMouseOut &&
topLevelType !== topLevelTypes.topMouseOver) {
// Must not be a mouse in or mouse out - ignoring.
return null;
}
var win;
if (topLevelTarget.window === topLevelTarget) {
// `topLevelTarget` is probably a window object.
win = topLevelTarget;
} else {
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
var doc = topLevelTarget.ownerDocument;
if (doc) {
win = doc.defaultView || doc.parentWindow;
} else {
win = window;
}
}
var from, to;
if (topLevelType === topLevelTypes.topMouseOut) {
from = topLevelTarget;
to =
getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement) ||
win;
} else {
from = win;
to = topLevelTarget;
}
if (from === to) {
// Nothing pertains to our managed components.
return null;
}
var fromID = from ? ReactMount.getID(from) : '';
var toID = to ? ReactMount.getID(to) : '';
var leave = SyntheticMouseEvent.getPooled(
eventTypes.mouseLeave,
fromID,
nativeEvent
);
leave.type = 'mouseleave';
leave.target = from;
leave.relatedTarget = to;
var enter = SyntheticMouseEvent.getPooled(
eventTypes.mouseEnter,
toID,
nativeEvent
);
enter.type = 'mouseenter';
enter.target = to;
enter.relatedTarget = from;
EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID);
extractedEvents[0] = leave;
extractedEvents[1] = enter;
return extractedEvents;
}
};
module.exports = EnterLeaveEventPlugin;
},{"./EventConstants":16,"./EventPropagators":21,"./ReactMount":67,"./SyntheticMouseEvent":100,"./keyOf":141}],16:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule 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":140}],17:[function(_dereq_,module,exports){
/**
* @providesModule EventListener
* @typechecks
*/
var emptyFunction = _dereq_("./emptyFunction");
/**
* Upstream version of event listener. Does not take into account specific
* nature of platform.
*/
var EventListener = {
/**
* Listen to DOM events during the bubble phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
listen: function(target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, false);
return {
remove: function() {
target.removeEventListener(eventType, callback, false);
}
};
} else if (target.attachEvent) {
target.attachEvent('on' + eventType, callback);
return {
remove: function() {
target.detachEvent('on' + eventType, callback);
}
};
}
},
/**
* Listen to DOM events during the capture phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
capture: function(target, eventType, callback) {
if (!target.addEventListener) {
if ("production" !== "development") {
console.error(
'Attempted to listen to events during the capture phase on a ' +
'browser that does not support the capture phase. Your application ' +
'will not receive some events.'
);
}
return {
remove: emptyFunction
};
} else {
target.addEventListener(eventType, callback, true);
return {
remove: function() {
target.removeEventListener(eventType, callback, true);
}
};
}
},
registerDefault: function() {}
};
module.exports = EventListener;
},{"./emptyFunction":116}],18:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule 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" !== "development") {
validateInstanceHandle();
}
},
getInstanceHandle: function() {
if ("production" !== "development") {
validateInstanceHandle();
}
return InstanceHandle;
},
/**
* @param {array} InjectedEventPluginOrder
* @public
*/
injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder,
/**
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
*/
injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName
},
eventNameDispatchConfigs: EventPluginRegistry.eventNameDispatchConfigs,
registrationNameModules: EventPluginRegistry.registrationNameModules,
/**
* Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent.
*
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {?function} listener The callback to store.
*/
putListener: function(id, registrationName, listener) {
("production" !== "development" ? invariant(
!listener || typeof listener === 'function',
'Expected %s listener to be a function, instead got type %s',
registrationName, typeof listener
) : invariant(!listener || typeof listener === 'function'));
if ("production" !== "development") {
// IE8 has no API for event capturing and the `onScroll` event doesn't
// bubble.
if (registrationName === 'onScroll' &&
!isEventSupported('scroll', true)) {
monitorCodeUse('react_no_scroll_event');
console.warn('This browser doesn\'t support the `onScroll` event');
}
}
var bankForRegistrationName =
listenerBank[registrationName] || (listenerBank[registrationName] = {});
bankForRegistrationName[id] = listener;
},
/**
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @return {?function} The stored callback.
*/
getListener: function(id, registrationName) {
var bankForRegistrationName = listenerBank[registrationName];
return bankForRegistrationName && bankForRegistrationName[id];
},
/**
* Deletes a listener from the registration bank.
*
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
*/
deleteListener: function(id, registrationName) {
var bankForRegistrationName = listenerBank[registrationName];
if (bankForRegistrationName) {
delete bankForRegistrationName[id];
}
},
/**
* Deletes all listeners for the DOM element with the supplied ID.
*
* @param {string} id ID of the DOM element.
*/
deleteAllListeners: function(id) {
for (var registrationName in listenerBank) {
delete listenerBank[registrationName][id];
}
},
/**
* Allows registered plugins an opportunity to extract events from top-level
* native browser events.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @internal
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var events;
var plugins = EventPluginRegistry.plugins;
for (var i = 0, l = plugins.length; i < l; i++) {
// Not every plugin in the ordering may be loaded at runtime.
var possiblePlugin = plugins[i];
if (possiblePlugin) {
var extractedEvents = possiblePlugin.extractEvents(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent
);
if (extractedEvents) {
events = accumulate(events, extractedEvents);
}
}
}
return events;
},
/**
* Enqueues a synthetic event that should be dispatched when
* `processEventQueue` is invoked.
*
* @param {*} events An accumulation of synthetic events.
* @internal
*/
enqueueEvents: function(events) {
if (events) {
eventQueue = accumulate(eventQueue, events);
}
},
/**
* Dispatches all synthetic events on the event queue.
*
* @internal
*/
processEventQueue: function() {
// Set `eventQueue` to null before processing it so that we can tell if more
// events get enqueued while processing.
var processingEventQueue = eventQueue;
eventQueue = null;
forEachAccumulated(processingEventQueue, executeDispatchesAndRelease);
("production" !== "development" ? invariant(
!eventQueue,
'processEventQueue(): Additional events were enqueued while processing ' +
'an event queue. Support for this has not yet been implemented.'
) : invariant(!eventQueue));
},
/**
* These are needed for tests only. Do not use!
*/
__purge: function() {
listenerBank = {};
},
__getListenerBank: function() {
return listenerBank;
}
};
module.exports = EventPluginHub;
},{"./EventPluginRegistry":19,"./EventPluginUtils":20,"./accumulate":106,"./forEachAccumulated":121,"./invariant":134,"./isEventSupported":135,"./monitorCodeUse":148}],19:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule EventPluginRegistry
* @typechecks static-only
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* Injectable ordering of event plugins.
*/
var EventPluginOrder = null;
/**
* Injectable mapping from names to event plugin modules.
*/
var namesToPlugins = {};
/**
* Recomputes the plugin list using the injected plugins and plugin ordering.
*
* @private
*/
function recomputePluginOrdering() {
if (!EventPluginOrder) {
// Wait until an `EventPluginOrder` is injected.
return;
}
for (var pluginName in namesToPlugins) {
var PluginModule = namesToPlugins[pluginName];
var pluginIndex = EventPluginOrder.indexOf(pluginName);
("production" !== "development" ? invariant(
pluginIndex > -1,
'EventPluginRegistry: Cannot inject event plugins that do not exist in ' +
'the plugin ordering, `%s`.',
pluginName
) : invariant(pluginIndex > -1));
if (EventPluginRegistry.plugins[pluginIndex]) {
continue;
}
("production" !== "development" ? invariant(
PluginModule.extractEvents,
'EventPluginRegistry: Event plugins must implement an `extractEvents` ' +
'method, but `%s` does not.',
pluginName
) : invariant(PluginModule.extractEvents));
EventPluginRegistry.plugins[pluginIndex] = PluginModule;
var publishedEvents = PluginModule.eventTypes;
for (var eventName in publishedEvents) {
("production" !== "development" ? invariant(
publishEventForPlugin(
publishedEvents[eventName],
PluginModule,
eventName
),
'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.',
eventName,
pluginName
) : invariant(publishEventForPlugin(
publishedEvents[eventName],
PluginModule,
eventName
)));
}
}
}
/**
* Publishes an event so that it can be dispatched by the supplied plugin.
*
* @param {object} dispatchConfig Dispatch configuration for the event.
* @param {object} PluginModule Plugin publishing the event.
* @return {boolean} True if the event was successfully published.
* @private
*/
function publishEventForPlugin(dispatchConfig, PluginModule, eventName) {
("production" !== "development" ? invariant(
!EventPluginRegistry.eventNameDispatchConfigs.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" !== "development" ? invariant(
!EventPluginRegistry.registrationNameModules[registrationName],
'EventPluginHub: More than one plugin attempted to publish the same ' +
'registration name, `%s`.',
registrationName
) : invariant(!EventPluginRegistry.registrationNameModules[registrationName]));
EventPluginRegistry.registrationNameModules[registrationName] = PluginModule;
EventPluginRegistry.registrationNameDependencies[registrationName] =
PluginModule.eventTypes[eventName].dependencies;
}
/**
* Registers plugins so that they can extract and dispatch events.
*
* @see {EventPluginHub}
*/
var EventPluginRegistry = {
/**
* Ordered list of injected plugins.
*/
plugins: [],
/**
* Mapping from event name to dispatch config
*/
eventNameDispatchConfigs: {},
/**
* Mapping from registration name to plugin module
*/
registrationNameModules: {},
/**
* Mapping from registration name to event name
*/
registrationNameDependencies: {},
/**
* Injects an ordering of plugins (by plugin name). This allows the ordering
* to be decoupled from injection of the actual plugins so that ordering is
* always deterministic regardless of packaging, on-the-fly injection, etc.
*
* @param {array} InjectedEventPluginOrder
* @internal
* @see {EventPluginHub.injection.injectEventPluginOrder}
*/
injectEventPluginOrder: function(InjectedEventPluginOrder) {
("production" !== "development" ? invariant(
!EventPluginOrder,
'EventPluginRegistry: Cannot inject event plugin ordering more than ' +
'once. 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" !== "development" ? invariant(
!namesToPlugins[pluginName],
'EventPluginRegistry: Cannot inject two different event plugins ' +
'using the same name, `%s`.',
pluginName
) : invariant(!namesToPlugins[pluginName]));
namesToPlugins[pluginName] = PluginModule;
isOrderingDirty = true;
}
}
if (isOrderingDirty) {
recomputePluginOrdering();
}
},
/**
* Looks up the plugin for the supplied event.
*
* @param {object} event A synthetic event.
* @return {?object} The plugin that created the supplied event.
* @internal
*/
getPluginModuleForEvent: function(event) {
var dispatchConfig = event.dispatchConfig;
if (dispatchConfig.registrationName) {
return EventPluginRegistry.registrationNameModules[
dispatchConfig.registrationName
] || null;
}
for (var phase in dispatchConfig.phasedRegistrationNames) {
if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) {
continue;
}
var PluginModule = EventPluginRegistry.registrationNameModules[
dispatchConfig.phasedRegistrationNames[phase]
];
if (PluginModule) {
return PluginModule;
}
}
return null;
},
/**
* Exposed for unit testing.
* @private
*/
_resetEventPlugins: function() {
EventPluginOrder = null;
for (var pluginName in namesToPlugins) {
if (namesToPlugins.hasOwnProperty(pluginName)) {
delete namesToPlugins[pluginName];
}
}
EventPluginRegistry.plugins.length = 0;
var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs;
for (var eventName in eventNameDispatchConfigs) {
if (eventNameDispatchConfigs.hasOwnProperty(eventName)) {
delete eventNameDispatchConfigs[eventName];
}
}
var registrationNameModules = EventPluginRegistry.registrationNameModules;
for (var registrationName in registrationNameModules) {
if (registrationNameModules.hasOwnProperty(registrationName)) {
delete registrationNameModules[registrationName];
}
}
}
};
module.exports = EventPluginRegistry;
},{"./invariant":134}],20:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule EventPluginUtils
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var invariant = _dereq_("./invariant");
/**
* Injected dependencies:
*/
/**
* - `Mount`: [required] Module that can convert between React dom IDs and
* actual node references.
*/
var injection = {
Mount: null,
injectMount: function(InjectedMount) {
injection.Mount = InjectedMount;
if ("production" !== "development") {
("production" !== "development" ? invariant(
InjectedMount && InjectedMount.getNode,
'EventPluginUtils.injection.injectMount(...): Injected Mount module ' +
'is missing getNode.'
) : invariant(InjectedMount && InjectedMount.getNode));
}
}
};
var topLevelTypes = EventConstants.topLevelTypes;
function isEndish(topLevelType) {
return topLevelType === topLevelTypes.topMouseUp ||
topLevelType === topLevelTypes.topTouchEnd ||
topLevelType === topLevelTypes.topTouchCancel;
}
function isMoveish(topLevelType) {
return topLevelType === topLevelTypes.topMouseMove ||
topLevelType === topLevelTypes.topTouchMove;
}
function isStartish(topLevelType) {
return topLevelType === topLevelTypes.topMouseDown ||
topLevelType === topLevelTypes.topTouchStart;
}
var validateEventDispatches;
if ("production" !== "development") {
validateEventDispatches = function(event) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
var listenersIsArr = Array.isArray(dispatchListeners);
var idsIsArr = Array.isArray(dispatchIDs);
var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0;
var listenersLen = listenersIsArr ?
dispatchListeners.length :
dispatchListeners ? 1 : 0;
("production" !== "development" ? invariant(
idsIsArr === listenersIsArr && IDsLen === listenersLen,
'EventPluginUtils: Invalid `event`.'
) : invariant(idsIsArr === listenersIsArr && IDsLen === listenersLen));
};
}
/**
* Invokes `cb(event, listener, id)`. Avoids using call if no scope is
* provided. The `(listener,id)` pair effectively forms the "dispatch" but are
* kept separate to conserve memory.
*/
function forEachEventDispatch(event, cb) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
if ("production" !== "development") {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and IDs are two parallel arrays that are always in sync.
cb(event, dispatchListeners[i], dispatchIDs[i]);
}
} else if (dispatchListeners) {
cb(event, dispatchListeners, dispatchIDs);
}
}
/**
* Default implementation of PluginModule.executeDispatch().
* @param {SyntheticEvent} SyntheticEvent to handle
* @param {function} Application-level callback
* @param {string} domID DOM id to pass to the callback.
*/
function executeDispatch(event, listener, domID) {
event.currentTarget = injection.Mount.getNode(domID);
var returnValue = listener(event, domID);
event.currentTarget = null;
return returnValue;
}
/**
* Standard/simple iteration through an event's collected dispatches.
*/
function executeDispatchesInOrder(event, executeDispatch) {
forEachEventDispatch(event, executeDispatch);
event._dispatchListeners = null;
event._dispatchIDs = null;
}
/**
* Standard/simple iteration through an event's collected dispatches, but stops
* at the first dispatch execution returning true, and returns that id.
*
* @return id of the first dispatch execution who's listener returns true, or
* null if no listener returned true.
*/
function executeDispatchesInOrderStopAtTrueImpl(event) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
if ("production" !== "development") {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and IDs are two parallel arrays that are always in sync.
if (dispatchListeners[i](event, dispatchIDs[i])) {
return dispatchIDs[i];
}
}
} else if (dispatchListeners) {
if (dispatchListeners(event, dispatchIDs)) {
return dispatchIDs;
}
}
return null;
}
/**
* @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" !== "development") {
validateEventDispatches(event);
}
var dispatchListener = event._dispatchListeners;
var dispatchID = event._dispatchIDs;
("production" !== "development" ? invariant(
!Array.isArray(dispatchListener),
'executeDirectDispatch(...): Invalid `event`.'
) : invariant(!Array.isArray(dispatchListener)));
var res = dispatchListener ?
dispatchListener(event, dispatchID) :
null;
event._dispatchListeners = null;
event._dispatchIDs = null;
return res;
}
/**
* @param {SyntheticEvent} event
* @return {bool} True iff number of dispatches accumulated is greater than 0.
*/
function hasDispatches(event) {
return !!event._dispatchListeners;
}
/**
* General utilities that are useful in creating custom Event Plugins.
*/
var EventPluginUtils = {
isEndish: isEndish,
isMoveish: isMoveish,
isStartish: isStartish,
executeDirectDispatch: executeDirectDispatch,
executeDispatch: executeDispatch,
executeDispatchesInOrder: executeDispatchesInOrder,
executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue,
hasDispatches: hasDispatches,
injection: injection,
useTouchEvents: false
};
module.exports = EventPluginUtils;
},{"./EventConstants":16,"./invariant":134}],21:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule EventPropagators
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPluginHub = _dereq_("./EventPluginHub");
var accumulate = _dereq_("./accumulate");
var forEachAccumulated = _dereq_("./forEachAccumulated");
var PropagationPhases = EventConstants.PropagationPhases;
var getListener = EventPluginHub.getListener;
/**
* Some event types have a notion of different registration names for different
* "phases" of propagation. This finds listeners by a given phase.
*/
function listenerAtPhase(id, event, propagationPhase) {
var registrationName =
event.dispatchConfig.phasedRegistrationNames[propagationPhase];
return getListener(id, registrationName);
}
/**
* Tags a `SyntheticEvent` with dispatched listeners. Creating this function
* here, allows us to not have to bind or create functions for each event.
* Mutating the event's members allows us to not have to create a wrapping
* "dispatch" object that pairs the event with the listener.
*/
function accumulateDirectionalDispatches(domID, upwards, event) {
if ("production" !== "development") {
if (!domID) {
throw new Error('Dispatching id must not be null');
}
}
var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured;
var listener = listenerAtPhase(domID, event, phase);
if (listener) {
event._dispatchListeners = accumulate(event._dispatchListeners, listener);
event._dispatchIDs = accumulate(event._dispatchIDs, domID);
}
}
/**
* Collect dispatches (must be entirely collected before dispatching - see unit
* tests). Lazily allocate the array to conserve memory. We must loop through
* each event and perform the traversal for each one. We can not perform a
* single traversal for the entire collection of events because each event may
* have a different target.
*/
function accumulateTwoPhaseDispatchesSingle(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
EventPluginHub.injection.getInstanceHandle().traverseTwoPhase(
event.dispatchMarker,
accumulateDirectionalDispatches,
event
);
}
}
/**
* Accumulates without regard to direction, does not look for phased
* registration names. Same as `accumulateDirectDispatchesSingle` but without
* requiring that the `dispatchMarker` be the same as the dispatched ID.
*/
function accumulateDispatches(id, ignoredDirection, event) {
if (event && event.dispatchConfig.registrationName) {
var registrationName = event.dispatchConfig.registrationName;
var listener = getListener(id, registrationName);
if (listener) {
event._dispatchListeners = accumulate(event._dispatchListeners, listener);
event._dispatchIDs = accumulate(event._dispatchIDs, id);
}
}
}
/**
* Accumulates dispatches on an `SyntheticEvent`, but only for the
* `dispatchMarker`.
* @param {SyntheticEvent} event
*/
function accumulateDirectDispatchesSingle(event) {
if (event && event.dispatchConfig.registrationName) {
accumulateDispatches(event.dispatchMarker, null, event);
}
}
function accumulateTwoPhaseDispatches(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
}
function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) {
EventPluginHub.injection.getInstanceHandle().traverseEnterLeave(
fromID,
toID,
accumulateDispatches,
leave,
enter
);
}
function accumulateDirectDispatches(events) {
forEachAccumulated(events, accumulateDirectDispatchesSingle);
}
/**
* A small set of propagation patterns, each of which will accept a small amount
* of information, and generate a set of "dispatch ready event objects" - which
* are sets of events that have already been annotated with a set of dispatched
* listener functions/ids. The API is designed this way to discourage these
* propagation strategies from actually executing the dispatches, since we
* always want to collect the entire set of dispatches before executing event a
* single one.
*
* @constructor EventPropagators
*/
var EventPropagators = {
accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches,
accumulateDirectDispatches: accumulateDirectDispatches,
accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches
};
module.exports = EventPropagators;
},{"./EventConstants":16,"./EventPluginHub":18,"./accumulate":106,"./forEachAccumulated":121}],22:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule 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;
},{}],23:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule HTMLDOMPropertyConfig
*/
/*jslint bitwise: true*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS;
var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE;
var HAS_POSITIVE_NUMERIC_VALUE =
DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
var HAS_OVERLOADED_BOOLEAN_VALUE =
DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE;
var hasSVG;
if (ExecutionEnvironment.canUseDOM) {
var implementation = document.implementation;
hasSVG = (
implementation &&
implementation.hasFeature &&
implementation.hasFeature(
'http://www.w3.org/TR/SVG11/feature#BasicStructure',
'1.1'
)
);
}
var HTMLDOMPropertyConfig = {
isCustomAttribute: RegExp.prototype.test.bind(
/^(data|aria)-[a-z_][a-z\d_.\-]*$/
),
Properties: {
/**
* Standard Properties
*/
accept: null,
accessKey: null,
action: null,
allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
allowTransparency: MUST_USE_ATTRIBUTE,
alt: null,
async: HAS_BOOLEAN_VALUE,
autoComplete: null,
// autoFocus is polyfilled/normalized by AutoFocusMixin
// autoFocus: HAS_BOOLEAN_VALUE,
autoPlay: HAS_BOOLEAN_VALUE,
cellPadding: null,
cellSpacing: null,
charSet: MUST_USE_ATTRIBUTE,
checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
// To set className on SVG elements, it's necessary to use .setAttribute;
// this works on HTML elements too in all browsers except IE8. Conveniently,
// IE8 doesn't support SVG and so we can simply use the attribute in
// browsers that support SVG and the property in browsers that don't,
// regardless of whether the element is HTML or SVG.
className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY,
cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
colSpan: null,
content: null,
contentEditable: null,
contextMenu: MUST_USE_ATTRIBUTE,
controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
coords: null,
crossOrigin: null,
data: null, // For `<object />` acts as `src`.
dateTime: MUST_USE_ATTRIBUTE,
defer: HAS_BOOLEAN_VALUE,
dir: null,
disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
download: HAS_OVERLOADED_BOOLEAN_VALUE,
draggable: null,
encType: null,
form: MUST_USE_ATTRIBUTE,
formNoValidate: HAS_BOOLEAN_VALUE,
frameBorder: MUST_USE_ATTRIBUTE,
height: MUST_USE_ATTRIBUTE,
hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
href: null,
hrefLang: null,
htmlFor: null,
httpEquiv: null,
icon: null,
id: MUST_USE_PROPERTY,
label: null,
lang: null,
list: null,
loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
max: null,
maxLength: MUST_USE_ATTRIBUTE,
media: MUST_USE_ATTRIBUTE,
mediaGroup: null,
method: null,
min: null,
multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
name: null,
noValidate: HAS_BOOLEAN_VALUE,
open: null,
pattern: null,
placeholder: null,
poster: null,
preload: null,
radioGroup: null,
readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
rel: null,
required: HAS_BOOLEAN_VALUE,
role: MUST_USE_ATTRIBUTE,
rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
rowSpan: null,
sandbox: null,
scope: null,
scrollLeft: MUST_USE_PROPERTY,
scrolling: null,
scrollTop: MUST_USE_PROPERTY,
seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
shape: null,
size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
sizes: MUST_USE_ATTRIBUTE,
span: HAS_POSITIVE_NUMERIC_VALUE,
spellCheck: null,
src: null,
srcDoc: MUST_USE_PROPERTY,
srcSet: MUST_USE_ATTRIBUTE,
start: HAS_NUMERIC_VALUE,
step: null,
style: null,
tabIndex: null,
target: null,
title: null,
type: null,
useMap: null,
value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
width: MUST_USE_ATTRIBUTE,
wmode: MUST_USE_ATTRIBUTE,
/**
* Non-standard Properties
*/
autoCapitalize: null, // Supported in Mobile Safari for keyboard hints
autoCorrect: null, // Supported in Mobile Safari for keyboard hints
itemProp: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, // Microdata: http://schema.org/docs/gs.html
itemType: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
property: null // Supports OG in meta tags
},
DOMAttributeNames: {
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv'
},
DOMPropertyNames: {
autoCapitalize: 'autocapitalize',
autoComplete: 'autocomplete',
autoCorrect: 'autocorrect',
autoFocus: 'autofocus',
autoPlay: 'autoplay',
encType: 'enctype',
hrefLang: 'hreflang',
radioGroup: 'radiogroup',
spellCheck: 'spellcheck',
srcDoc: 'srcdoc',
srcSet: 'srcset'
}
};
module.exports = HTMLDOMPropertyConfig;
},{"./DOMProperty":11,"./ExecutionEnvironment":22}],24:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule LinkedStateMixin
* @typechecks static-only
*/
"use strict";
var ReactLink = _dereq_("./ReactLink");
var ReactStateSetters = _dereq_("./ReactStateSetters");
/**
* A simple mixin around ReactLink.forState().
*/
var LinkedStateMixin = {
/**
* Create a ReactLink that's linked to part of this component's state. The
* ReactLink will have the current value of this.state[key] and will call
* setState() when a change is requested.
*
* @param {string} key state key to update. Note: you may want to use keyOf()
* if you're using Google Closure Compiler advanced mode.
* @return {ReactLink} ReactLink instance linking to the state.
*/
linkState: function(key) {
return new ReactLink(
this.state[key],
ReactStateSetters.createStateKeySetter(this, key)
);
}
};
module.exports = LinkedStateMixin;
},{"./ReactLink":65,"./ReactStateSetters":81}],25:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule LinkedValueUtils
* @typechecks static-only
*/
"use strict";
var ReactPropTypes = _dereq_("./ReactPropTypes");
var invariant = _dereq_("./invariant");
var hasReadOnlyValue = {
'button': true,
'checkbox': true,
'image': true,
'hidden': true,
'radio': true,
'reset': true,
'submit': true
};
function _assertSingleLink(input) {
("production" !== "development" ? invariant(
input.props.checkedLink == null || input.props.valueLink == null,
'Cannot provide a checkedLink and a valueLink. If you want to use ' +
'checkedLink, you probably don\'t want to use valueLink and vice versa.'
) : invariant(input.props.checkedLink == null || input.props.valueLink == null));
}
function _assertValueLink(input) {
_assertSingleLink(input);
("production" !== "development" ? invariant(
input.props.value == null && input.props.onChange == null,
'Cannot provide a valueLink and a value or onChange event. If you want ' +
'to use value or onChange, you probably don\'t want to use valueLink.'
) : invariant(input.props.value == null && input.props.onChange == null));
}
function _assertCheckedLink(input) {
_assertSingleLink(input);
("production" !== "development" ? invariant(
input.props.checked == null && input.props.onChange == null,
'Cannot provide a checkedLink and a checked property or onChange event. ' +
'If you want to use checked or onChange, you probably don\'t want to ' +
'use checkedLink'
) : invariant(input.props.checked == null && input.props.onChange == null));
}
/**
* @param {SyntheticEvent} e change event to handle
*/
function _handleLinkedValueChange(e) {
/*jshint validthis:true */
this.props.valueLink.requestChange(e.target.value);
}
/**
* @param {SyntheticEvent} e change event to handle
*/
function _handleLinkedCheckChange(e) {
/*jshint validthis:true */
this.props.checkedLink.requestChange(e.target.checked);
}
/**
* Provide a linked `value` attribute for controlled forms. You should not use
* this outside of the ReactDOM controlled form components.
*/
var LinkedValueUtils = {
Mixin: {
propTypes: {
value: function(props, propName, componentName) {
if (!props[propName] ||
hasReadOnlyValue[props.type] ||
props.onChange ||
props.readOnly ||
props.disabled) {
return;
}
return new Error(
'You provided a `value` prop to a form field without an ' +
'`onChange` handler. This will render a read-only field. If ' +
'the field should be mutable use `defaultValue`. Otherwise, ' +
'set either `onChange` or `readOnly`.'
);
},
checked: function(props, propName, componentName) {
if (!props[propName] ||
props.onChange ||
props.readOnly ||
props.disabled) {
return;
}
return new Error(
'You provided a `checked` prop to a form field without an ' +
'`onChange` handler. This will render a read-only field. If ' +
'the field should be mutable use `defaultChecked`. Otherwise, ' +
'set either `onChange` or `readOnly`.'
);
},
onChange: ReactPropTypes.func
}
},
/**
* @param {ReactComponent} input Form component
* @return {*} current value of the input either from value prop or link.
*/
getValue: function(input) {
if (input.props.valueLink) {
_assertValueLink(input);
return input.props.valueLink.value;
}
return input.props.value;
},
/**
* @param {ReactComponent} input Form component
* @return {*} current checked status of the input either from checked prop
* or link.
*/
getChecked: function(input) {
if (input.props.checkedLink) {
_assertCheckedLink(input);
return input.props.checkedLink.value;
}
return input.props.checked;
},
/**
* @param {ReactComponent} input Form component
* @return {function} change callback either from onChange prop or link.
*/
getOnChange: function(input) {
if (input.props.valueLink) {
_assertValueLink(input);
return _handleLinkedValueChange;
} else if (input.props.checkedLink) {
_assertCheckedLink(input);
return _handleLinkedCheckChange;
}
return input.props.onChange;
}
};
module.exports = LinkedValueUtils;
},{"./ReactPropTypes":75,"./invariant":134}],26:[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 LocalEventTrapMixin
*/
"use strict";
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var accumulate = _dereq_("./accumulate");
var forEachAccumulated = _dereq_("./forEachAccumulated");
var invariant = _dereq_("./invariant");
function remove(event) {
event.remove();
}
var LocalEventTrapMixin = {
trapBubbledEvent:function(topLevelType, handlerBaseName) {
("production" !== "development" ? invariant(this.isMounted(), 'Must be mounted to trap events') : invariant(this.isMounted()));
var listener = ReactBrowserEventEmitter.trapBubbledEvent(
topLevelType,
handlerBaseName,
this.getDOMNode()
);
this._localEventListeners = accumulate(this._localEventListeners, listener);
},
// trapCapturedEvent would look nearly identical. We don't implement that
// method because it isn't currently needed.
componentWillUnmount:function() {
if (this._localEventListeners) {
forEachAccumulated(this._localEventListeners, remove);
}
}
};
module.exports = LocalEventTrapMixin;
},{"./ReactBrowserEventEmitter":31,"./accumulate":106,"./forEachAccumulated":121,"./invariant":134}],27:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule MobileSafariClickEventPlugin
* @typechecks static-only
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var emptyFunction = _dereq_("./emptyFunction");
var topLevelTypes = EventConstants.topLevelTypes;
/**
* Mobile Safari does not fire properly bubble click events on non-interactive
* elements, which means delegated click listeners do not fire. The workaround
* for this bug involves attaching an empty click listener on the target node.
*
* This particular plugin works around the bug by attaching an empty click
* listener on `touchstart` (which does fire on every element).
*/
var MobileSafariClickEventPlugin = {
eventTypes: null,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
if (topLevelType === topLevelTypes.topTouchStart) {
var target = nativeEvent.target;
if (target && !target.onclick) {
target.onclick = emptyFunction;
}
}
}
};
module.exports = MobileSafariClickEventPlugin;
},{"./EventConstants":16,"./emptyFunction":116}],28:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule PooledClass
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* Static poolers. Several custom versions for each potential number of
* arguments. A completely generic pooler is easy to implement, but would
* require accessing the `arguments` object. In each of these, `this` refers to
* the Class itself, not an instance. If any others are needed, simply add them
* here, or in their own files.
*/
var oneArgumentPooler = function(copyFieldsFrom) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, copyFieldsFrom);
return instance;
} else {
return new Klass(copyFieldsFrom);
}
};
var twoArgumentPooler = function(a1, a2) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2);
return instance;
} else {
return new Klass(a1, a2);
}
};
var threeArgumentPooler = function(a1, a2, a3) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3);
return instance;
} else {
return new Klass(a1, a2, a3);
}
};
var fiveArgumentPooler = function(a1, a2, a3, a4, a5) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3, a4, a5);
return instance;
} else {
return new Klass(a1, a2, a3, a4, a5);
}
};
var standardReleaser = function(instance) {
var Klass = this;
("production" !== "development" ? invariant(
instance instanceof Klass,
'Trying to release an instance into a pool of a different type.'
) : invariant(instance instanceof Klass));
if (instance.destructor) {
instance.destructor();
}
if (Klass.instancePool.length < Klass.poolSize) {
Klass.instancePool.push(instance);
}
};
var DEFAULT_POOL_SIZE = 10;
var DEFAULT_POOLER = oneArgumentPooler;
/**
* Augments `CopyConstructor` to be a poolable class, augmenting only the class
* itself (statically) not adding any prototypical fields. Any CopyConstructor
* you give this may have a `poolSize` property, and will look for a
* prototypical `destructor` on instances (optional).
*
* @param {Function} CopyConstructor Constructor that can be used to reset.
* @param {Function} pooler Customizable pooler.
*/
var addPoolingTo = function(CopyConstructor, pooler) {
var NewKlass = CopyConstructor;
NewKlass.instancePool = [];
NewKlass.getPooled = pooler || DEFAULT_POOLER;
if (!NewKlass.poolSize) {
NewKlass.poolSize = DEFAULT_POOL_SIZE;
}
NewKlass.release = standardReleaser;
return NewKlass;
};
var PooledClass = {
addPoolingTo: addPoolingTo,
oneArgumentPooler: oneArgumentPooler,
twoArgumentPooler: twoArgumentPooler,
threeArgumentPooler: threeArgumentPooler,
fiveArgumentPooler: fiveArgumentPooler
};
module.exports = PooledClass;
},{"./invariant":134}],29:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule React
*/
"use strict";
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var EventPluginUtils = _dereq_("./EventPluginUtils");
var ReactChildren = _dereq_("./ReactChildren");
var ReactComponent = _dereq_("./ReactComponent");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactContext = _dereq_("./ReactContext");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var ReactDescriptor = _dereq_("./ReactDescriptor");
var ReactDOM = _dereq_("./ReactDOM");
var ReactDOMComponent = _dereq_("./ReactDOMComponent");
var ReactDefaultInjection = _dereq_("./ReactDefaultInjection");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactMount = _dereq_("./ReactMount");
var ReactMultiChild = _dereq_("./ReactMultiChild");
var ReactPerf = _dereq_("./ReactPerf");
var ReactPropTypes = _dereq_("./ReactPropTypes");
var ReactServerRendering = _dereq_("./ReactServerRendering");
var ReactTextComponent = _dereq_("./ReactTextComponent");
var onlyChild = _dereq_("./onlyChild");
var warning = _dereq_("./warning");
ReactDefaultInjection.inject();
// Specifying arguments isn't necessary since we just use apply anyway, but it
// makes it clear for those actually consuming this API.
function createDescriptor(type, props, children) {
var args = Array.prototype.slice.call(arguments, 1);
return type.apply(null, args);
}
if ("production" !== "development") {
var _warnedForDeprecation = false;
}
var React = {
Children: {
map: ReactChildren.map,
forEach: ReactChildren.forEach,
count: ReactChildren.count,
only: onlyChild
},
DOM: ReactDOM,
PropTypes: ReactPropTypes,
initializeTouchEvents: function(shouldUseTouch) {
EventPluginUtils.useTouchEvents = shouldUseTouch;
},
createClass: ReactCompositeComponent.createClass,
createDescriptor: function() {
if ("production" !== "development") {
("production" !== "development" ? warning(
_warnedForDeprecation,
'React.createDescriptor is deprecated and will be removed in the ' +
'next version of React. Use React.createElement instead.'
) : null);
_warnedForDeprecation = true;
}
return createDescriptor.apply(this, arguments);
},
createElement: createDescriptor,
constructAndRenderComponent: ReactMount.constructAndRenderComponent,
constructAndRenderComponentByID: ReactMount.constructAndRenderComponentByID,
renderComponent: ReactPerf.measure(
'React',
'renderComponent',
ReactMount.renderComponent
),
renderComponentToString: ReactServerRendering.renderComponentToString,
renderComponentToStaticMarkup:
ReactServerRendering.renderComponentToStaticMarkup,
unmountComponentAtNode: ReactMount.unmountComponentAtNode,
isValidClass: ReactDescriptor.isValidFactory,
isValidComponent: ReactDescriptor.isValidDescriptor,
withContext: ReactContext.withContext,
__internals: {
Component: ReactComponent,
CurrentOwner: ReactCurrentOwner,
DOMComponent: ReactDOMComponent,
DOMPropertyOperations: DOMPropertyOperations,
InstanceHandles: ReactInstanceHandles,
Mount: ReactMount,
MultiChild: ReactMultiChild,
TextComponent: ReactTextComponent
}
};
if ("production" !== "development") {
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
if (ExecutionEnvironment.canUseDOM &&
window.top === window.self &&
navigator.userAgent.indexOf('Chrome') > -1) {
console.debug(
'Download the React DevTools for a better development experience: ' +
'http://fb.me/react-devtools'
);
var expectedFeatures = [
// shims
Array.isArray,
Array.prototype.every,
Array.prototype.forEach,
Array.prototype.indexOf,
Array.prototype.map,
Date.now,
Function.prototype.bind,
Object.keys,
String.prototype.split,
String.prototype.trim,
// shams
Object.create,
Object.freeze
];
for (var i in expectedFeatures) {
if (!expectedFeatures[i]) {
console.error(
'One or more ES5 shim/shams expected by React are not available: ' +
'http://fb.me/react-warning-polyfills'
);
break;
}
}
}
}
// Version exists only in the open-source version of React, not in Facebook's
// internal version.
React.version = '0.11.2';
module.exports = React;
},{"./DOMPropertyOperations":12,"./EventPluginUtils":20,"./ExecutionEnvironment":22,"./ReactChildren":34,"./ReactComponent":35,"./ReactCompositeComponent":38,"./ReactContext":39,"./ReactCurrentOwner":40,"./ReactDOM":41,"./ReactDOMComponent":43,"./ReactDefaultInjection":53,"./ReactDescriptor":56,"./ReactInstanceHandles":64,"./ReactMount":67,"./ReactMultiChild":68,"./ReactPerf":71,"./ReactPropTypes":75,"./ReactServerRendering":79,"./ReactTextComponent":83,"./onlyChild":149,"./warning":158}],30:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactBrowserComponentMixin
*/
"use strict";
var ReactEmptyComponent = _dereq_("./ReactEmptyComponent");
var ReactMount = _dereq_("./ReactMount");
var invariant = _dereq_("./invariant");
var ReactBrowserComponentMixin = {
/**
* Returns the DOM node rendered by this component.
*
* @return {DOMElement} The root node of this component.
* @final
* @protected
*/
getDOMNode: function() {
("production" !== "development" ? invariant(
this.isMounted(),
'getDOMNode(): A component must be mounted to have a DOM node.'
) : invariant(this.isMounted()));
if (ReactEmptyComponent.isNullComponentID(this._rootNodeID)) {
return null;
}
return ReactMount.getNode(this._rootNodeID);
}
};
module.exports = ReactBrowserComponentMixin;
},{"./ReactEmptyComponent":58,"./ReactMount":67,"./invariant":134}],31:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule 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":16,"./EventPluginHub":18,"./EventPluginRegistry":19,"./ReactEventEmitterMixin":60,"./ViewportMetrics":105,"./isEventSupported":135,"./merge":144}],32:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @typechecks
* @providesModule ReactCSSTransitionGroup
*/
"use strict";
var React = _dereq_("./React");
var ReactTransitionGroup = _dereq_("./ReactTransitionGroup");
var ReactCSSTransitionGroupChild = _dereq_("./ReactCSSTransitionGroupChild");
var ReactCSSTransitionGroup = React.createClass({
displayName: 'ReactCSSTransitionGroup',
propTypes: {
transitionName: React.PropTypes.string.isRequired,
transitionEnter: React.PropTypes.bool,
transitionLeave: React.PropTypes.bool
},
getDefaultProps: function() {
return {
transitionEnter: true,
transitionLeave: true
};
},
_wrapChild: function(child) {
// We need to provide this childFactory so that
// ReactCSSTransitionGroupChild can receive updates to name, enter, and
// leave while it is leaving.
return ReactCSSTransitionGroupChild(
{
name: this.props.transitionName,
enter: this.props.transitionEnter,
leave: this.props.transitionLeave
},
child
);
},
render: function() {
return this.transferPropsTo(
ReactTransitionGroup(
{childFactory: this._wrapChild},
this.props.children
)
);
}
});
module.exports = ReactCSSTransitionGroup;
},{"./React":29,"./ReactCSSTransitionGroupChild":33,"./ReactTransitionGroup":86}],33:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @typechecks
* @providesModule ReactCSSTransitionGroupChild
*/
"use strict";
var React = _dereq_("./React");
var CSSCore = _dereq_("./CSSCore");
var ReactTransitionEvents = _dereq_("./ReactTransitionEvents");
var onlyChild = _dereq_("./onlyChild");
// We don't remove the element from the DOM until we receive an animationend or
// transitionend event. If the user screws up and forgets to add an animation
// their node will be stuck in the DOM forever, so we detect if an animation
// does not start and if it doesn't, we just call the end listener immediately.
var TICK = 17;
var NO_EVENT_TIMEOUT = 5000;
var noEventListener = null;
if ("production" !== "development") {
noEventListener = function() {
console.warn(
'transition(): tried to perform an animation without ' +
'an animationend or transitionend event after timeout (' +
NO_EVENT_TIMEOUT + 'ms). You should either disable this ' +
'transition in JS or add a CSS animation/transition.'
);
};
}
var ReactCSSTransitionGroupChild = React.createClass({
displayName: 'ReactCSSTransitionGroupChild',
transition: function(animationType, finishCallback) {
var node = this.getDOMNode();
var className = this.props.name + '-' + animationType;
var activeClassName = className + '-active';
var noEventTimeout = null;
var endListener = function() {
if ("production" !== "development") {
clearTimeout(noEventTimeout);
}
CSSCore.removeClass(node, className);
CSSCore.removeClass(node, activeClassName);
ReactTransitionEvents.removeEndEventListener(node, endListener);
// Usually this optional callback is used for informing an owner of
// a leave animation and telling it to remove the child.
finishCallback && finishCallback();
};
ReactTransitionEvents.addEndEventListener(node, endListener);
CSSCore.addClass(node, className);
// Need to do this to actually trigger a transition.
this.queueClass(activeClassName);
if ("production" !== "development") {
noEventTimeout = setTimeout(noEventListener, NO_EVENT_TIMEOUT);
}
},
queueClass: function(className) {
this.classNameQueue.push(className);
if (!this.timeout) {
this.timeout = setTimeout(this.flushClassNameQueue, TICK);
}
},
flushClassNameQueue: function() {
if (this.isMounted()) {
this.classNameQueue.forEach(
CSSCore.addClass.bind(CSSCore, this.getDOMNode())
);
}
this.classNameQueue.length = 0;
this.timeout = null;
},
componentWillMount: function() {
this.classNameQueue = [];
},
componentWillUnmount: function() {
if (this.timeout) {
clearTimeout(this.timeout);
}
},
componentWillEnter: function(done) {
if (this.props.enter) {
this.transition('enter', done);
} else {
done();
}
},
componentWillLeave: function(done) {
if (this.props.leave) {
this.transition('leave', done);
} else {
done();
}
},
render: function() {
return onlyChild(this.props.children);
}
});
module.exports = ReactCSSTransitionGroupChild;
},{"./CSSCore":3,"./React":29,"./ReactTransitionEvents":85,"./onlyChild":149}],34:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactChildren
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var traverseAllChildren = _dereq_("./traverseAllChildren");
var warning = _dereq_("./warning");
var twoArgumentPooler = PooledClass.twoArgumentPooler;
var threeArgumentPooler = PooledClass.threeArgumentPooler;
/**
* PooledClass representing the bookkeeping associated with performing a child
* traversal. Allows avoiding binding callbacks.
*
* @constructor ForEachBookKeeping
* @param {!function} forEachFunction Function to perform traversal with.
* @param {?*} forEachContext Context to perform context with.
*/
function ForEachBookKeeping(forEachFunction, forEachContext) {
this.forEachFunction = forEachFunction;
this.forEachContext = forEachContext;
}
PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler);
function forEachSingleChild(traverseContext, child, name, i) {
var forEachBookKeeping = traverseContext;
forEachBookKeeping.forEachFunction.call(
forEachBookKeeping.forEachContext, child, i);
}
/**
* Iterates through children that are typically specified as `props.children`.
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc.
* @param {*} forEachContext Context for forEachContext.
*/
function forEachChildren(children, forEachFunc, forEachContext) {
if (children == null) {
return children;
}
var traverseContext =
ForEachBookKeeping.getPooled(forEachFunc, forEachContext);
traverseAllChildren(children, forEachSingleChild, traverseContext);
ForEachBookKeeping.release(traverseContext);
}
/**
* PooledClass representing the bookkeeping associated with performing a child
* mapping. Allows avoiding binding callbacks.
*
* @constructor MapBookKeeping
* @param {!*} mapResult Object containing the ordered map of results.
* @param {!function} mapFunction Function to perform mapping with.
* @param {?*} mapContext Context to perform mapping with.
*/
function MapBookKeeping(mapResult, mapFunction, mapContext) {
this.mapResult = mapResult;
this.mapFunction = mapFunction;
this.mapContext = mapContext;
}
PooledClass.addPoolingTo(MapBookKeeping, threeArgumentPooler);
function mapSingleChildIntoContext(traverseContext, child, name, i) {
var mapBookKeeping = traverseContext;
var mapResult = mapBookKeeping.mapResult;
var keyUnique = !mapResult.hasOwnProperty(name);
("production" !== "development" ? warning(
keyUnique,
'ReactChildren.map(...): Encountered two children with the same key, ' +
'`%s`. Child keys must be unique; when two children share a key, only ' +
'the first child will be used.',
name
) : null);
if (keyUnique) {
var mappedChild =
mapBookKeeping.mapFunction.call(mapBookKeeping.mapContext, child, i);
mapResult[name] = mappedChild;
}
}
/**
* Maps children that are typically specified as `props.children`.
*
* The provided mapFunction(child, key, index) will be called for each
* leaf child.
*
* TODO: This may likely break any calls to `ReactChildren.map` that were
* previously relying on the fact that we guarded against null children.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} mapFunction.
* @param {*} mapContext Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var mapResult = {};
var traverseContext = MapBookKeeping.getPooled(mapResult, func, context);
traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);
MapBookKeeping.release(traverseContext);
return mapResult;
}
function forEachSingleChildDummy(traverseContext, child, name, i) {
return null;
}
/**
* Count the number of children that are typically specified as
* `props.children`.
*
* @param {?*} children Children tree container.
* @return {number} The number of children.
*/
function countChildren(children, context) {
return traverseAllChildren(children, forEachSingleChildDummy, null);
}
var ReactChildren = {
forEach: forEachChildren,
map: mapChildren,
count: countChildren
};
module.exports = ReactChildren;
},{"./PooledClass":28,"./traverseAllChildren":156,"./warning":158}],35:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactComponent
*/
"use strict";
var ReactDescriptor = _dereq_("./ReactDescriptor");
var ReactOwner = _dereq_("./ReactOwner");
var ReactUpdates = _dereq_("./ReactUpdates");
var invariant = _dereq_("./invariant");
var keyMirror = _dereq_("./keyMirror");
var merge = _dereq_("./merge");
/**
* Every React component is in one of these life cycles.
*/
var ComponentLifeCycle = keyMirror({
/**
* Mounted components have a DOM node representation and are capable of
* receiving new props.
*/
MOUNTED: null,
/**
* Unmounted components are inactive and cannot receive new props.
*/
UNMOUNTED: null
});
var injected = false;
/**
* Optionally injectable environment dependent cleanup hook. (server vs.
* browser etc). Example: A browser system caches DOM nodes based on component
* ID and must remove that cache entry when this instance is unmounted.
*
* @private
*/
var unmountIDFromEnvironment = null;
/**
* The "image" of a component tree, is the platform specific (typically
* serialized) data that represents a tree of lower level UI building blocks.
* On the web, this "image" is HTML markup which describes a construction of
* low level `div` and `span` nodes. Other platforms may have different
* encoding of this "image". This must be injected.
*
* @private
*/
var mountImageIntoNode = null;
/**
* Components are the basic units of composition in React.
*
* Every component accepts a set of keyed input parameters known as "props" that
* are initialized by the constructor. Once a component is mounted, the props
* can be mutated using `setProps` or `replaceProps`.
*
* Every component is capable of the following operations:
*
* `mountComponent`
* Initializes the component, renders markup, and registers event listeners.
*
* `receiveComponent`
* Updates the rendered DOM nodes to match the given component.
*
* `unmountComponent`
* Releases any resources allocated by this component.
*
* Components can also be "owned" by other components. Being owned by another
* component means being constructed by that component. This is different from
* being the child of a component, which means having a DOM representation that
* is a child of the DOM representation of that component.
*
* @class ReactComponent
*/
var ReactComponent = {
injection: {
injectEnvironment: function(ReactComponentEnvironment) {
("production" !== "development" ? invariant(
!injected,
'ReactComponent: injectEnvironment() can only be called once.'
) : invariant(!injected));
mountImageIntoNode = ReactComponentEnvironment.mountImageIntoNode;
unmountIDFromEnvironment =
ReactComponentEnvironment.unmountIDFromEnvironment;
ReactComponent.BackendIDOperations =
ReactComponentEnvironment.BackendIDOperations;
injected = true;
}
},
/**
* @internal
*/
LifeCycle: ComponentLifeCycle,
/**
* Injected module that provides ability to mutate individual properties.
* Injected into the base class because many different subclasses need access
* to this.
*
* @internal
*/
BackendIDOperations: null,
/**
* Base functionality for every ReactComponent constructor. Mixed into the
* `ReactComponent` prototype, but exposed statically for easy access.
*
* @lends {ReactComponent.prototype}
*/
Mixin: {
/**
* Checks whether or not this component is mounted.
*
* @return {boolean} True if mounted, false otherwise.
* @final
* @protected
*/
isMounted: function() {
return this._lifeCycleState === ComponentLifeCycle.MOUNTED;
},
/**
* Sets a subset of the props.
*
* @param {object} partialProps Subset of the next props.
* @param {?function} callback Called after props are updated.
* @final
* @public
*/
setProps: function(partialProps, callback) {
// Merge with the pending descriptor if it exists, otherwise with existing
// descriptor props.
var descriptor = this._pendingDescriptor || this._descriptor;
this.replaceProps(
merge(descriptor.props, partialProps),
callback
);
},
/**
* Replaces all of the props.
*
* @param {object} props New props.
* @param {?function} callback Called after props are updated.
* @final
* @public
*/
replaceProps: function(props, callback) {
("production" !== "development" ? invariant(
this.isMounted(),
'replaceProps(...): Can only update a mounted component.'
) : invariant(this.isMounted()));
("production" !== "development" ? invariant(
this._mountDepth === 0,
'replaceProps(...): You called `setProps` or `replaceProps` on a ' +
'component with a parent. This is an anti-pattern since props will ' +
'get reactively updated when rendered. Instead, change the owner\'s ' +
'`render` method to pass the correct value as props to the component ' +
'where it is created.'
) : invariant(this._mountDepth === 0));
// This is a deoptimized path. We optimize for always having a descriptor.
// This creates an extra internal descriptor.
this._pendingDescriptor = ReactDescriptor.cloneAndReplaceProps(
this._pendingDescriptor || this._descriptor,
props
);
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* Schedule a partial update to the props. Only used for internal testing.
*
* @param {object} partialProps Subset of the next props.
* @param {?function} callback Called after props are updated.
* @final
* @internal
*/
_setPropsInternal: function(partialProps, callback) {
// This is a deoptimized path. We optimize for always having a descriptor.
// This creates an extra internal descriptor.
var descriptor = this._pendingDescriptor || this._descriptor;
this._pendingDescriptor = ReactDescriptor.cloneAndReplaceProps(
descriptor,
merge(descriptor.props, partialProps)
);
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* Base constructor for all React components.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.construct.call(this, ...)`.
*
* @param {ReactDescriptor} descriptor
* @internal
*/
construct: function(descriptor) {
// This is the public exposed props object after it has been processed
// with default props. The descriptor's props represents the true internal
// state of the props.
this.props = descriptor.props;
// Record the component responsible for creating this component.
// This is accessible through the descriptor but we maintain an extra
// field for compatibility with devtools and as a way to make an
// incremental update. TODO: Consider deprecating this field.
this._owner = descriptor._owner;
// All components start unmounted.
this._lifeCycleState = ComponentLifeCycle.UNMOUNTED;
// See ReactUpdates.
this._pendingCallbacks = null;
// We keep the old descriptor and a reference to the pending descriptor
// to track updates.
this._descriptor = descriptor;
this._pendingDescriptor = null;
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* NOTE: This does not insert any nodes into the DOM.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.mountComponent.call(this, ...)`.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {number} mountDepth number of components in the owner hierarchy.
* @return {?string} Rendered markup to be inserted into the DOM.
* @internal
*/
mountComponent: function(rootID, transaction, mountDepth) {
("production" !== "development" ? invariant(
!this.isMounted(),
'mountComponent(%s, ...): Can only mount an unmounted component. ' +
'Make sure to avoid storing components between renders or reusing a ' +
'single component instance in multiple places.',
rootID
) : invariant(!this.isMounted()));
var props = this._descriptor.props;
if (props.ref != null) {
var owner = this._descriptor._owner;
ReactOwner.addComponentAsRefTo(this, props.ref, owner);
}
this._rootNodeID = rootID;
this._lifeCycleState = ComponentLifeCycle.MOUNTED;
this._mountDepth = mountDepth;
// Effectively: return '';
},
/**
* Releases any resources allocated by `mountComponent`.
*
* NOTE: This does not remove any nodes from the DOM.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.unmountComponent.call(this)`.
*
* @internal
*/
unmountComponent: function() {
("production" !== "development" ? invariant(
this.isMounted(),
'unmountComponent(): Can only unmount a mounted component.'
) : invariant(this.isMounted()));
var props = this.props;
if (props.ref != null) {
ReactOwner.removeComponentAsRefFrom(this, props.ref, this._owner);
}
unmountIDFromEnvironment(this._rootNodeID);
this._rootNodeID = null;
this._lifeCycleState = ComponentLifeCycle.UNMOUNTED;
},
/**
* Given a new instance of this component, updates the rendered DOM nodes
* as if that instance was rendered instead.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.receiveComponent.call(this, ...)`.
*
* @param {object} nextComponent Next set of properties.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveComponent: function(nextDescriptor, transaction) {
("production" !== "development" ? invariant(
this.isMounted(),
'receiveComponent(...): Can only update a mounted component.'
) : invariant(this.isMounted()));
this._pendingDescriptor = nextDescriptor;
this.performUpdateIfNecessary(transaction);
},
/**
* If `_pendingDescriptor` is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function(transaction) {
if (this._pendingDescriptor == null) {
return;
}
var prevDescriptor = this._descriptor;
var nextDescriptor = this._pendingDescriptor;
this._descriptor = nextDescriptor;
this.props = nextDescriptor.props;
this._owner = nextDescriptor._owner;
this._pendingDescriptor = null;
this.updateComponent(transaction, prevDescriptor);
},
/**
* Updates the component's currently mounted representation.
*
* @param {ReactReconcileTransaction} transaction
* @param {object} prevDescriptor
* @internal
*/
updateComponent: function(transaction, prevDescriptor) {
var nextDescriptor = this._descriptor;
// If either the owner or a `ref` has changed, make sure the newest owner
// has stored a reference to `this`, and the previous owner (if different)
// has forgotten the reference to `this`. We use the descriptor instead
// of the public this.props because the post processing cannot determine
// a ref. The ref conceptually lives on the descriptor.
// TODO: Should this even be possible? The owner cannot change because
// it's forbidden by shouldUpdateReactComponent. The ref can change
// if you swap the keys of but not the refs. Reconsider where this check
// is made. It probably belongs where the key checking and
// instantiateReactComponent is done.
if (nextDescriptor._owner !== prevDescriptor._owner ||
nextDescriptor.props.ref !== prevDescriptor.props.ref) {
if (prevDescriptor.props.ref != null) {
ReactOwner.removeComponentAsRefFrom(
this, prevDescriptor.props.ref, prevDescriptor._owner
);
}
// Correct, even if the owner is the same, and only the ref has changed.
if (nextDescriptor.props.ref != null) {
ReactOwner.addComponentAsRefTo(
this,
nextDescriptor.props.ref,
nextDescriptor._owner
);
}
}
},
/**
* Mounts this component and inserts it into the DOM.
*
* @param {string} rootID DOM ID of the root node.
* @param {DOMElement} container DOM element to mount into.
* @param {boolean} shouldReuseMarkup If true, do not insert markup
* @final
* @internal
* @see {ReactMount.renderComponent}
*/
mountComponentIntoNode: function(rootID, container, shouldReuseMarkup) {
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled();
transaction.perform(
this._mountComponentIntoNode,
this,
rootID,
container,
transaction,
shouldReuseMarkup
);
ReactUpdates.ReactReconcileTransaction.release(transaction);
},
/**
* @param {string} rootID DOM ID of the root node.
* @param {DOMElement} container DOM element to mount into.
* @param {ReactReconcileTransaction} transaction
* @param {boolean} shouldReuseMarkup If true, do not insert markup
* @final
* @private
*/
_mountComponentIntoNode: function(
rootID,
container,
transaction,
shouldReuseMarkup) {
var markup = this.mountComponent(rootID, transaction, 0);
mountImageIntoNode(markup, container, shouldReuseMarkup);
},
/**
* Checks if this component is owned by the supplied `owner` component.
*
* @param {ReactComponent} owner Component to check.
* @return {boolean} True if `owners` owns this component.
* @final
* @internal
*/
isOwnedBy: function(owner) {
return this._owner === owner;
},
/**
* Gets another component, that shares the same owner as this one, by ref.
*
* @param {string} ref of a sibling Component.
* @return {?ReactComponent} the actual sibling Component.
* @final
* @internal
*/
getSiblingByRef: function(ref) {
var owner = this._owner;
if (!owner || !owner.refs) {
return null;
}
return owner.refs[ref];
}
}
};
module.exports = ReactComponent;
},{"./ReactDescriptor":56,"./ReactOwner":70,"./ReactUpdates":87,"./invariant":134,"./keyMirror":140,"./merge":144}],36:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactComponentBrowserEnvironment
*/
/*jslint evil: true */
"use strict";
var ReactDOMIDOperations = _dereq_("./ReactDOMIDOperations");
var ReactMarkupChecksum = _dereq_("./ReactMarkupChecksum");
var ReactMount = _dereq_("./ReactMount");
var ReactPerf = _dereq_("./ReactPerf");
var ReactReconcileTransaction = _dereq_("./ReactReconcileTransaction");
var getReactRootElementInContainer = _dereq_("./getReactRootElementInContainer");
var invariant = _dereq_("./invariant");
var setInnerHTML = _dereq_("./setInnerHTML");
var ELEMENT_NODE_TYPE = 1;
var DOC_NODE_TYPE = 9;
/**
* Abstracts away all functionality of `ReactComponent` requires knowledge of
* the browser context.
*/
var ReactComponentBrowserEnvironment = {
ReactReconcileTransaction: ReactReconcileTransaction,
BackendIDOperations: ReactDOMIDOperations,
/**
* If a particular environment requires that some resources be cleaned up,
* specify this in the injected Mixin. In the DOM, we would likely want to
* purge any cached node ID lookups.
*
* @private
*/
unmountIDFromEnvironment: function(rootNodeID) {
ReactMount.purgeID(rootNodeID);
},
/**
* @param {string} markup Markup string to place into the DOM Element.
* @param {DOMElement} container DOM Element to insert markup into.
* @param {boolean} shouldReuseMarkup Should reuse the existing markup in the
* container if possible.
*/
mountImageIntoNode: ReactPerf.measure(
'ReactComponentBrowserEnvironment',
'mountImageIntoNode',
function(markup, container, shouldReuseMarkup) {
("production" !== "development" ? invariant(
container && (
container.nodeType === ELEMENT_NODE_TYPE ||
container.nodeType === DOC_NODE_TYPE
),
'mountComponentIntoNode(...): Target container is not valid.'
) : invariant(container && (
container.nodeType === ELEMENT_NODE_TYPE ||
container.nodeType === DOC_NODE_TYPE
)));
if (shouldReuseMarkup) {
if (ReactMarkupChecksum.canReuseMarkup(
markup,
getReactRootElementInContainer(container))) {
return;
} else {
("production" !== "development" ? invariant(
container.nodeType !== DOC_NODE_TYPE,
'You\'re trying to render a component to the document using ' +
'server rendering but the checksum was invalid. This usually ' +
'means you rendered a different component type or props on ' +
'the client from the one on the server, or your render() ' +
'methods are impure. React cannot handle this case due to ' +
'cross-browser quirks by rendering at the document root. You ' +
'should look for environment dependent code in your components ' +
'and ensure the props are the same client and server side.'
) : invariant(container.nodeType !== DOC_NODE_TYPE));
if ("production" !== "development") {
console.warn(
'React attempted to use reuse markup in a container but the ' +
'checksum was invalid. This generally means that you are ' +
'using server rendering and the markup generated on the ' +
'server was not what the client was expecting. React injected ' +
'new markup to compensate which works but you have lost many ' +
'of the benefits of server rendering. Instead, figure out ' +
'why the markup being generated is different on the client ' +
'or server.'
);
}
}
}
("production" !== "development" ? invariant(
container.nodeType !== DOC_NODE_TYPE,
'You\'re trying to render a component to the document but ' +
'you didn\'t use server rendering. We can\'t do this ' +
'without using server rendering due to cross-browser quirks. ' +
'See renderComponentToString() for server rendering.'
) : invariant(container.nodeType !== DOC_NODE_TYPE));
setInnerHTML(container, markup);
}
)
};
module.exports = ReactComponentBrowserEnvironment;
},{"./ReactDOMIDOperations":45,"./ReactMarkupChecksum":66,"./ReactMount":67,"./ReactPerf":71,"./ReactReconcileTransaction":77,"./getReactRootElementInContainer":128,"./invariant":134,"./setInnerHTML":152}],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 ReactComponentWithPureRenderMixin
*/
"use strict";
var shallowEqual = _dereq_("./shallowEqual");
/**
* If your React component's render function is "pure", e.g. it will render the
* same result given the same props and state, provide this Mixin for a
* considerable performance boost.
*
* Most React components have pure render functions.
*
* Example:
*
* var ReactComponentWithPureRenderMixin =
* require('ReactComponentWithPureRenderMixin');
* React.createClass({
* mixins: [ReactComponentWithPureRenderMixin],
*
* render: function() {
* return <div className={this.props.className}>foo</div>;
* }
* });
*
* Note: This only checks shallow equality for props and state. If these contain
* complex data structures this mixin may have false-negatives for deeper
* differences. Only mixin to components which have simple props and state, or
* use `forceUpdate()` when you know deep data structures have changed.
*/
var ReactComponentWithPureRenderMixin = {
shouldComponentUpdate: function(nextProps, nextState) {
return !shallowEqual(this.props, nextProps) ||
!shallowEqual(this.state, nextState);
}
};
module.exports = ReactComponentWithPureRenderMixin;
},{"./shallowEqual":153}],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 ReactCompositeComponent
*/
"use strict";
var ReactComponent = _dereq_("./ReactComponent");
var ReactContext = _dereq_("./ReactContext");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var ReactDescriptor = _dereq_("./ReactDescriptor");
var ReactDescriptorValidator = _dereq_("./ReactDescriptorValidator");
var ReactEmptyComponent = _dereq_("./ReactEmptyComponent");
var ReactErrorUtils = _dereq_("./ReactErrorUtils");
var ReactOwner = _dereq_("./ReactOwner");
var ReactPerf = _dereq_("./ReactPerf");
var ReactPropTransferer = _dereq_("./ReactPropTransferer");
var ReactPropTypeLocations = _dereq_("./ReactPropTypeLocations");
var ReactPropTypeLocationNames = _dereq_("./ReactPropTypeLocationNames");
var ReactUpdates = _dereq_("./ReactUpdates");
var instantiateReactComponent = _dereq_("./instantiateReactComponent");
var invariant = _dereq_("./invariant");
var keyMirror = _dereq_("./keyMirror");
var merge = _dereq_("./merge");
var mixInto = _dereq_("./mixInto");
var monitorCodeUse = _dereq_("./monitorCodeUse");
var mapObject = _dereq_("./mapObject");
var shouldUpdateReactComponent = _dereq_("./shouldUpdateReactComponent");
var warning = _dereq_("./warning");
/**
* Policies that describe methods in `ReactCompositeComponentInterface`.
*/
var SpecPolicy = keyMirror({
/**
* These methods may be defined only once by the class specification or mixin.
*/
DEFINE_ONCE: null,
/**
* These methods may be defined by both the class specification and mixins.
* Subsequent definitions will be chained. These methods must return void.
*/
DEFINE_MANY: null,
/**
* These methods are overriding the base ReactCompositeComponent class.
*/
OVERRIDE_BASE: null,
/**
* These methods are similar to DEFINE_MANY, except we assume they return
* objects. We try to merge the keys of the return values of all the mixed in
* functions. If there is a key conflict we throw.
*/
DEFINE_MANY_MERGED: null
});
var injectedMixins = [];
/**
* Composite components are higher-level components that compose other composite
* or native components.
*
* To create a new type of `ReactCompositeComponent`, pass a specification of
* your new class to `React.createClass`. The only requirement of your class
* specification is that you implement a `render` method.
*
* var MyComponent = React.createClass({
* render: function() {
* return <div>Hello World</div>;
* }
* });
*
* The class specification supports a specific protocol of methods that have
* special meaning (e.g. `render`). See `ReactCompositeComponentInterface` for
* more the comprehensive protocol. Any other properties and methods in the
* class specification will available on the prototype.
*
* @interface ReactCompositeComponentInterface
* @internal
*/
var ReactCompositeComponentInterface = {
/**
* An array of Mixin objects to include when defining your component.
*
* @type {array}
* @optional
*/
mixins: SpecPolicy.DEFINE_MANY,
/**
* An object containing properties and methods that should be defined on
* the component's constructor instead of its prototype (static methods).
*
* @type {object}
* @optional
*/
statics: SpecPolicy.DEFINE_MANY,
/**
* Definition of prop types for this component.
*
* @type {object}
* @optional
*/
propTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types for this component.
*
* @type {object}
* @optional
*/
contextTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types this component sets for its children.
*
* @type {object}
* @optional
*/
childContextTypes: SpecPolicy.DEFINE_MANY,
// ==== Definition methods ====
/**
* Invoked when the component is mounted. Values in the mapping will be set on
* `this.props` if that prop is not specified (i.e. using an `in` check).
*
* This method is invoked before `getInitialState` and therefore cannot rely
* on `this.state` or use `this.setState`.
*
* @return {object}
* @optional
*/
getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED,
/**
* Invoked once before the component is mounted. The return value will be used
* as the initial value of `this.state`.
*
* getInitialState: function() {
* return {
* isOn: false,
* fooBaz: new BazFoo()
* }
* }
*
* @return {object}
* @optional
*/
getInitialState: SpecPolicy.DEFINE_MANY_MERGED,
/**
* @return {object}
* @optional
*/
getChildContext: SpecPolicy.DEFINE_MANY_MERGED,
/**
* Uses props from `this.props` and state from `this.state` to render the
* structure of the component.
*
* No guarantees are made about when or how often this method is invoked, so
* it must not have side effects.
*
* render: function() {
* var name = this.props.name;
* return <div>Hello, {name}!</div>;
* }
*
* @return {ReactComponent}
* @nosideeffects
* @required
*/
render: SpecPolicy.DEFINE_ONCE,
// ==== Delegate methods ====
/**
* Invoked when the component is initially created and about to be mounted.
* This may have side effects, but any external subscriptions or data created
* by this method must be cleaned up in `componentWillUnmount`.
*
* @optional
*/
componentWillMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component has been mounted and has a DOM representation.
* However, there is no guarantee that the DOM node is in the document.
*
* Use this as an opportunity to operate on the DOM when the component has
* been mounted (initialized and rendered) for the first time.
*
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked before the component receives new props.
*
* Use this as an opportunity to react to a prop transition by updating the
* state using `this.setState`. Current props are accessed via `this.props`.
*
* componentWillReceiveProps: function(nextProps, nextContext) {
* this.setState({
* likesIncreasing: nextProps.likeCount > this.props.likeCount
* });
* }
*
* NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
* transition may cause a state change, but the opposite is not true. If you
* need it, you are probably looking for `componentWillUpdate`.
*
* @param {object} nextProps
* @optional
*/
componentWillReceiveProps: SpecPolicy.DEFINE_MANY,
/**
* Invoked while deciding if the component should be updated as a result of
* receiving new props, state and/or context.
*
* Use this as an opportunity to `return false` when you're certain that the
* transition to the new props/state/context will not require a component
* update.
*
* shouldComponentUpdate: function(nextProps, nextState, nextContext) {
* return !equal(nextProps, this.props) ||
* !equal(nextState, this.state) ||
* !equal(nextContext, this.context);
* }
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @return {boolean} True if the component should update.
* @optional
*/
shouldComponentUpdate: SpecPolicy.DEFINE_ONCE,
/**
* Invoked when the component is about to update due to a transition from
* `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`
* and `nextContext`.
*
* Use this as an opportunity to perform preparation before an update occurs.
*
* NOTE: You **cannot** use `this.setState()` in this method.
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @param {ReactReconcileTransaction} transaction
* @optional
*/
componentWillUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component's DOM representation has been updated.
*
* Use this as an opportunity to operate on the DOM when the component has
* been updated.
*
* @param {object} prevProps
* @param {?object} prevState
* @param {?object} prevContext
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component is about to be removed from its parent and have
* its DOM representation destroyed.
*
* Use this as an opportunity to deallocate any external resources.
*
* NOTE: There is no `componentDidUnmount` since your component will have been
* destroyed by that point.
*
* @optional
*/
componentWillUnmount: SpecPolicy.DEFINE_MANY,
// ==== Advanced methods ====
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @internal
* @overridable
*/
updateComponent: SpecPolicy.OVERRIDE_BASE
};
/**
* Mapping from class specification keys to special processing functions.
*
* Although these are declared like instance properties in the specification
* when defining classes using `React.createClass`, they are actually static
* and are accessible on the constructor instead of the prototype. Despite
* being static, they must be defined outside of the "statics" key under
* which all other static methods are defined.
*/
var RESERVED_SPEC_KEYS = {
displayName: function(Constructor, displayName) {
Constructor.displayName = displayName;
},
mixins: function(Constructor, mixins) {
if (mixins) {
for (var i = 0; i < mixins.length; i++) {
mixSpecIntoComponent(Constructor, mixins[i]);
}
}
},
childContextTypes: function(Constructor, childContextTypes) {
validateTypeDef(
Constructor,
childContextTypes,
ReactPropTypeLocations.childContext
);
Constructor.childContextTypes = merge(
Constructor.childContextTypes,
childContextTypes
);
},
contextTypes: function(Constructor, contextTypes) {
validateTypeDef(
Constructor,
contextTypes,
ReactPropTypeLocations.context
);
Constructor.contextTypes = merge(Constructor.contextTypes, contextTypes);
},
/**
* Special case getDefaultProps which should move into statics but requires
* automatic merging.
*/
getDefaultProps: function(Constructor, getDefaultProps) {
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps = createMergedResultFunction(
Constructor.getDefaultProps,
getDefaultProps
);
} else {
Constructor.getDefaultProps = getDefaultProps;
}
},
propTypes: function(Constructor, propTypes) {
validateTypeDef(
Constructor,
propTypes,
ReactPropTypeLocations.prop
);
Constructor.propTypes = merge(Constructor.propTypes, propTypes);
},
statics: function(Constructor, statics) {
mixStaticSpecIntoComponent(Constructor, statics);
}
};
function getDeclarationErrorAddendum(component) {
var owner = component._owner || null;
if (owner && owner.constructor && owner.constructor.displayName) {
return ' Check the render method of `' + owner.constructor.displayName +
'`.';
}
return '';
}
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) {
if (typeDef.hasOwnProperty(propName)) {
("production" !== "development" ? invariant(
typeof typeDef[propName] == 'function',
'%s: %s type `%s` is invalid; it must be a function, usually from ' +
'React.PropTypes.',
Constructor.displayName || 'ReactCompositeComponent',
ReactPropTypeLocationNames[location],
propName
) : invariant(typeof typeDef[propName] == 'function'));
}
}
}
function validateMethodOverride(proto, name) {
var specPolicy = ReactCompositeComponentInterface.hasOwnProperty(name) ?
ReactCompositeComponentInterface[name] :
null;
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactCompositeComponentMixin.hasOwnProperty(name)) {
("production" !== "development" ? invariant(
specPolicy === SpecPolicy.OVERRIDE_BASE,
'ReactCompositeComponentInterface: You are attempting to override ' +
'`%s` from your class specification. Ensure that your method names ' +
'do not overlap with React methods.',
name
) : invariant(specPolicy === SpecPolicy.OVERRIDE_BASE));
}
// Disallow defining methods more than once unless explicitly allowed.
if (proto.hasOwnProperty(name)) {
("production" !== "development" ? invariant(
specPolicy === SpecPolicy.DEFINE_MANY ||
specPolicy === SpecPolicy.DEFINE_MANY_MERGED,
'ReactCompositeComponentInterface: You are attempting to define ' +
'`%s` on your component more than once. This conflict may be due ' +
'to a mixin.',
name
) : invariant(specPolicy === SpecPolicy.DEFINE_MANY ||
specPolicy === SpecPolicy.DEFINE_MANY_MERGED));
}
}
function validateLifeCycleOnReplaceState(instance) {
var compositeLifeCycleState = instance._compositeLifeCycleState;
("production" !== "development" ? invariant(
instance.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING,
'replaceState(...): Can only update a mounted or mounting component.'
) : invariant(instance.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING));
("production" !== "development" ? invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE,
'replaceState(...): Cannot update during an existing state transition ' +
'(such as within `render`). This could potentially cause an infinite ' +
'loop so it is forbidden.'
) : invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE));
("production" !== "development" ? invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING,
'replaceState(...): Cannot update while unmounting component. This ' +
'usually means you called setState() on an unmounted component.'
) : invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING));
}
/**
* Custom version of `mixInto` which handles policy validation and reserved
* specification keys when building `ReactCompositeComponent` classses.
*/
function mixSpecIntoComponent(Constructor, spec) {
("production" !== "development" ? invariant(
!ReactDescriptor.isValidFactory(spec),
'ReactCompositeComponent: You\'re attempting to ' +
'use a component class as a mixin. Instead, just use a regular object.'
) : invariant(!ReactDescriptor.isValidFactory(spec)));
("production" !== "development" ? invariant(
!ReactDescriptor.isValidDescriptor(spec),
'ReactCompositeComponent: You\'re attempting to ' +
'use a component as a mixin. Instead, just use a regular object.'
) : invariant(!ReactDescriptor.isValidDescriptor(spec)));
var proto = Constructor.prototype;
for (var name in spec) {
var property = spec[name];
if (!spec.hasOwnProperty(name)) {
continue;
}
validateMethodOverride(proto, name);
if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
RESERVED_SPEC_KEYS[name](Constructor, property);
} else {
// Setup methods on prototype:
// The following member methods should not be automatically bound:
// 1. Expected ReactCompositeComponent methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isCompositeComponentMethod =
ReactCompositeComponentInterface.hasOwnProperty(name);
var isAlreadyDefined = proto.hasOwnProperty(name);
var markedDontBind = property && property.__reactDontBind;
var isFunction = typeof property === 'function';
var shouldAutoBind =
isFunction &&
!isCompositeComponentMethod &&
!isAlreadyDefined &&
!markedDontBind;
if (shouldAutoBind) {
if (!proto.__reactAutoBindMap) {
proto.__reactAutoBindMap = {};
}
proto.__reactAutoBindMap[name] = property;
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactCompositeComponentInterface[name];
// These cases should already be caught by validateMethodOverride
("production" !== "development" ? invariant(
isCompositeComponentMethod && (
specPolicy === SpecPolicy.DEFINE_MANY_MERGED ||
specPolicy === SpecPolicy.DEFINE_MANY
),
'ReactCompositeComponent: Unexpected spec policy %s for key %s ' +
'when mixing in component specs.',
specPolicy,
name
) : invariant(isCompositeComponentMethod && (
specPolicy === SpecPolicy.DEFINE_MANY_MERGED ||
specPolicy === SpecPolicy.DEFINE_MANY
)));
// For methods which are defined more than once, call the existing
// methods before calling the new property, merging if appropriate.
if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) {
proto[name] = createMergedResultFunction(proto[name], property);
} else if (specPolicy === SpecPolicy.DEFINE_MANY) {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
if ("production" !== "development") {
// Add verbose displayName to the function, which helps when looking
// at profiling tools.
if (typeof property === 'function' && spec.displayName) {
proto[name].displayName = spec.displayName + '_' + name;
}
}
}
}
}
}
}
function mixStaticSpecIntoComponent(Constructor, statics) {
if (!statics) {
return;
}
for (var name in statics) {
var property = statics[name];
if (!statics.hasOwnProperty(name)) {
continue;
}
var isInherited = name in Constructor;
var result = property;
if (isInherited) {
var existingProperty = Constructor[name];
var existingType = typeof existingProperty;
var propertyType = typeof property;
("production" !== "development" ? invariant(
existingType === 'function' && propertyType === 'function',
'ReactCompositeComponent: You are attempting to define ' +
'`%s` on your component more than once, but that is only supported ' +
'for functions, which are chained together. This conflict may be ' +
'due to a mixin.',
name
) : invariant(existingType === 'function' && propertyType === 'function'));
result = createChainedFunction(existingProperty, property);
}
Constructor[name] = result;
}
}
/**
* Merge two objects, but throw if both contain the same key.
*
* @param {object} one The first object, which is mutated.
* @param {object} two The second object
* @return {object} one after it has been mutated to contain everything in two.
*/
function mergeObjectsWithNoDuplicateKeys(one, two) {
("production" !== "development" ? invariant(
one && two && typeof one === 'object' && typeof two === 'object',
'mergeObjectsWithNoDuplicateKeys(): Cannot merge non-objects'
) : invariant(one && two && typeof one === 'object' && typeof two === 'object'));
mapObject(two, function(value, key) {
("production" !== "development" ? invariant(
one[key] === undefined,
'mergeObjectsWithNoDuplicateKeys(): ' +
'Tried to merge two objects with the same key: %s',
key
) : invariant(one[key] === undefined));
one[key] = value;
});
return one;
}
/**
* Creates a function that invokes two functions and merges their return values.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createMergedResultFunction(one, two) {
return function mergedResult() {
var a = one.apply(this, arguments);
var b = two.apply(this, arguments);
if (a == null) {
return b;
} else if (b == null) {
return a;
}
return mergeObjectsWithNoDuplicateKeys(a, b);
};
}
/**
* Creates a function that invokes two functions and ignores their return vales.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createChainedFunction(one, two) {
return function chainedFunction() {
one.apply(this, arguments);
two.apply(this, arguments);
};
}
/**
* `ReactCompositeComponent` maintains an auxiliary life cycle state in
* `this._compositeLifeCycleState` (which can be null).
*
* This is different from the life cycle state maintained by `ReactComponent` in
* `this._lifeCycleState`. The following diagram shows how the states overlap in
* time. There are times when the CompositeLifeCycle is null - at those times it
* is only meaningful to look at ComponentLifeCycle alone.
*
* Top Row: ReactComponent.ComponentLifeCycle
* Low Row: ReactComponent.CompositeLifeCycle
*
* +-------+------------------------------------------------------+--------+
* | UN | MOUNTED | UN |
* |MOUNTED| | MOUNTED|
* +-------+------------------------------------------------------+--------+
* | ^--------+ +------+ +------+ +------+ +--------^ |
* | | | | | | | | | | | |
* | 0--|MOUNTING|-0-|RECEIV|-0-|RECEIV|-0-|RECEIV|-0-| UN |--->0 |
* | | | |PROPS | | PROPS| | STATE| |MOUNTING| |
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | +--------+ +------+ +------+ +------+ +--------+ |
* | | | |
* +-------+------------------------------------------------------+--------+
*/
var CompositeLifeCycle = keyMirror({
/**
* Components in the process of being mounted respond to state changes
* differently.
*/
MOUNTING: null,
/**
* Components in the process of being unmounted are guarded against state
* changes.
*/
UNMOUNTING: null,
/**
* Components that are mounted and receiving new props respond to state
* changes differently.
*/
RECEIVING_PROPS: null,
/**
* Components that are mounted and receiving new state are guarded against
* additional state changes.
*/
RECEIVING_STATE: null
});
/**
* @lends {ReactCompositeComponent.prototype}
*/
var ReactCompositeComponentMixin = {
/**
* Base constructor for all composite component.
*
* @param {ReactDescriptor} descriptor
* @final
* @internal
*/
construct: function(descriptor) {
// Children can be either an array or more than one argument
ReactComponent.Mixin.construct.apply(this, arguments);
ReactOwner.Mixin.construct.apply(this, arguments);
this.state = null;
this._pendingState = null;
// This is the public post-processed context. The real context and pending
// context lives on the descriptor.
this.context = null;
this._compositeLifeCycleState = null;
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function() {
return ReactComponent.Mixin.isMounted.call(this) &&
this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING;
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {number} mountDepth number of components in the owner hierarchy
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: ReactPerf.measure(
'ReactCompositeComponent',
'mountComponent',
function(rootID, transaction, mountDepth) {
ReactComponent.Mixin.mountComponent.call(
this,
rootID,
transaction,
mountDepth
);
this._compositeLifeCycleState = CompositeLifeCycle.MOUNTING;
if (this.__reactAutoBindMap) {
this._bindAutoBindMethods();
}
this.context = this._processContext(this._descriptor._context);
this.props = this._processProps(this.props);
this.state = this.getInitialState ? this.getInitialState() : null;
("production" !== "development" ? invariant(
typeof this.state === 'object' && !Array.isArray(this.state),
'%s.getInitialState(): must return an object or null',
this.constructor.displayName || 'ReactCompositeComponent'
) : invariant(typeof this.state === 'object' && !Array.isArray(this.state)));
this._pendingState = null;
this._pendingForceUpdate = false;
if (this.componentWillMount) {
this.componentWillMount();
// When mounting, calls to `setState` by `componentWillMount` will set
// `this._pendingState` without triggering a re-render.
if (this._pendingState) {
this.state = this._pendingState;
this._pendingState = null;
}
}
this._renderedComponent = instantiateReactComponent(
this._renderValidatedComponent()
);
// Done with mounting, `setState` will now trigger UI changes.
this._compositeLifeCycleState = null;
var markup = this._renderedComponent.mountComponent(
rootID,
transaction,
mountDepth + 1
);
if (this.componentDidMount) {
transaction.getReactMountReady().enqueue(this.componentDidMount, this);
}
return markup;
}
),
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function() {
this._compositeLifeCycleState = CompositeLifeCycle.UNMOUNTING;
if (this.componentWillUnmount) {
this.componentWillUnmount();
}
this._compositeLifeCycleState = null;
this._renderedComponent.unmountComponent();
this._renderedComponent = null;
ReactComponent.Mixin.unmountComponent.call(this);
// Some existing components rely on this.props even after they've been
// destroyed (in event handlers).
// TODO: this.props = null;
// TODO: this.state = null;
},
/**
* Sets a subset of the state. Always use this or `replaceState` to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* @param {object} partialState Next partial state to be merged with state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
setState: function(partialState, callback) {
("production" !== "development" ? invariant(
typeof partialState === 'object' || partialState == null,
'setState(...): takes an object of state variables to update.'
) : invariant(typeof partialState === 'object' || partialState == null));
if ("production" !== "development"){
("production" !== "development" ? warning(
partialState != null,
'setState(...): You passed an undefined or null state object; ' +
'instead, use forceUpdate().'
) : null);
}
// Merge with `_pendingState` if it exists, otherwise with existing state.
this.replaceState(
merge(this._pendingState || this.state, partialState),
callback
);
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {object} completeState Next state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
replaceState: function(completeState, callback) {
validateLifeCycleOnReplaceState(this);
this._pendingState = completeState;
if (this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING) {
// If we're in a componentWillMount handler, don't enqueue a rerender
// because ReactUpdates assumes we're in a browser context (which is wrong
// for server rendering) and we're about to do a render anyway.
// TODO: The callback here is ignored when setState is called from
// componentWillMount. Either fix it or disallow doing so completely in
// favor of getInitialState.
ReactUpdates.enqueueUpdate(this, callback);
}
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`, and asserts that they are valid.
*
* @param {object} context
* @return {?object}
* @private
*/
_processContext: function(context) {
var maskedContext = null;
var contextTypes = this.constructor.contextTypes;
if (contextTypes) {
maskedContext = {};
for (var contextName in contextTypes) {
maskedContext[contextName] = context[contextName];
}
if ("production" !== "development") {
this._checkPropTypes(
contextTypes,
maskedContext,
ReactPropTypeLocations.context
);
}
}
return maskedContext;
},
/**
* @param {object} currentContext
* @return {object}
* @private
*/
_processChildContext: function(currentContext) {
var childContext = this.getChildContext && this.getChildContext();
var displayName = this.constructor.displayName || 'ReactCompositeComponent';
if (childContext) {
("production" !== "development" ? invariant(
typeof this.constructor.childContextTypes === 'object',
'%s.getChildContext(): childContextTypes must be defined in order to ' +
'use getChildContext().',
displayName
) : invariant(typeof this.constructor.childContextTypes === 'object'));
if ("production" !== "development") {
this._checkPropTypes(
this.constructor.childContextTypes,
childContext,
ReactPropTypeLocations.childContext
);
}
for (var name in childContext) {
("production" !== "development" ? invariant(
name in this.constructor.childContextTypes,
'%s.getChildContext(): key "%s" is not defined in childContextTypes.',
displayName,
name
) : invariant(name in this.constructor.childContextTypes));
}
return merge(currentContext, childContext);
}
return currentContext;
},
/**
* Processes props by setting default values for unspecified props and
* asserting that the props are valid. Does not mutate its argument; returns
* a new props object with defaults merged in.
*
* @param {object} newProps
* @return {object}
* @private
*/
_processProps: function(newProps) {
var defaultProps = this.constructor.defaultProps;
var props;
if (defaultProps) {
props = merge(newProps);
for (var propName in defaultProps) {
if (typeof props[propName] === 'undefined') {
props[propName] = defaultProps[propName];
}
}
} else {
props = newProps;
}
if ("production" !== "development") {
var propTypes = this.constructor.propTypes;
if (propTypes) {
this._checkPropTypes(propTypes, props, ReactPropTypeLocations.prop);
}
}
return props;
},
/**
* Assert that the props are valid
*
* @param {object} propTypes Map of prop name to a ReactPropType
* @param {object} props
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
_checkPropTypes: function(propTypes, props, location) {
// TODO: Stop validating prop types here and only use the descriptor
// validation.
var componentName = this.constructor.displayName;
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error =
propTypes[propName](props, propName, componentName, location);
if (error instanceof Error) {
// We may want to extend this logic for similar errors in
// renderComponent calls, so I'm abstracting it away into
// a function to minimize refactoring in the future
var addendum = getDeclarationErrorAddendum(this);
("production" !== "development" ? warning(false, error.message + addendum) : null);
}
}
}
},
/**
* If any of `_pendingDescriptor`, `_pendingState`, or `_pendingForceUpdate`
* is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function(transaction) {
var compositeLifeCycleState = this._compositeLifeCycleState;
// Do not trigger a state transition if we are in the middle of mounting or
// receiving props because both of those will already be doing this.
if (compositeLifeCycleState === CompositeLifeCycle.MOUNTING ||
compositeLifeCycleState === CompositeLifeCycle.RECEIVING_PROPS) {
return;
}
if (this._pendingDescriptor == null &&
this._pendingState == null &&
!this._pendingForceUpdate) {
return;
}
var nextContext = this.context;
var nextProps = this.props;
var nextDescriptor = this._descriptor;
if (this._pendingDescriptor != null) {
nextDescriptor = this._pendingDescriptor;
nextContext = this._processContext(nextDescriptor._context);
nextProps = this._processProps(nextDescriptor.props);
this._pendingDescriptor = null;
this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_PROPS;
if (this.componentWillReceiveProps) {
this.componentWillReceiveProps(nextProps, nextContext);
}
}
this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_STATE;
var nextState = this._pendingState || this.state;
this._pendingState = null;
try {
var shouldUpdate =
this._pendingForceUpdate ||
!this.shouldComponentUpdate ||
this.shouldComponentUpdate(nextProps, nextState, nextContext);
if ("production" !== "development") {
if (typeof shouldUpdate === "undefined") {
console.warn(
(this.constructor.displayName || 'ReactCompositeComponent') +
'.shouldComponentUpdate(): Returned undefined instead of a ' +
'boolean value. Make sure to return true or false.'
);
}
}
if (shouldUpdate) {
this._pendingForceUpdate = false;
// Will set `this.props`, `this.state` and `this.context`.
this._performComponentUpdate(
nextDescriptor,
nextProps,
nextState,
nextContext,
transaction
);
} else {
// If it's determined that a component should not update, we still want
// to set props and state.
this._descriptor = nextDescriptor;
this.props = nextProps;
this.state = nextState;
this.context = nextContext;
// Owner cannot change because shouldUpdateReactComponent doesn't allow
// it. TODO: Remove this._owner completely.
this._owner = nextDescriptor._owner;
}
} finally {
this._compositeLifeCycleState = null;
}
},
/**
* Merges new props and state, notifies delegate methods of update and
* performs update.
*
* @param {ReactDescriptor} nextDescriptor Next descriptor
* @param {object} nextProps Next public object to set as properties.
* @param {?object} nextState Next object to set as state.
* @param {?object} nextContext Next public object to set as context.
* @param {ReactReconcileTransaction} transaction
* @private
*/
_performComponentUpdate: function(
nextDescriptor,
nextProps,
nextState,
nextContext,
transaction
) {
var prevDescriptor = this._descriptor;
var prevProps = this.props;
var prevState = this.state;
var prevContext = this.context;
if (this.componentWillUpdate) {
this.componentWillUpdate(nextProps, nextState, nextContext);
}
this._descriptor = nextDescriptor;
this.props = nextProps;
this.state = nextState;
this.context = nextContext;
// Owner cannot change because shouldUpdateReactComponent doesn't allow
// it. TODO: Remove this._owner completely.
this._owner = nextDescriptor._owner;
this.updateComponent(
transaction,
prevDescriptor
);
if (this.componentDidUpdate) {
transaction.getReactMountReady().enqueue(
this.componentDidUpdate.bind(this, prevProps, prevState, prevContext),
this
);
}
},
receiveComponent: function(nextDescriptor, transaction) {
if (nextDescriptor === this._descriptor &&
nextDescriptor._owner != null) {
// Since descriptors are immutable after the owner is rendered,
// we can do a cheap identity compare here to determine if this is a
// superfluous reconcile. It's possible for state to be mutable but such
// change should trigger an update of the owner which would recreate
// the descriptor. We explicitly check for the existence of an owner since
// it's possible for a descriptor created outside a composite to be
// deeply mutated and reused.
return;
}
ReactComponent.Mixin.receiveComponent.call(
this,
nextDescriptor,
transaction
);
},
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactDescriptor} prevDescriptor
* @internal
* @overridable
*/
updateComponent: ReactPerf.measure(
'ReactCompositeComponent',
'updateComponent',
function(transaction, prevParentDescriptor) {
ReactComponent.Mixin.updateComponent.call(
this,
transaction,
prevParentDescriptor
);
var prevComponentInstance = this._renderedComponent;
var prevDescriptor = prevComponentInstance._descriptor;
var nextDescriptor = this._renderValidatedComponent();
if (shouldUpdateReactComponent(prevDescriptor, nextDescriptor)) {
prevComponentInstance.receiveComponent(nextDescriptor, transaction);
} else {
// These two IDs are actually the same! But nothing should rely on that.
var thisID = this._rootNodeID;
var prevComponentID = prevComponentInstance._rootNodeID;
prevComponentInstance.unmountComponent();
this._renderedComponent = instantiateReactComponent(nextDescriptor);
var nextMarkup = this._renderedComponent.mountComponent(
thisID,
transaction,
this._mountDepth + 1
);
ReactComponent.BackendIDOperations.dangerouslyReplaceNodeWithMarkupByID(
prevComponentID,
nextMarkup
);
}
}
),
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldUpdateComponent`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
forceUpdate: function(callback) {
var compositeLifeCycleState = this._compositeLifeCycleState;
("production" !== "development" ? invariant(
this.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING,
'forceUpdate(...): Can only force an update on mounted or mounting ' +
'components.'
) : invariant(this.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING));
("production" !== "development" ? invariant(
compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE &&
compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING,
'forceUpdate(...): Cannot force an update while unmounting component ' +
'or during an existing state transition (such as within `render`).'
) : invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE &&
compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING));
this._pendingForceUpdate = true;
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* @private
*/
_renderValidatedComponent: ReactPerf.measure(
'ReactCompositeComponent',
'_renderValidatedComponent',
function() {
var renderedComponent;
var previousContext = ReactContext.current;
ReactContext.current = this._processChildContext(
this._descriptor._context
);
ReactCurrentOwner.current = this;
try {
renderedComponent = this.render();
if (renderedComponent === null || renderedComponent === false) {
renderedComponent = ReactEmptyComponent.getEmptyComponent();
ReactEmptyComponent.registerNullComponentID(this._rootNodeID);
} else {
ReactEmptyComponent.deregisterNullComponentID(this._rootNodeID);
}
} finally {
ReactContext.current = previousContext;
ReactCurrentOwner.current = null;
}
("production" !== "development" ? invariant(
ReactDescriptor.isValidDescriptor(renderedComponent),
'%s.render(): A valid ReactComponent must be returned. You may have ' +
'returned undefined, an array or some other invalid object.',
this.constructor.displayName || 'ReactCompositeComponent'
) : invariant(ReactDescriptor.isValidDescriptor(renderedComponent)));
return renderedComponent;
}
),
/**
* @private
*/
_bindAutoBindMethods: function() {
for (var autoBindKey in this.__reactAutoBindMap) {
if (!this.__reactAutoBindMap.hasOwnProperty(autoBindKey)) {
continue;
}
var method = this.__reactAutoBindMap[autoBindKey];
this[autoBindKey] = this._bindAutoBindMethod(ReactErrorUtils.guard(
method,
this.constructor.displayName + '.' + autoBindKey
));
}
},
/**
* Binds a method to the component.
*
* @param {function} method Method to be bound.
* @private
*/
_bindAutoBindMethod: function(method) {
var component = this;
var boundMethod = function() {
return method.apply(component, arguments);
};
if ("production" !== "development") {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
boundMethod.bind = function(newThis ) {var args=Array.prototype.slice.call(arguments,1);
// User is trying to bind() an autobound method; we effectively will
// ignore the value of "this" that the user is trying to use, so
// let's warn.
if (newThis !== component && newThis !== null) {
monitorCodeUse('react_bind_warning', { component: componentName });
console.warn(
'bind(): React component methods may only be bound to the ' +
'component instance. See ' + componentName
);
} else if (!args.length) {
monitorCodeUse('react_bind_warning', { component: componentName });
console.warn(
'bind(): You are binding a component method to the component. ' +
'React does this for you automatically in a high-performance ' +
'way, so you can safely remove this call. See ' + componentName
);
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
};
}
return boundMethod;
}
};
var ReactCompositeComponentBase = function() {};
mixInto(ReactCompositeComponentBase, ReactComponent.Mixin);
mixInto(ReactCompositeComponentBase, ReactOwner.Mixin);
mixInto(ReactCompositeComponentBase, ReactPropTransferer.Mixin);
mixInto(ReactCompositeComponentBase, ReactCompositeComponentMixin);
/**
* Module for creating composite components.
*
* @class ReactCompositeComponent
* @extends ReactComponent
* @extends ReactOwner
* @extends ReactPropTransferer
*/
var ReactCompositeComponent = {
LifeCycle: CompositeLifeCycle,
Base: ReactCompositeComponentBase,
/**
* Creates a composite component class given a class specification.
*
* @param {object} spec Class specification (which must define `render`).
* @return {function} Component constructor function.
* @public
*/
createClass: function(spec) {
var Constructor = function(props, owner) {
this.construct(props, owner);
};
Constructor.prototype = new ReactCompositeComponentBase();
Constructor.prototype.constructor = Constructor;
injectedMixins.forEach(
mixSpecIntoComponent.bind(null, Constructor)
);
mixSpecIntoComponent(Constructor, spec);
// Initialize the defaultProps property after all mixins have been merged
if (Constructor.getDefaultProps) {
Constructor.defaultProps = Constructor.getDefaultProps();
}
("production" !== "development" ? invariant(
Constructor.prototype.render,
'createClass(...): Class specification must implement a `render` method.'
) : invariant(Constructor.prototype.render));
if ("production" !== "development") {
if (Constructor.prototype.componentShouldUpdate) {
monitorCodeUse(
'react_component_should_update_warning',
{ component: spec.displayName }
);
console.warn(
(spec.displayName || 'A component') + ' has a method called ' +
'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
'The name is phrased as a question because the function is ' +
'expected to return a value.'
);
}
}
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactCompositeComponentInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
var descriptorFactory = ReactDescriptor.createFactory(Constructor);
if ("production" !== "development") {
return ReactDescriptorValidator.createFactory(
descriptorFactory,
Constructor.propTypes,
Constructor.contextTypes
);
}
return descriptorFactory;
},
injection: {
injectMixin: function(mixin) {
injectedMixins.push(mixin);
}
}
};
module.exports = ReactCompositeComponent;
},{"./ReactComponent":35,"./ReactContext":39,"./ReactCurrentOwner":40,"./ReactDescriptor":56,"./ReactDescriptorValidator":57,"./ReactEmptyComponent":58,"./ReactErrorUtils":59,"./ReactOwner":70,"./ReactPerf":71,"./ReactPropTransferer":72,"./ReactPropTypeLocationNames":73,"./ReactPropTypeLocations":74,"./ReactUpdates":87,"./instantiateReactComponent":133,"./invariant":134,"./keyMirror":140,"./mapObject":142,"./merge":144,"./mixInto":147,"./monitorCodeUse":148,"./shouldUpdateReactComponent":154,"./warning":158}],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 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":144}],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 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;
},{}],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 ReactDOM
* @typechecks static-only
*/
"use strict";
var ReactDescriptor = _dereq_("./ReactDescriptor");
var ReactDescriptorValidator = _dereq_("./ReactDescriptorValidator");
var ReactDOMComponent = _dereq_("./ReactDOMComponent");
var mergeInto = _dereq_("./mergeInto");
var mapObject = _dereq_("./mapObject");
/**
* Creates a new React class that is idempotent and capable of containing other
* React components. It accepts event listeners and DOM properties that are
* valid according to `DOMProperty`.
*
* - Event listeners: `onClick`, `onMouseDown`, etc.
* - DOM properties: `className`, `name`, `title`, etc.
*
* The `style` property functions differently from the DOM API. It accepts an
* object mapping of style properties to values.
*
* @param {boolean} omitClose True if the close tag should be omitted.
* @param {string} tag Tag name (e.g. `div`).
* @private
*/
function createDOMComponentClass(omitClose, tag) {
var Constructor = function(descriptor) {
this.construct(descriptor);
};
Constructor.prototype = new ReactDOMComponent(tag, omitClose);
Constructor.prototype.constructor = Constructor;
Constructor.displayName = tag;
var ConvenienceConstructor = ReactDescriptor.createFactory(Constructor);
if ("production" !== "development") {
return ReactDescriptorValidator.createFactory(
ConvenienceConstructor
);
}
return ConvenienceConstructor;
}
/**
* Creates a mapping from supported HTML tags to `ReactDOMComponent` classes.
* This is also accessible via `React.DOM`.
*
* @public
*/
var ReactDOM = mapObject({
a: false,
abbr: false,
address: false,
area: true,
article: false,
aside: false,
audio: false,
b: false,
base: true,
bdi: false,
bdo: false,
big: false,
blockquote: false,
body: false,
br: true,
button: false,
canvas: false,
caption: false,
cite: false,
code: false,
col: true,
colgroup: false,
data: false,
datalist: false,
dd: false,
del: false,
details: false,
dfn: false,
dialog: false,
div: false,
dl: false,
dt: false,
em: false,
embed: true,
fieldset: false,
figcaption: false,
figure: false,
footer: false,
form: false, // NOTE: Injected, see `ReactDOMForm`.
h1: false,
h2: false,
h3: false,
h4: false,
h5: false,
h6: false,
head: false,
header: false,
hr: true,
html: false,
i: false,
iframe: false,
img: true,
input: true,
ins: false,
kbd: false,
keygen: true,
label: false,
legend: false,
li: false,
link: true,
main: false,
map: false,
mark: false,
menu: false,
menuitem: false, // NOTE: Close tag should be omitted, but causes problems.
meta: true,
meter: false,
nav: false,
noscript: false,
object: false,
ol: false,
optgroup: false,
option: false,
output: false,
p: false,
param: true,
picture: false,
pre: false,
progress: false,
q: false,
rp: false,
rt: false,
ruby: false,
s: false,
samp: false,
script: false,
section: false,
select: false,
small: false,
source: true,
span: false,
strong: false,
style: false,
sub: false,
summary: false,
sup: false,
table: false,
tbody: false,
td: false,
textarea: false, // NOTE: Injected, see `ReactDOMTextarea`.
tfoot: false,
th: false,
thead: false,
time: false,
title: false,
tr: false,
track: true,
u: false,
ul: false,
'var': false,
video: false,
wbr: true,
// SVG
circle: false,
defs: false,
ellipse: false,
g: false,
line: false,
linearGradient: false,
mask: false,
path: false,
pattern: false,
polygon: false,
polyline: false,
radialGradient: false,
rect: false,
stop: false,
svg: false,
text: false,
tspan: false
}, createDOMComponentClass);
var injection = {
injectComponentClasses: function(componentClasses) {
mergeInto(ReactDOM, componentClasses);
}
};
ReactDOM.injection = injection;
module.exports = ReactDOM;
},{"./ReactDOMComponent":43,"./ReactDescriptor":56,"./ReactDescriptorValidator":57,"./mapObject":142,"./mergeInto":146}],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 ReactDOMButton
*/
"use strict";
var AutoFocusMixin = _dereq_("./AutoFocusMixin");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var keyMirror = _dereq_("./keyMirror");
// Store a reference to the <button> `ReactDOMComponent`.
var button = ReactDOM.button;
var mouseListenerNames = keyMirror({
onClick: true,
onDoubleClick: true,
onMouseDown: true,
onMouseMove: true,
onMouseUp: true,
onClickCapture: true,
onDoubleClickCapture: true,
onMouseDownCapture: true,
onMouseMoveCapture: true,
onMouseUpCapture: true
});
/**
* Implements a <button> native component that does not receive mouse events
* when `disabled` is set.
*/
var ReactDOMButton = ReactCompositeComponent.createClass({
displayName: 'ReactDOMButton',
mixins: [AutoFocusMixin, ReactBrowserComponentMixin],
render: function() {
var props = {};
// Copy the props; except the mouse listeners if we're disabled
for (var key in this.props) {
if (this.props.hasOwnProperty(key) &&
(!this.props.disabled || !mouseListenerNames[key])) {
props[key] = this.props[key];
}
}
return button(props, this.props.children);
}
});
module.exports = ReactDOMButton;
},{"./AutoFocusMixin":1,"./ReactBrowserComponentMixin":30,"./ReactCompositeComponent":38,"./ReactDOM":41,"./keyMirror":140}],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 ReactDOMComponent
* @typechecks static-only
*/
"use strict";
var CSSPropertyOperations = _dereq_("./CSSPropertyOperations");
var DOMProperty = _dereq_("./DOMProperty");
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactComponent = _dereq_("./ReactComponent");
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var ReactMount = _dereq_("./ReactMount");
var ReactMultiChild = _dereq_("./ReactMultiChild");
var ReactPerf = _dereq_("./ReactPerf");
var escapeTextForBrowser = _dereq_("./escapeTextForBrowser");
var invariant = _dereq_("./invariant");
var keyOf = _dereq_("./keyOf");
var merge = _dereq_("./merge");
var mixInto = _dereq_("./mixInto");
var deleteListener = ReactBrowserEventEmitter.deleteListener;
var listenTo = ReactBrowserEventEmitter.listenTo;
var registrationNameModules = ReactBrowserEventEmitter.registrationNameModules;
// For quickly matching children type, to test if can be treated as content.
var CONTENT_TYPES = {'string': true, 'number': true};
var STYLE = keyOf({style: null});
var ELEMENT_NODE_TYPE = 1;
/**
* @param {?object} props
*/
function assertValidProps(props) {
if (!props) {
return;
}
// Note the use of `==` which checks for null or undefined.
("production" !== "development" ? invariant(
props.children == null || props.dangerouslySetInnerHTML == null,
'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'
) : invariant(props.children == null || props.dangerouslySetInnerHTML == null));
("production" !== "development" ? invariant(
props.style == null || typeof props.style === 'object',
'The `style` prop expects a mapping from style properties to values, ' +
'not a string.'
) : invariant(props.style == null || typeof props.style === 'object'));
}
function putListener(id, registrationName, listener, transaction) {
var container = ReactMount.findReactContainerForID(id);
if (container) {
var doc = container.nodeType === ELEMENT_NODE_TYPE ?
container.ownerDocument :
container;
listenTo(registrationName, doc);
}
transaction.getPutListenerQueue().enqueuePutListener(
id,
registrationName,
listener
);
}
/**
* @constructor ReactDOMComponent
* @extends ReactComponent
* @extends ReactMultiChild
*/
function ReactDOMComponent(tag, omitClose) {
this._tagOpen = '<' + tag;
this._tagClose = omitClose ? '' : '</' + tag + '>';
this.tagName = tag.toUpperCase();
}
ReactDOMComponent.Mixin = {
/**
* Generates root tag markup then recurses. This method has side effects and
* is not idempotent.
*
* @internal
* @param {string} rootID The root DOM ID for this node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {number} mountDepth number of components in the owner hierarchy
* @return {string} The computed markup.
*/
mountComponent: ReactPerf.measure(
'ReactDOMComponent',
'mountComponent',
function(rootID, transaction, mountDepth) {
ReactComponent.Mixin.mountComponent.call(
this,
rootID,
transaction,
mountDepth
);
assertValidProps(this.props);
return (
this._createOpenTagMarkupAndPutListeners(transaction) +
this._createContentMarkup(transaction) +
this._tagClose
);
}
),
/**
* Creates markup for the open tag and all attributes.
*
* This method has side effects because events get registered.
*
* Iterating over object properties is faster than iterating over arrays.
* @see http://jsperf.com/obj-vs-arr-iteration
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {string} Markup of opening tag.
*/
_createOpenTagMarkupAndPutListeners: function(transaction) {
var props = this.props;
var ret = this._tagOpen;
for (var propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
var propValue = props[propKey];
if (propValue == null) {
continue;
}
if (registrationNameModules.hasOwnProperty(propKey)) {
putListener(this._rootNodeID, propKey, propValue, transaction);
} else {
if (propKey === STYLE) {
if (propValue) {
propValue = props.style = merge(props.style);
}
propValue = CSSPropertyOperations.createMarkupForStyles(propValue);
}
var markup =
DOMPropertyOperations.createMarkupForProperty(propKey, propValue);
if (markup) {
ret += ' ' + markup;
}
}
}
// For static pages, no need to put React ID and checksum. Saves lots of
// bytes.
if (transaction.renderToStaticMarkup) {
return ret + '>';
}
var markupForID = DOMPropertyOperations.createMarkupForID(this._rootNodeID);
return ret + ' ' + markupForID + '>';
},
/**
* Creates markup for the content between the tags.
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {string} Content markup.
*/
_createContentMarkup: function(transaction) {
// Intentional use of != to avoid catching zero/false.
var innerHTML = this.props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
return innerHTML.__html;
}
} else {
var contentToUse =
CONTENT_TYPES[typeof this.props.children] ? this.props.children : null;
var childrenToUse = contentToUse != null ? null : this.props.children;
if (contentToUse != null) {
return escapeTextForBrowser(contentToUse);
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(
childrenToUse,
transaction
);
return mountImages.join('');
}
}
return '';
},
receiveComponent: function(nextDescriptor, transaction) {
if (nextDescriptor === this._descriptor &&
nextDescriptor._owner != null) {
// Since descriptors are immutable after the owner is rendered,
// we can do a cheap identity compare here to determine if this is a
// superfluous reconcile. It's possible for state to be mutable but such
// change should trigger an update of the owner which would recreate
// the descriptor. We explicitly check for the existence of an owner since
// it's possible for a descriptor created outside a composite to be
// deeply mutated and reused.
return;
}
ReactComponent.Mixin.receiveComponent.call(
this,
nextDescriptor,
transaction
);
},
/**
* Updates a native DOM component after it has already been allocated and
* attached to the DOM. Reconciles the root DOM node, then recurses.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactDescriptor} prevDescriptor
* @internal
* @overridable
*/
updateComponent: ReactPerf.measure(
'ReactDOMComponent',
'updateComponent',
function(transaction, prevDescriptor) {
assertValidProps(this._descriptor.props);
ReactComponent.Mixin.updateComponent.call(
this,
transaction,
prevDescriptor
);
this._updateDOMProperties(prevDescriptor.props, transaction);
this._updateDOMChildren(prevDescriptor.props, transaction);
}
),
/**
* Reconciles the properties by detecting differences in property values and
* updating the DOM as necessary. This function is probably the single most
* critical path for performance optimization.
*
* TODO: Benchmark whether checking for changed values in memory actually
* improves performance (especially statically positioned elements).
* TODO: Benchmark the effects of putting this at the top since 99% of props
* do not change for a given reconciliation.
* TODO: Benchmark areas that can be improved with caching.
*
* @private
* @param {object} lastProps
* @param {ReactReconcileTransaction} transaction
*/
_updateDOMProperties: function(lastProps, transaction) {
var nextProps = this.props;
var propKey;
var styleName;
var styleUpdates;
for (propKey in lastProps) {
if (nextProps.hasOwnProperty(propKey) ||
!lastProps.hasOwnProperty(propKey)) {
continue;
}
if (propKey === STYLE) {
var lastStyle = lastProps[propKey];
for (styleName in lastStyle) {
if (lastStyle.hasOwnProperty(styleName)) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
} else if (registrationNameModules.hasOwnProperty(propKey)) {
deleteListener(this._rootNodeID, propKey);
} else if (
DOMProperty.isStandardName[propKey] ||
DOMProperty.isCustomAttribute(propKey)) {
ReactComponent.BackendIDOperations.deletePropertyByID(
this._rootNodeID,
propKey
);
}
}
for (propKey in nextProps) {
var nextProp = nextProps[propKey];
var lastProp = lastProps[propKey];
if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) {
continue;
}
if (propKey === STYLE) {
if (nextProp) {
nextProp = nextProps.style = merge(nextProp);
}
if (lastProp) {
// Unset styles on `lastProp` but not on `nextProp`.
for (styleName in lastProp) {
if (lastProp.hasOwnProperty(styleName) &&
(!nextProp || !nextProp.hasOwnProperty(styleName))) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
// Update styles that changed since `lastProp`.
for (styleName in nextProp) {
if (nextProp.hasOwnProperty(styleName) &&
lastProp[styleName] !== nextProp[styleName]) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = nextProp[styleName];
}
}
} else {
// Relies on `updateStylesByID` not mutating `styleUpdates`.
styleUpdates = nextProp;
}
} else if (registrationNameModules.hasOwnProperty(propKey)) {
putListener(this._rootNodeID, propKey, nextProp, transaction);
} else if (
DOMProperty.isStandardName[propKey] ||
DOMProperty.isCustomAttribute(propKey)) {
ReactComponent.BackendIDOperations.updatePropertyByID(
this._rootNodeID,
propKey,
nextProp
);
}
}
if (styleUpdates) {
ReactComponent.BackendIDOperations.updateStylesByID(
this._rootNodeID,
styleUpdates
);
}
},
/**
* Reconciles the children with the various properties that affect the
* children content.
*
* @param {object} lastProps
* @param {ReactReconcileTransaction} transaction
*/
_updateDOMChildren: function(lastProps, transaction) {
var nextProps = this.props;
var lastContent =
CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null;
var nextContent =
CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null;
var lastHtml =
lastProps.dangerouslySetInnerHTML &&
lastProps.dangerouslySetInnerHTML.__html;
var nextHtml =
nextProps.dangerouslySetInnerHTML &&
nextProps.dangerouslySetInnerHTML.__html;
// Note the use of `!=` which checks for null or undefined.
var lastChildren = lastContent != null ? null : lastProps.children;
var nextChildren = nextContent != null ? null : nextProps.children;
// If we're switching from children to content/html or vice versa, remove
// the old content
var lastHasContentOrHtml = lastContent != null || lastHtml != null;
var nextHasContentOrHtml = nextContent != null || nextHtml != null;
if (lastChildren != null && nextChildren == null) {
this.updateChildren(null, transaction);
} else if (lastHasContentOrHtml && !nextHasContentOrHtml) {
this.updateTextContent('');
}
if (nextContent != null) {
if (lastContent !== nextContent) {
this.updateTextContent('' + nextContent);
}
} else if (nextHtml != null) {
if (lastHtml !== nextHtml) {
ReactComponent.BackendIDOperations.updateInnerHTMLByID(
this._rootNodeID,
nextHtml
);
}
} else if (nextChildren != null) {
this.updateChildren(nextChildren, transaction);
}
},
/**
* Destroys all event registrations for this instance. Does not remove from
* the DOM. That must be done by the parent.
*
* @internal
*/
unmountComponent: function() {
this.unmountChildren();
ReactBrowserEventEmitter.deleteAllListeners(this._rootNodeID);
ReactComponent.Mixin.unmountComponent.call(this);
}
};
mixInto(ReactDOMComponent, ReactComponent.Mixin);
mixInto(ReactDOMComponent, ReactDOMComponent.Mixin);
mixInto(ReactDOMComponent, ReactMultiChild.Mixin);
mixInto(ReactDOMComponent, ReactBrowserComponentMixin);
module.exports = ReactDOMComponent;
},{"./CSSPropertyOperations":5,"./DOMProperty":11,"./DOMPropertyOperations":12,"./ReactBrowserComponentMixin":30,"./ReactBrowserEventEmitter":31,"./ReactComponent":35,"./ReactMount":67,"./ReactMultiChild":68,"./ReactPerf":71,"./escapeTextForBrowser":118,"./invariant":134,"./keyOf":141,"./merge":144,"./mixInto":147}],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 ReactDOMForm
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var LocalEventTrapMixin = _dereq_("./LocalEventTrapMixin");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
// Store a reference to the <form> `ReactDOMComponent`.
var form = ReactDOM.form;
/**
* Since onSubmit doesn't bubble OR capture on the top level in IE8, we need
* to capture it on the <form> element itself. There are lots of hacks we could
* do to accomplish this, but the most reliable is to make <form> a
* composite component and use `componentDidMount` to attach the event handlers.
*/
var ReactDOMForm = ReactCompositeComponent.createClass({
displayName: 'ReactDOMForm',
mixins: [ReactBrowserComponentMixin, LocalEventTrapMixin],
render: function() {
// TODO: Instead of using `ReactDOM` directly, we should use JSX. However,
// `jshint` fails to parse JSX so in order for linting to work in the open
// source repo, we need to just use `ReactDOM.form`.
return this.transferPropsTo(form(null, this.props.children));
},
componentDidMount: function() {
this.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset');
this.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit');
}
});
module.exports = ReactDOMForm;
},{"./EventConstants":16,"./LocalEventTrapMixin":26,"./ReactBrowserComponentMixin":30,"./ReactCompositeComponent":38,"./ReactDOM":41}],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 ReactDOMIDOperations
* @typechecks static-only
*/
/*jslint evil: true */
"use strict";
var CSSPropertyOperations = _dereq_("./CSSPropertyOperations");
var DOMChildrenOperations = _dereq_("./DOMChildrenOperations");
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var ReactMount = _dereq_("./ReactMount");
var ReactPerf = _dereq_("./ReactPerf");
var invariant = _dereq_("./invariant");
var setInnerHTML = _dereq_("./setInnerHTML");
/**
* Errors for properties that should not be updated with `updatePropertyById()`.
*
* @type {object}
* @private
*/
var INVALID_PROPERTY_ERRORS = {
dangerouslySetInnerHTML:
'`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.',
style: '`style` must be set using `updateStylesByID()`.'
};
/**
* Operations used to process updates to DOM nodes. This is made injectable via
* `ReactComponent.BackendIDOperations`.
*/
var ReactDOMIDOperations = {
/**
* Updates a DOM node with new property values. This should only be used to
* update DOM properties in `DOMProperty`.
*
* @param {string} id ID of the node to update.
* @param {string} name A valid property name, see `DOMProperty`.
* @param {*} value New value of the property.
* @internal
*/
updatePropertyByID: ReactPerf.measure(
'ReactDOMIDOperations',
'updatePropertyByID',
function(id, name, value) {
var node = ReactMount.getNode(id);
("production" !== "development" ? invariant(
!INVALID_PROPERTY_ERRORS.hasOwnProperty(name),
'updatePropertyByID(...): %s',
INVALID_PROPERTY_ERRORS[name]
) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name)));
// If we're updating to null or undefined, we should remove the property
// from the DOM node instead of inadvertantly setting to a string. This
// brings us in line with the same behavior we have on initial render.
if (value != null) {
DOMPropertyOperations.setValueForProperty(node, name, value);
} else {
DOMPropertyOperations.deleteValueForProperty(node, name);
}
}
),
/**
* Updates a DOM node to remove a property. This should only be used to remove
* DOM properties in `DOMProperty`.
*
* @param {string} id ID of the node to update.
* @param {string} name A property name to remove, see `DOMProperty`.
* @internal
*/
deletePropertyByID: ReactPerf.measure(
'ReactDOMIDOperations',
'deletePropertyByID',
function(id, name, value) {
var node = ReactMount.getNode(id);
("production" !== "development" ? invariant(
!INVALID_PROPERTY_ERRORS.hasOwnProperty(name),
'updatePropertyByID(...): %s',
INVALID_PROPERTY_ERRORS[name]
) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name)));
DOMPropertyOperations.deleteValueForProperty(node, name, value);
}
),
/**
* Updates a DOM node with new style values. If a value is specified as '',
* the corresponding style property will be unset.
*
* @param {string} id ID of the node to update.
* @param {object} styles Mapping from styles to values.
* @internal
*/
updateStylesByID: ReactPerf.measure(
'ReactDOMIDOperations',
'updateStylesByID',
function(id, styles) {
var node = ReactMount.getNode(id);
CSSPropertyOperations.setValueForStyles(node, styles);
}
),
/**
* Updates a DOM node's innerHTML.
*
* @param {string} id ID of the node to update.
* @param {string} html An HTML string.
* @internal
*/
updateInnerHTMLByID: ReactPerf.measure(
'ReactDOMIDOperations',
'updateInnerHTMLByID',
function(id, html) {
var node = ReactMount.getNode(id);
setInnerHTML(node, html);
}
),
/**
* Updates a DOM node's text content set by `props.content`.
*
* @param {string} id ID of the node to update.
* @param {string} content Text content.
* @internal
*/
updateTextContentByID: ReactPerf.measure(
'ReactDOMIDOperations',
'updateTextContentByID',
function(id, content) {
var node = ReactMount.getNode(id);
DOMChildrenOperations.updateTextContent(node, content);
}
),
/**
* Replaces a DOM node that exists in the document with markup.
*
* @param {string} id ID of child to be replaced.
* @param {string} markup Dangerous markup to inject in place of child.
* @internal
* @see {Danger.dangerouslyReplaceNodeWithMarkup}
*/
dangerouslyReplaceNodeWithMarkupByID: ReactPerf.measure(
'ReactDOMIDOperations',
'dangerouslyReplaceNodeWithMarkupByID',
function(id, markup) {
var node = ReactMount.getNode(id);
DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup);
}
),
/**
* Updates a component's children by processing a series of updates.
*
* @param {array<object>} updates List of update configurations.
* @param {array<string>} markup List of markup strings.
* @internal
*/
dangerouslyProcessChildrenUpdates: ReactPerf.measure(
'ReactDOMIDOperations',
'dangerouslyProcessChildrenUpdates',
function(updates, markup) {
for (var i = 0; i < updates.length; i++) {
updates[i].parentNode = ReactMount.getNode(updates[i].parentID);
}
DOMChildrenOperations.processUpdates(updates, markup);
}
)
};
module.exports = ReactDOMIDOperations;
},{"./CSSPropertyOperations":5,"./DOMChildrenOperations":10,"./DOMPropertyOperations":12,"./ReactMount":67,"./ReactPerf":71,"./invariant":134,"./setInnerHTML":152}],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 ReactDOMImg
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var LocalEventTrapMixin = _dereq_("./LocalEventTrapMixin");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
// Store a reference to the <img> `ReactDOMComponent`.
var img = ReactDOM.img;
/**
* Since onLoad doesn't bubble OR capture on the top level in IE8, we need to
* capture it on the <img> element itself. There are lots of hacks we could do
* to accomplish this, but the most reliable is to make <img> a composite
* component and use `componentDidMount` to attach the event handlers.
*/
var ReactDOMImg = ReactCompositeComponent.createClass({
displayName: 'ReactDOMImg',
tagName: 'IMG',
mixins: [ReactBrowserComponentMixin, LocalEventTrapMixin],
render: function() {
return img(this.props);
},
componentDidMount: function() {
this.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load');
this.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error');
}
});
module.exports = ReactDOMImg;
},{"./EventConstants":16,"./LocalEventTrapMixin":26,"./ReactBrowserComponentMixin":30,"./ReactCompositeComponent":38,"./ReactDOM":41}],47:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactDOMInput
*/
"use strict";
var AutoFocusMixin = _dereq_("./AutoFocusMixin");
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var LinkedValueUtils = _dereq_("./LinkedValueUtils");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var ReactMount = _dereq_("./ReactMount");
var invariant = _dereq_("./invariant");
var merge = _dereq_("./merge");
// Store a reference to the <input> `ReactDOMComponent`.
var input = ReactDOM.input;
var instancesByReactID = {};
/**
* Implements an <input> native component that allows setting these optional
* props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
*
* If `checked` or `value` are not supplied (or null/undefined), user actions
* that affect the checked state or value will trigger updates to the element.
*
* If they are supplied (and not null/undefined), the rendered element will not
* trigger updates to the element. Instead, the props must change in order for
* the rendered element to be updated.
*
* The rendered element will be initialized as unchecked (or `defaultChecked`)
* with an empty value (or `defaultValue`).
*
* @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
*/
var ReactDOMInput = ReactCompositeComponent.createClass({
displayName: 'ReactDOMInput',
mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin],
getInitialState: function() {
var defaultValue = this.props.defaultValue;
return {
checked: this.props.defaultChecked || false,
value: defaultValue != null ? defaultValue : null
};
},
shouldComponentUpdate: function() {
// Defer any updates to this component during the `onChange` handler.
return !this._isChanging;
},
render: function() {
// Clone `this.props` so we don't mutate the input.
var props = merge(this.props);
props.defaultChecked = null;
props.defaultValue = null;
var value = LinkedValueUtils.getValue(this);
props.value = value != null ? value : this.state.value;
var checked = LinkedValueUtils.getChecked(this);
props.checked = checked != null ? checked : this.state.checked;
props.onChange = this._handleChange;
return input(props, this.props.children);
},
componentDidMount: function() {
var id = ReactMount.getID(this.getDOMNode());
instancesByReactID[id] = this;
},
componentWillUnmount: function() {
var rootNode = this.getDOMNode();
var id = ReactMount.getID(rootNode);
delete instancesByReactID[id];
},
componentDidUpdate: function(prevProps, prevState, prevContext) {
var rootNode = this.getDOMNode();
if (this.props.checked != null) {
DOMPropertyOperations.setValueForProperty(
rootNode,
'checked',
this.props.checked || false
);
}
var value = LinkedValueUtils.getValue(this);
if (value != null) {
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value);
}
},
_handleChange: function(event) {
var returnValue;
var onChange = LinkedValueUtils.getOnChange(this);
if (onChange) {
this._isChanging = true;
returnValue = onChange.call(this, event);
this._isChanging = false;
}
this.setState({
checked: event.target.checked,
value: event.target.value
});
var name = this.props.name;
if (this.props.type === 'radio' && name != null) {
var rootNode = this.getDOMNode();
var queryRoot = rootNode;
while (queryRoot.parentNode) {
queryRoot = queryRoot.parentNode;
}
// If `rootNode.form` was non-null, then we could try `form.elements`,
// but that sometimes behaves strangely in IE8. We could also try using
// `form.getElementsByName`, but that will only return direct children
// and won't include inputs that use the HTML5 `form=` attribute. Since
// the input might not even be in a form, let's just use the global
// `querySelectorAll` to ensure we don't miss anything.
var group = queryRoot.querySelectorAll(
'input[name=' + JSON.stringify('' + name) + '][type="radio"]');
for (var i = 0, groupLen = group.length; i < groupLen; i++) {
var otherNode = group[i];
if (otherNode === rootNode ||
otherNode.form !== rootNode.form) {
continue;
}
var otherID = ReactMount.getID(otherNode);
("production" !== "development" ? invariant(
otherID,
'ReactDOMInput: Mixing React and non-React radio inputs with the ' +
'same `name` is not supported.'
) : invariant(otherID));
var otherInstance = instancesByReactID[otherID];
("production" !== "development" ? invariant(
otherInstance,
'ReactDOMInput: Unknown radio button ID %s.',
otherID
) : invariant(otherInstance));
// In some cases, this will actually change the `checked` state value.
// In other cases, there's no change but this forces a reconcile upon
// which componentDidUpdate will reset the DOM property to whatever it
// should be.
otherInstance.setState({
checked: false
});
}
}
return returnValue;
}
});
module.exports = ReactDOMInput;
},{"./AutoFocusMixin":1,"./DOMPropertyOperations":12,"./LinkedValueUtils":25,"./ReactBrowserComponentMixin":30,"./ReactCompositeComponent":38,"./ReactDOM":41,"./ReactMount":67,"./invariant":134,"./merge":144}],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 ReactDOMOption
*/
"use strict";
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var warning = _dereq_("./warning");
// Store a reference to the <option> `ReactDOMComponent`.
var option = ReactDOM.option;
/**
* Implements an <option> native component that warns when `selected` is set.
*/
var ReactDOMOption = ReactCompositeComponent.createClass({
displayName: 'ReactDOMOption',
mixins: [ReactBrowserComponentMixin],
componentWillMount: function() {
// TODO (yungsters): Remove support for `selected` in <option>.
if ("production" !== "development") {
("production" !== "development" ? warning(
this.props.selected == null,
'Use the `defaultValue` or `value` props on <select> instead of ' +
'setting `selected` on <option>.'
) : null);
}
},
render: function() {
return option(this.props, this.props.children);
}
});
module.exports = ReactDOMOption;
},{"./ReactBrowserComponentMixin":30,"./ReactCompositeComponent":38,"./ReactDOM":41,"./warning":158}],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 ReactDOMSelect
*/
"use strict";
var AutoFocusMixin = _dereq_("./AutoFocusMixin");
var LinkedValueUtils = _dereq_("./LinkedValueUtils");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var merge = _dereq_("./merge");
// Store a reference to the <select> `ReactDOMComponent`.
var select = ReactDOM.select;
/**
* Validation function for `value` and `defaultValue`.
* @private
*/
function selectValueType(props, propName, componentName) {
if (props[propName] == null) {
return;
}
if (props.multiple) {
if (!Array.isArray(props[propName])) {
return new Error(
("The `" + propName + "` prop supplied to <select> must be an array if ") +
("`multiple` is true.")
);
}
} else {
if (Array.isArray(props[propName])) {
return new Error(
("The `" + propName + "` prop supplied to <select> must be a scalar ") +
("value if `multiple` is false.")
);
}
}
}
/**
* If `value` is supplied, updates <option> elements on mount and update.
* @param {ReactComponent} component Instance of ReactDOMSelect
* @param {?*} propValue For uncontrolled components, null/undefined. For
* controlled components, a string (or with `multiple`, a list of strings).
* @private
*/
function updateOptions(component, propValue) {
var multiple = component.props.multiple;
var value = propValue != null ? propValue : component.state.value;
var options = component.getDOMNode().options;
var selectedValue, i, l;
if (multiple) {
selectedValue = {};
for (i = 0, l = value.length; i < l; ++i) {
selectedValue['' + value[i]] = true;
}
} else {
selectedValue = '' + value;
}
for (i = 0, l = options.length; i < l; i++) {
var selected = multiple ?
selectedValue.hasOwnProperty(options[i].value) :
options[i].value === selectedValue;
if (selected !== options[i].selected) {
options[i].selected = selected;
}
}
}
/**
* Implements a <select> native component that allows optionally setting the
* props `value` and `defaultValue`. If `multiple` is false, the prop must be a
* string. If `multiple` is true, the prop must be an array of strings.
*
* If `value` is not supplied (or null/undefined), user actions that change the
* selected option will trigger updates to the rendered options.
*
* If it is supplied (and not null/undefined), the rendered options will not
* update in response to user actions. Instead, the `value` prop must change in
* order for the rendered options to update.
*
* If `defaultValue` is provided, any options with the supplied values will be
* selected.
*/
var ReactDOMSelect = ReactCompositeComponent.createClass({
displayName: 'ReactDOMSelect',
mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin],
propTypes: {
defaultValue: selectValueType,
value: selectValueType
},
getInitialState: function() {
return {value: this.props.defaultValue || (this.props.multiple ? [] : '')};
},
componentWillReceiveProps: function(nextProps) {
if (!this.props.multiple && nextProps.multiple) {
this.setState({value: [this.state.value]});
} else if (this.props.multiple && !nextProps.multiple) {
this.setState({value: this.state.value[0]});
}
},
shouldComponentUpdate: function() {
// Defer any updates to this component during the `onChange` handler.
return !this._isChanging;
},
render: function() {
// Clone `this.props` so we don't mutate the input.
var props = merge(this.props);
props.onChange = this._handleChange;
props.value = null;
return select(props, this.props.children);
},
componentDidMount: function() {
updateOptions(this, LinkedValueUtils.getValue(this));
},
componentDidUpdate: function(prevProps) {
var value = LinkedValueUtils.getValue(this);
var prevMultiple = !!prevProps.multiple;
var multiple = !!this.props.multiple;
if (value != null || prevMultiple !== multiple) {
updateOptions(this, value);
}
},
_handleChange: function(event) {
var returnValue;
var onChange = LinkedValueUtils.getOnChange(this);
if (onChange) {
this._isChanging = true;
returnValue = onChange.call(this, event);
this._isChanging = false;
}
var selectedValue;
if (this.props.multiple) {
selectedValue = [];
var options = event.target.options;
for (var i = 0, l = options.length; i < l; i++) {
if (options[i].selected) {
selectedValue.push(options[i].value);
}
}
} else {
selectedValue = event.target.value;
}
this.setState({value: selectedValue});
return returnValue;
}
});
module.exports = ReactDOMSelect;
},{"./AutoFocusMixin":1,"./LinkedValueUtils":25,"./ReactBrowserComponentMixin":30,"./ReactCompositeComponent":38,"./ReactDOM":41,"./merge":144}],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 ReactDOMSelection
*/
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var getNodeForCharacterOffset = _dereq_("./getNodeForCharacterOffset");
var getTextContentAccessor = _dereq_("./getTextContentAccessor");
/**
* While `isCollapsed` is available on the Selection object and `collapsed`
* is available on the Range object, IE11 sometimes gets them wrong.
* If the anchor/focus nodes and offsets are the same, the range is collapsed.
*/
function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) {
return anchorNode === focusNode && anchorOffset === focusOffset;
}
/**
* Get the appropriate anchor and focus node/offset pairs for IE.
*
* The catch here is that IE's selection API doesn't provide information
* about whether the selection is forward or backward, so we have to
* behave as though it's always forward.
*
* IE text differs from modern selection in that it behaves as though
* block elements end with a new line. This means character offsets will
* differ between the two APIs.
*
* @param {DOMElement} node
* @return {object}
*/
function getIEOffsets(node) {
var selection = document.selection;
var selectedRange = selection.createRange();
var selectedLength = selectedRange.text.length;
// Duplicate selection so we can move range without breaking user selection.
var fromStart = selectedRange.duplicate();
fromStart.moveToElementText(node);
fromStart.setEndPoint('EndToStart', selectedRange);
var startOffset = fromStart.text.length;
var endOffset = startOffset + selectedLength;
return {
start: startOffset,
end: endOffset
};
}
/**
* @param {DOMElement} node
* @return {?object}
*/
function getModernOffsets(node) {
var selection = window.getSelection();
if (selection.rangeCount === 0) {
return null;
}
var anchorNode = selection.anchorNode;
var anchorOffset = selection.anchorOffset;
var focusNode = selection.focusNode;
var focusOffset = selection.focusOffset;
var currentRange = selection.getRangeAt(0);
// If the node and offset values are the same, the selection is collapsed.
// `Selection.isCollapsed` is available natively, but IE sometimes gets
// this value wrong.
var isSelectionCollapsed = isCollapsed(
selection.anchorNode,
selection.anchorOffset,
selection.focusNode,
selection.focusOffset
);
var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length;
var tempRange = currentRange.cloneRange();
tempRange.selectNodeContents(node);
tempRange.setEnd(currentRange.startContainer, currentRange.startOffset);
var isTempRangeCollapsed = isCollapsed(
tempRange.startContainer,
tempRange.startOffset,
tempRange.endContainer,
tempRange.endOffset
);
var start = isTempRangeCollapsed ? 0 : tempRange.toString().length;
var end = start + rangeLength;
// Detect whether the selection is backward.
var detectionRange = document.createRange();
detectionRange.setStart(anchorNode, anchorOffset);
detectionRange.setEnd(focusNode, focusOffset);
var isBackward = detectionRange.collapsed;
detectionRange.detach();
return {
start: isBackward ? end : start,
end: isBackward ? start : end
};
}
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setIEOffsets(node, offsets) {
var range = document.selection.createRange().duplicate();
var start, end;
if (typeof offsets.end === 'undefined') {
start = offsets.start;
end = start;
} else if (offsets.start > offsets.end) {
start = offsets.end;
end = offsets.start;
} else {
start = offsets.start;
end = offsets.end;
}
range.moveToElementText(node);
range.moveStart('character', start);
range.setEndPoint('EndToStart', range);
range.moveEnd('character', end - start);
range.select();
}
/**
* In modern non-IE browsers, we can support both forward and backward
* selections.
*
* Note: IE10+ supports the Selection object, but it does not support
* the `extend` method, which means that even in modern IE, it's not possible
* to programatically create a backward selection. Thus, for all IE
* versions, we use the old IE API to create our selections.
*
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setModernOffsets(node, offsets) {
var selection = window.getSelection();
var length = node[getTextContentAccessor()].length;
var start = Math.min(offsets.start, length);
var end = typeof offsets.end === 'undefined' ?
start : Math.min(offsets.end, length);
// IE 11 uses modern selection, but doesn't support the extend method.
// Flip backward selections, so we can set with a single range.
if (!selection.extend && start > end) {
var temp = end;
end = start;
start = temp;
}
var startMarker = getNodeForCharacterOffset(node, start);
var endMarker = getNodeForCharacterOffset(node, end);
if (startMarker && endMarker) {
var range = document.createRange();
range.setStart(startMarker.node, startMarker.offset);
selection.removeAllRanges();
if (start > end) {
selection.addRange(range);
selection.extend(endMarker.node, endMarker.offset);
} else {
range.setEnd(endMarker.node, endMarker.offset);
selection.addRange(range);
}
range.detach();
}
}
var useIEOffsets = ExecutionEnvironment.canUseDOM && document.selection;
var ReactDOMSelection = {
/**
* @param {DOMElement} node
*/
getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets,
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets
};
module.exports = ReactDOMSelection;
},{"./ExecutionEnvironment":22,"./getNodeForCharacterOffset":127,"./getTextContentAccessor":129}],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 ReactDOMTextarea
*/
"use strict";
var AutoFocusMixin = _dereq_("./AutoFocusMixin");
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var LinkedValueUtils = _dereq_("./LinkedValueUtils");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var invariant = _dereq_("./invariant");
var merge = _dereq_("./merge");
var warning = _dereq_("./warning");
// Store a reference to the <textarea> `ReactDOMComponent`.
var textarea = ReactDOM.textarea;
/**
* Implements a <textarea> native component that allows setting `value`, and
* `defaultValue`. This differs from the traditional DOM API because value is
* usually set as PCDATA children.
*
* If `value` is not supplied (or null/undefined), user actions that affect the
* value will trigger updates to the element.
*
* If `value` is supplied (and not null/undefined), the rendered element will
* not trigger updates to the element. Instead, the `value` prop must change in
* order for the rendered element to be updated.
*
* The rendered element will be initialized with an empty value, the prop
* `defaultValue` if specified, or the children content (deprecated).
*/
var ReactDOMTextarea = ReactCompositeComponent.createClass({
displayName: 'ReactDOMTextarea',
mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin],
getInitialState: function() {
var defaultValue = this.props.defaultValue;
// TODO (yungsters): Remove support for children content in <textarea>.
var children = this.props.children;
if (children != null) {
if ("production" !== "development") {
("production" !== "development" ? warning(
false,
'Use the `defaultValue` or `value` props instead of setting ' +
'children on <textarea>.'
) : null);
}
("production" !== "development" ? invariant(
defaultValue == null,
'If you supply `defaultValue` on a <textarea>, do not pass children.'
) : invariant(defaultValue == null));
if (Array.isArray(children)) {
("production" !== "development" ? invariant(
children.length <= 1,
'<textarea> can only have at most one child.'
) : invariant(children.length <= 1));
children = children[0];
}
defaultValue = '' + children;
}
if (defaultValue == null) {
defaultValue = '';
}
var value = LinkedValueUtils.getValue(this);
return {
// We save the initial value so that `ReactDOMComponent` doesn't update
// `textContent` (unnecessary since we update value).
// The initial value can be a boolean or object so that's why it's
// forced to be a string.
initialValue: '' + (value != null ? value : defaultValue)
};
},
shouldComponentUpdate: function() {
// Defer any updates to this component during the `onChange` handler.
return !this._isChanging;
},
render: function() {
// Clone `this.props` so we don't mutate the input.
var props = merge(this.props);
("production" !== "development" ? invariant(
props.dangerouslySetInnerHTML == null,
'`dangerouslySetInnerHTML` does not make sense on <textarea>.'
) : invariant(props.dangerouslySetInnerHTML == null));
props.defaultValue = null;
props.value = null;
props.onChange = this._handleChange;
// Always set children to the same thing. In IE9, the selection range will
// get reset if `textContent` is mutated.
return textarea(props, this.state.initialValue);
},
componentDidUpdate: function(prevProps, prevState, prevContext) {
var value = LinkedValueUtils.getValue(this);
if (value != null) {
var rootNode = this.getDOMNode();
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value);
}
},
_handleChange: function(event) {
var returnValue;
var onChange = LinkedValueUtils.getOnChange(this);
if (onChange) {
this._isChanging = true;
returnValue = onChange.call(this, event);
this._isChanging = false;
}
this.setState({value: event.target.value});
return returnValue;
}
});
module.exports = ReactDOMTextarea;
},{"./AutoFocusMixin":1,"./DOMPropertyOperations":12,"./LinkedValueUtils":25,"./ReactBrowserComponentMixin":30,"./ReactCompositeComponent":38,"./ReactDOM":41,"./invariant":134,"./merge":144,"./warning":158}],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 ReactDefaultBatchingStrategy
*/
"use strict";
var ReactUpdates = _dereq_("./ReactUpdates");
var Transaction = _dereq_("./Transaction");
var emptyFunction = _dereq_("./emptyFunction");
var mixInto = _dereq_("./mixInto");
var RESET_BATCHED_UPDATES = {
initialize: emptyFunction,
close: function() {
ReactDefaultBatchingStrategy.isBatchingUpdates = false;
}
};
var FLUSH_BATCHED_UPDATES = {
initialize: emptyFunction,
close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates)
};
var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES];
function ReactDefaultBatchingStrategyTransaction() {
this.reinitializeTransaction();
}
mixInto(ReactDefaultBatchingStrategyTransaction, Transaction.Mixin);
mixInto(ReactDefaultBatchingStrategyTransaction, {
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS;
}
});
var transaction = new ReactDefaultBatchingStrategyTransaction();
var ReactDefaultBatchingStrategy = {
isBatchingUpdates: false,
/**
* Call the provided function in a context within which calls to `setState`
* and friends are batched such that components aren't updated unnecessarily.
*/
batchedUpdates: function(callback, a, b) {
var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
ReactDefaultBatchingStrategy.isBatchingUpdates = true;
// The code is written this way to avoid extra allocations
if (alreadyBatchingUpdates) {
callback(a, b);
} else {
transaction.perform(callback, null, a, b);
}
}
};
module.exports = ReactDefaultBatchingStrategy;
},{"./ReactUpdates":87,"./Transaction":104,"./emptyFunction":116,"./mixInto":147}],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 ReactDefaultInjection
*/
"use strict";
var BeforeInputEventPlugin = _dereq_("./BeforeInputEventPlugin");
var ChangeEventPlugin = _dereq_("./ChangeEventPlugin");
var ClientReactRootIndex = _dereq_("./ClientReactRootIndex");
var CompositionEventPlugin = _dereq_("./CompositionEventPlugin");
var DefaultEventPluginOrder = _dereq_("./DefaultEventPluginOrder");
var EnterLeaveEventPlugin = _dereq_("./EnterLeaveEventPlugin");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var HTMLDOMPropertyConfig = _dereq_("./HTMLDOMPropertyConfig");
var MobileSafariClickEventPlugin = _dereq_("./MobileSafariClickEventPlugin");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactComponentBrowserEnvironment =
_dereq_("./ReactComponentBrowserEnvironment");
var ReactDefaultBatchingStrategy = _dereq_("./ReactDefaultBatchingStrategy");
var ReactDOM = _dereq_("./ReactDOM");
var ReactDOMButton = _dereq_("./ReactDOMButton");
var ReactDOMForm = _dereq_("./ReactDOMForm");
var ReactDOMImg = _dereq_("./ReactDOMImg");
var ReactDOMInput = _dereq_("./ReactDOMInput");
var ReactDOMOption = _dereq_("./ReactDOMOption");
var ReactDOMSelect = _dereq_("./ReactDOMSelect");
var ReactDOMTextarea = _dereq_("./ReactDOMTextarea");
var ReactEventListener = _dereq_("./ReactEventListener");
var ReactInjection = _dereq_("./ReactInjection");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactMount = _dereq_("./ReactMount");
var SelectEventPlugin = _dereq_("./SelectEventPlugin");
var ServerReactRootIndex = _dereq_("./ServerReactRootIndex");
var SimpleEventPlugin = _dereq_("./SimpleEventPlugin");
var SVGDOMPropertyConfig = _dereq_("./SVGDOMPropertyConfig");
var createFullPageComponent = _dereq_("./createFullPageComponent");
function inject() {
ReactInjection.EventEmitter.injectReactEventListener(
ReactEventListener
);
/**
* Inject modules for resolving DOM hierarchy and plugin ordering.
*/
ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder);
ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles);
ReactInjection.EventPluginHub.injectMount(ReactMount);
/**
* Some important event plugins included by default (without having to require
* them).
*/
ReactInjection.EventPluginHub.injectEventPluginsByName({
SimpleEventPlugin: SimpleEventPlugin,
EnterLeaveEventPlugin: EnterLeaveEventPlugin,
ChangeEventPlugin: ChangeEventPlugin,
CompositionEventPlugin: CompositionEventPlugin,
MobileSafariClickEventPlugin: MobileSafariClickEventPlugin,
SelectEventPlugin: SelectEventPlugin,
BeforeInputEventPlugin: BeforeInputEventPlugin
});
ReactInjection.DOM.injectComponentClasses({
button: ReactDOMButton,
form: ReactDOMForm,
img: ReactDOMImg,
input: ReactDOMInput,
option: ReactDOMOption,
select: ReactDOMSelect,
textarea: ReactDOMTextarea,
html: createFullPageComponent(ReactDOM.html),
head: createFullPageComponent(ReactDOM.head),
body: createFullPageComponent(ReactDOM.body)
});
// This needs to happen after createFullPageComponent() otherwise the mixin
// gets double injected.
ReactInjection.CompositeComponent.injectMixin(ReactBrowserComponentMixin);
ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig);
ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig);
ReactInjection.EmptyComponent.injectEmptyComponent(ReactDOM.noscript);
ReactInjection.Updates.injectReconcileTransaction(
ReactComponentBrowserEnvironment.ReactReconcileTransaction
);
ReactInjection.Updates.injectBatchingStrategy(
ReactDefaultBatchingStrategy
);
ReactInjection.RootIndex.injectCreateReactRootIndex(
ExecutionEnvironment.canUseDOM ?
ClientReactRootIndex.createReactRootIndex :
ServerReactRootIndex.createReactRootIndex
);
ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment);
if ("production" !== "development") {
var url = (ExecutionEnvironment.canUseDOM && window.location.href) || '';
if ((/[?&]react_perf\b/).test(url)) {
var ReactDefaultPerf = _dereq_("./ReactDefaultPerf");
ReactDefaultPerf.start();
}
}
}
module.exports = {
inject: inject
};
},{"./BeforeInputEventPlugin":2,"./ChangeEventPlugin":7,"./ClientReactRootIndex":8,"./CompositionEventPlugin":9,"./DefaultEventPluginOrder":14,"./EnterLeaveEventPlugin":15,"./ExecutionEnvironment":22,"./HTMLDOMPropertyConfig":23,"./MobileSafariClickEventPlugin":27,"./ReactBrowserComponentMixin":30,"./ReactComponentBrowserEnvironment":36,"./ReactDOM":41,"./ReactDOMButton":42,"./ReactDOMForm":44,"./ReactDOMImg":46,"./ReactDOMInput":47,"./ReactDOMOption":48,"./ReactDOMSelect":49,"./ReactDOMTextarea":51,"./ReactDefaultBatchingStrategy":52,"./ReactDefaultPerf":54,"./ReactEventListener":61,"./ReactInjection":62,"./ReactInstanceHandles":64,"./ReactMount":67,"./SVGDOMPropertyConfig":89,"./SelectEventPlugin":90,"./ServerReactRootIndex":91,"./SimpleEventPlugin":92,"./createFullPageComponent":112}],54:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactDefaultPerf
* @typechecks static-only
*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var ReactDefaultPerfAnalysis = _dereq_("./ReactDefaultPerfAnalysis");
var ReactMount = _dereq_("./ReactMount");
var ReactPerf = _dereq_("./ReactPerf");
var performanceNow = _dereq_("./performanceNow");
function roundFloat(val) {
return Math.floor(val * 100) / 100;
}
function addValue(obj, key, val) {
obj[key] = (obj[key] || 0) + val;
}
var ReactDefaultPerf = {
_allMeasurements: [], // last item in the list is the current one
_mountStack: [0],
_injected: false,
start: function() {
if (!ReactDefaultPerf._injected) {
ReactPerf.injection.injectMeasure(ReactDefaultPerf.measure);
}
ReactDefaultPerf._allMeasurements.length = 0;
ReactPerf.enableMeasure = true;
},
stop: function() {
ReactPerf.enableMeasure = false;
},
getLastMeasurements: function() {
return ReactDefaultPerf._allMeasurements;
},
printExclusive: function(measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getExclusiveSummary(measurements);
console.table(summary.map(function(item) {
return {
'Component class name': item.componentName,
'Total inclusive time (ms)': roundFloat(item.inclusive),
'Exclusive mount time (ms)': roundFloat(item.exclusive),
'Exclusive render time (ms)': roundFloat(item.render),
'Mount time per instance (ms)': roundFloat(item.exclusive / item.count),
'Render time per instance (ms)': roundFloat(item.render / item.count),
'Instances': item.count
};
}));
// TODO: ReactDefaultPerfAnalysis.getTotalTime() does not return the correct
// number.
},
printInclusive: function(measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements);
console.table(summary.map(function(item) {
return {
'Owner > component': item.componentName,
'Inclusive time (ms)': roundFloat(item.time),
'Instances': item.count
};
}));
console.log(
'Total time:',
ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'
);
},
printWasted: function(measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(
measurements,
true
);
console.table(summary.map(function(item) {
return {
'Owner > component': item.componentName,
'Wasted time (ms)': item.time,
'Instances': item.count
};
}));
console.log(
'Total time:',
ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'
);
},
printDOM: function(measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getDOMSummary(measurements);
console.table(summary.map(function(item) {
var result = {};
result[DOMProperty.ID_ATTRIBUTE_NAME] = item.id;
result['type'] = item.type;
result['args'] = JSON.stringify(item.args);
return result;
}));
console.log(
'Total time:',
ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'
);
},
_recordWrite: function(id, fnName, totalTime, args) {
// TODO: totalTime isn't that useful since it doesn't count paints/reflows
var writes =
ReactDefaultPerf
._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1]
.writes;
writes[id] = writes[id] || [];
writes[id].push({
type: fnName,
time: totalTime,
args: args
});
},
measure: function(moduleName, fnName, func) {
return function() {var args=Array.prototype.slice.call(arguments,0);
var totalTime;
var rv;
var start;
if (fnName === '_renderNewRootComponent' ||
fnName === 'flushBatchedUpdates') {
// A "measurement" is a set of metrics recorded for each flush. We want
// to group the metrics for a given flush together so we can look at the
// components that rendered and the DOM operations that actually
// happened to determine the amount of "wasted work" performed.
ReactDefaultPerf._allMeasurements.push({
exclusive: {},
inclusive: {},
render: {},
counts: {},
writes: {},
displayNames: {},
totalTime: 0
});
start = performanceNow();
rv = func.apply(this, args);
ReactDefaultPerf._allMeasurements[
ReactDefaultPerf._allMeasurements.length - 1
].totalTime = performanceNow() - start;
return rv;
} else if (moduleName === 'ReactDOMIDOperations' ||
moduleName === 'ReactComponentBrowserEnvironment') {
start = performanceNow();
rv = func.apply(this, args);
totalTime = performanceNow() - start;
if (fnName === 'mountImageIntoNode') {
var mountID = ReactMount.getID(args[1]);
ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]);
} else if (fnName === 'dangerouslyProcessChildrenUpdates') {
// special format
args[0].forEach(function(update) {
var writeArgs = {};
if (update.fromIndex !== null) {
writeArgs.fromIndex = update.fromIndex;
}
if (update.toIndex !== null) {
writeArgs.toIndex = update.toIndex;
}
if (update.textContent !== null) {
writeArgs.textContent = update.textContent;
}
if (update.markupIndex !== null) {
writeArgs.markup = args[1][update.markupIndex];
}
ReactDefaultPerf._recordWrite(
update.parentID,
update.type,
totalTime,
writeArgs
);
});
} else {
// basic format
ReactDefaultPerf._recordWrite(
args[0],
fnName,
totalTime,
Array.prototype.slice.call(args, 1)
);
}
return rv;
} else if (moduleName === 'ReactCompositeComponent' && (
fnName === 'mountComponent' ||
fnName === 'updateComponent' || // TODO: receiveComponent()?
fnName === '_renderValidatedComponent')) {
var rootNodeID = fnName === 'mountComponent' ?
args[0] :
this._rootNodeID;
var isRender = fnName === '_renderValidatedComponent';
var isMount = fnName === 'mountComponent';
var mountStack = ReactDefaultPerf._mountStack;
var entry = ReactDefaultPerf._allMeasurements[
ReactDefaultPerf._allMeasurements.length - 1
];
if (isRender) {
addValue(entry.counts, rootNodeID, 1);
} else if (isMount) {
mountStack.push(0);
}
start = performanceNow();
rv = func.apply(this, args);
totalTime = performanceNow() - start;
if (isRender) {
addValue(entry.render, rootNodeID, totalTime);
} else if (isMount) {
var subMountTime = mountStack.pop();
mountStack[mountStack.length - 1] += totalTime;
addValue(entry.exclusive, rootNodeID, totalTime - subMountTime);
addValue(entry.inclusive, rootNodeID, totalTime);
} else {
addValue(entry.inclusive, rootNodeID, totalTime);
}
entry.displayNames[rootNodeID] = {
current: this.constructor.displayName,
owner: this._owner ? this._owner.constructor.displayName : '<root>'
};
return rv;
} else {
return func.apply(this, args);
}
};
}
};
module.exports = ReactDefaultPerf;
},{"./DOMProperty":11,"./ReactDefaultPerfAnalysis":55,"./ReactMount":67,"./ReactPerf":71,"./performanceNow":151}],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 ReactDefaultPerfAnalysis
*/
var merge = _dereq_("./merge");
// Don't try to save users less than 1.2ms (a number I made up)
var DONT_CARE_THRESHOLD = 1.2;
var DOM_OPERATION_TYPES = {
'mountImageIntoNode': 'set innerHTML',
INSERT_MARKUP: 'set innerHTML',
MOVE_EXISTING: 'move',
REMOVE_NODE: 'remove',
TEXT_CONTENT: 'set textContent',
'updatePropertyByID': 'update attribute',
'deletePropertyByID': 'delete attribute',
'updateStylesByID': 'update styles',
'updateInnerHTMLByID': 'set innerHTML',
'dangerouslyReplaceNodeWithMarkupByID': 'replace'
};
function getTotalTime(measurements) {
// TODO: return number of DOM ops? could be misleading.
// TODO: measure dropped frames after reconcile?
// TODO: log total time of each reconcile and the top-level component
// class that triggered it.
var totalTime = 0;
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
totalTime += measurement.totalTime;
}
return totalTime;
}
function getDOMSummary(measurements) {
var items = [];
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
var id;
for (id in measurement.writes) {
measurement.writes[id].forEach(function(write) {
items.push({
id: id,
type: DOM_OPERATION_TYPES[write.type] || write.type,
args: write.args
});
});
}
}
return items;
}
function getExclusiveSummary(measurements) {
var candidates = {};
var displayName;
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
var allIDs = merge(measurement.exclusive, measurement.inclusive);
for (var id in allIDs) {
displayName = measurement.displayNames[id].current;
candidates[displayName] = candidates[displayName] || {
componentName: displayName,
inclusive: 0,
exclusive: 0,
render: 0,
count: 0
};
if (measurement.render[id]) {
candidates[displayName].render += measurement.render[id];
}
if (measurement.exclusive[id]) {
candidates[displayName].exclusive += measurement.exclusive[id];
}
if (measurement.inclusive[id]) {
candidates[displayName].inclusive += measurement.inclusive[id];
}
if (measurement.counts[id]) {
candidates[displayName].count += measurement.counts[id];
}
}
}
// Now make a sorted array with the results.
var arr = [];
for (displayName in candidates) {
if (candidates[displayName].exclusive >= DONT_CARE_THRESHOLD) {
arr.push(candidates[displayName]);
}
}
arr.sort(function(a, b) {
return b.exclusive - a.exclusive;
});
return arr;
}
function getInclusiveSummary(measurements, onlyClean) {
var candidates = {};
var inclusiveKey;
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
var allIDs = merge(measurement.exclusive, measurement.inclusive);
var cleanComponents;
if (onlyClean) {
cleanComponents = getUnchangedComponents(measurement);
}
for (var id in allIDs) {
if (onlyClean && !cleanComponents[id]) {
continue;
}
var displayName = measurement.displayNames[id];
// Inclusive time is not useful for many components without knowing where
// they are instantiated. So we aggregate inclusive time with both the
// owner and current displayName as the key.
inclusiveKey = displayName.owner + ' > ' + displayName.current;
candidates[inclusiveKey] = candidates[inclusiveKey] || {
componentName: inclusiveKey,
time: 0,
count: 0
};
if (measurement.inclusive[id]) {
candidates[inclusiveKey].time += measurement.inclusive[id];
}
if (measurement.counts[id]) {
candidates[inclusiveKey].count += measurement.counts[id];
}
}
}
// Now make a sorted array with the results.
var arr = [];
for (inclusiveKey in candidates) {
if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) {
arr.push(candidates[inclusiveKey]);
}
}
arr.sort(function(a, b) {
return b.time - a.time;
});
return arr;
}
function getUnchangedComponents(measurement) {
// For a given reconcile, look at which components did not actually
// render anything to the DOM and return a mapping of their ID to
// the amount of time it took to render the entire subtree.
var cleanComponents = {};
var dirtyLeafIDs = Object.keys(measurement.writes);
var allIDs = merge(measurement.exclusive, measurement.inclusive);
for (var id in allIDs) {
var isDirty = false;
// For each component that rendered, see if a component that triggerd
// a DOM op is in its subtree.
for (var i = 0; i < dirtyLeafIDs.length; i++) {
if (dirtyLeafIDs[i].indexOf(id) === 0) {
isDirty = true;
break;
}
}
if (!isDirty && measurement.counts[id] > 0) {
cleanComponents[id] = true;
}
}
return cleanComponents;
}
var ReactDefaultPerfAnalysis = {
getExclusiveSummary: getExclusiveSummary,
getInclusiveSummary: getInclusiveSummary,
getDOMSummary: getDOMSummary,
getTotalTime: getTotalTime
};
module.exports = ReactDefaultPerfAnalysis;
},{"./merge":144}],56:[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" !== "development" ? 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" !== "development") {
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" !== "development") {
// 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" !== "development") {
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":39,"./ReactCurrentOwner":40,"./merge":144,"./warning":158}],57:[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 ReactDescriptorValidator
*/
/**
* ReactDescriptorValidator provides a wrapper around a descriptor factory
* which validates the props passed to the descriptor. This is intended to be
* used only in DEV and could be replaced by a static type checker for languages
* that support it.
*/
"use strict";
var ReactDescriptor = _dereq_("./ReactDescriptor");
var ReactPropTypeLocations = _dereq_("./ReactPropTypeLocations");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var monitorCodeUse = _dereq_("./monitorCodeUse");
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/
var ownerHasKeyUseWarning = {
'react_key_warning': {},
'react_numeric_key_warning': {}
};
var ownerHasMonitoredObjectMap = {};
var loggedTypeFailures = {};
var NUMERIC_PROPERTY_REGEX = /^\d+$/;
/**
* Gets the current owner's displayName for use in warnings.
*
* @internal
* @return {?string} Display name or undefined
*/
function getCurrentOwnerDisplayName() {
var current = ReactCurrentOwner.current;
return current && current.constructor.displayName || undefined;
}
/**
* Warn if the component doesn't have an explicit key assigned to it.
* This component is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it.
*
* @internal
* @param {ReactComponent} component Component that requires a key.
* @param {*} parentType component's parent's type.
*/
function validateExplicitKey(component, parentType) {
if (component._store.validated || component.props.key != null) {
return;
}
component._store.validated = true;
warnAndMonitorForKeyUse(
'react_key_warning',
'Each child in an array should have a unique "key" prop.',
component,
parentType
);
}
/**
* Warn if the key is being defined as an object property but has an incorrect
* value.
*
* @internal
* @param {string} name Property name of the key.
* @param {ReactComponent} component Component that requires a key.
* @param {*} parentType component's parent's type.
*/
function validatePropertyKey(name, component, parentType) {
if (!NUMERIC_PROPERTY_REGEX.test(name)) {
return;
}
warnAndMonitorForKeyUse(
'react_numeric_key_warning',
'Child objects should have non-numeric keys so ordering is preserved.',
component,
parentType
);
}
/**
* Shared warning and monitoring code for the key warnings.
*
* @internal
* @param {string} warningID The id used when logging.
* @param {string} message The base warning that gets output.
* @param {ReactComponent} component Component that requires a key.
* @param {*} parentType component's parent's type.
*/
function warnAndMonitorForKeyUse(warningID, message, component, parentType) {
var ownerName = getCurrentOwnerDisplayName();
var parentName = parentType.displayName;
var useName = ownerName || parentName;
var memoizer = ownerHasKeyUseWarning[warningID];
if (memoizer.hasOwnProperty(useName)) {
return;
}
memoizer[useName] = true;
message += ownerName ?
(" Check the render method of " + ownerName + ".") :
(" Check the renderComponent call using <" + parentName + ">.");
// Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
var childOwnerName = null;
if (component._owner && component._owner !== ReactCurrentOwner.current) {
// Name of the component that originally created this child.
childOwnerName = component._owner.constructor.displayName;
message += (" It was passed a child from " + childOwnerName + ".");
}
message += ' See http://fb.me/react-warning-keys for more information.';
monitorCodeUse(warningID, {
component: useName,
componentOwner: childOwnerName
});
console.warn(message);
}
/**
* Log that we're using an object map. We're considering deprecating this
* feature and replace it with proper Map and ImmutableMap data structures.
*
* @internal
*/
function monitorUseOfObjectMap() {
var currentName = getCurrentOwnerDisplayName() || '';
if (ownerHasMonitoredObjectMap.hasOwnProperty(currentName)) {
return;
}
ownerHasMonitoredObjectMap[currentName] = true;
monitorCodeUse('react_object_map_children');
}
/**
* Ensure that every component either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {*} component Statically passed child of any type.
* @param {*} parentType component's parent's type.
* @return {boolean}
*/
function validateChildKeys(component, parentType) {
if (Array.isArray(component)) {
for (var i = 0; i < component.length; i++) {
var child = component[i];
if (ReactDescriptor.isValidDescriptor(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (ReactDescriptor.isValidDescriptor(component)) {
// This component was passed in a valid location.
component._store.validated = true;
} else if (component && typeof component === 'object') {
monitorUseOfObjectMap();
for (var name in component) {
validatePropertyKey(name, component[name], parentType);
}
}
}
/**
* Assert that the props are valid
*
* @param {string} componentName Name of the component for error messages.
* @param {object} propTypes Map of prop name to a ReactPropType
* @param {object} props
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
function checkPropTypes(componentName, propTypes, props, location) {
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
error = propTypes[propName](props, propName, componentName, location);
} catch (ex) {
error = ex;
}
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
// This will soon use the warning module
monitorCodeUse(
'react_failed_descriptor_type_check',
{ message: error.message }
);
}
}
}
}
var ReactDescriptorValidator = {
/**
* Wraps a descriptor factory function in another function which validates
* the props and context of the descriptor and warns about any failed type
* checks.
*
* @param {function} factory The original descriptor factory
* @param {object?} propTypes A prop type definition set
* @param {object?} contextTypes A context type definition set
* @return {object} The component descriptor, which may be invalid.
* @private
*/
createFactory: function(factory, propTypes, contextTypes) {
var validatedFactory = function(props, children) {
var descriptor = factory.apply(this, arguments);
for (var i = 1; i < arguments.length; i++) {
validateChildKeys(arguments[i], descriptor.type);
}
var name = descriptor.type.displayName;
if (propTypes) {
checkPropTypes(
name,
propTypes,
descriptor.props,
ReactPropTypeLocations.prop
);
}
if (contextTypes) {
checkPropTypes(
name,
contextTypes,
descriptor._context,
ReactPropTypeLocations.context
);
}
return descriptor;
};
validatedFactory.prototype = factory.prototype;
validatedFactory.type = factory.type;
// Copy static properties
for (var key in factory) {
if (factory.hasOwnProperty(key)) {
validatedFactory[key] = factory[key];
}
}
return validatedFactory;
}
};
module.exports = ReactDescriptorValidator;
},{"./ReactCurrentOwner":40,"./ReactDescriptor":56,"./ReactPropTypeLocations":74,"./monitorCodeUse":148}],58:[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 ReactEmptyComponent
*/
"use strict";
var invariant = _dereq_("./invariant");
var component;
// This registry keeps track of the React IDs of the components that rendered to
// `null` (in reality a placeholder such as `noscript`)
var nullComponentIdsRegistry = {};
var ReactEmptyComponentInjection = {
injectEmptyComponent: function(emptyComponent) {
component = emptyComponent;
}
};
/**
* @return {ReactComponent} component The injected empty component.
*/
function getEmptyComponent() {
("production" !== "development" ? invariant(
component,
'Trying to return null from a render, but no null placeholder component ' +
'was injected.'
) : invariant(component));
return component();
}
/**
* Mark the component as having rendered to null.
* @param {string} id Component's `_rootNodeID`.
*/
function registerNullComponentID(id) {
nullComponentIdsRegistry[id] = true;
}
/**
* Unmark the component as having rendered to null: it renders to something now.
* @param {string} id Component's `_rootNodeID`.
*/
function deregisterNullComponentID(id) {
delete nullComponentIdsRegistry[id];
}
/**
* @param {string} id Component's `_rootNodeID`.
* @return {boolean} True if the component is rendered to null.
*/
function isNullComponentID(id) {
return nullComponentIdsRegistry[id];
}
var ReactEmptyComponent = {
deregisterNullComponentID: deregisterNullComponentID,
getEmptyComponent: getEmptyComponent,
injection: ReactEmptyComponentInjection,
isNullComponentID: isNullComponentID,
registerNullComponentID: registerNullComponentID
};
module.exports = ReactEmptyComponent;
},{"./invariant":134}],59:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactErrorUtils
* @typechecks
*/
"use strict";
var ReactErrorUtils = {
/**
* Creates a guarded version of a function. This is supposed to make debugging
* of event handlers easier. To aid debugging with the browser's debugger,
* this currently simply returns the original function.
*
* @param {function} func Function to be executed
* @param {string} name The name of the guard
* @return {function}
*/
guard: function(func, name) {
return func;
}
};
module.exports = ReactErrorUtils;
},{}],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 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":18}],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 ReactEventListener
* @typechecks static-only
*/
"use strict";
var EventListener = _dereq_("./EventListener");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var PooledClass = _dereq_("./PooledClass");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactMount = _dereq_("./ReactMount");
var ReactUpdates = _dereq_("./ReactUpdates");
var getEventTarget = _dereq_("./getEventTarget");
var getUnboundedScrollPosition = _dereq_("./getUnboundedScrollPosition");
var mixInto = _dereq_("./mixInto");
/**
* Finds the parent React component of `node`.
*
* @param {*} node
* @return {?DOMEventTarget} Parent container, or `null` if the specified node
* is not nested.
*/
function findParent(node) {
// TODO: It may be a good idea to cache this to prevent unnecessary DOM
// traversal, but caching is difficult to do correctly without using a
// mutation observer to listen for all DOM changes.
var nodeID = ReactMount.getID(node);
var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID);
var container = ReactMount.findReactContainerForID(rootID);
var parent = ReactMount.getFirstReactDOM(container);
return parent;
}
// Used to store ancestor hierarchy in top level callback
function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) {
this.topLevelType = topLevelType;
this.nativeEvent = nativeEvent;
this.ancestors = [];
}
mixInto(TopLevelCallbackBookKeeping, {
destructor: function() {
this.topLevelType = null;
this.nativeEvent = null;
this.ancestors.length = 0;
}
});
PooledClass.addPoolingTo(
TopLevelCallbackBookKeeping,
PooledClass.twoArgumentPooler
);
function handleTopLevelImpl(bookKeeping) {
var topLevelTarget = ReactMount.getFirstReactDOM(
getEventTarget(bookKeeping.nativeEvent)
) || window;
// Loop through the hierarchy, in case there's any nested components.
// It's important that we build the array of ancestors before calling any
// event handlers, because event handlers can modify the DOM, leading to
// inconsistencies with ReactMount's node cache. See #1105.
var ancestor = topLevelTarget;
while (ancestor) {
bookKeeping.ancestors.push(ancestor);
ancestor = findParent(ancestor);
}
for (var i = 0, l = bookKeeping.ancestors.length; i < l; i++) {
topLevelTarget = bookKeeping.ancestors[i];
var topLevelTargetID = ReactMount.getID(topLevelTarget) || '';
ReactEventListener._handleTopLevel(
bookKeeping.topLevelType,
topLevelTarget,
topLevelTargetID,
bookKeeping.nativeEvent
);
}
}
function scrollValueMonitor(cb) {
var scrollPosition = getUnboundedScrollPosition(window);
cb(scrollPosition);
}
var ReactEventListener = {
_enabled: true,
_handleTopLevel: null,
WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null,
setHandleTopLevel: function(handleTopLevel) {
ReactEventListener._handleTopLevel = handleTopLevel;
},
setEnabled: function(enabled) {
ReactEventListener._enabled = !!enabled;
},
isEnabled: function() {
return ReactEventListener._enabled;
},
/**
* Traps top-level events by using event bubbling.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {object} handle Element on which to attach listener.
* @return {object} An object with a remove function which will forcefully
* remove the listener.
* @internal
*/
trapBubbledEvent: function(topLevelType, handlerBaseName, handle) {
var element = handle;
if (!element) {
return;
}
return EventListener.listen(
element,
handlerBaseName,
ReactEventListener.dispatchEvent.bind(null, topLevelType)
);
},
/**
* Traps a top-level event by using event capturing.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {object} handle Element on which to attach listener.
* @return {object} An object with a remove function which will forcefully
* remove the listener.
* @internal
*/
trapCapturedEvent: function(topLevelType, handlerBaseName, handle) {
var element = handle;
if (!element) {
return;
}
return EventListener.capture(
element,
handlerBaseName,
ReactEventListener.dispatchEvent.bind(null, topLevelType)
);
},
monitorScrollValue: function(refresh) {
var callback = scrollValueMonitor.bind(null, refresh);
EventListener.listen(window, 'scroll', callback);
EventListener.listen(window, 'resize', callback);
},
dispatchEvent: function(topLevelType, nativeEvent) {
if (!ReactEventListener._enabled) {
return;
}
var bookKeeping = TopLevelCallbackBookKeeping.getPooled(
topLevelType,
nativeEvent
);
try {
// Event queue being processed in the same cycle allows
// `preventDefault`.
ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping);
} finally {
TopLevelCallbackBookKeeping.release(bookKeeping);
}
}
};
module.exports = ReactEventListener;
},{"./EventListener":17,"./ExecutionEnvironment":22,"./PooledClass":28,"./ReactInstanceHandles":64,"./ReactMount":67,"./ReactUpdates":87,"./getEventTarget":125,"./getUnboundedScrollPosition":130,"./mixInto":147}],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 ReactInjection
*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var EventPluginHub = _dereq_("./EventPluginHub");
var ReactComponent = _dereq_("./ReactComponent");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var ReactEmptyComponent = _dereq_("./ReactEmptyComponent");
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var ReactPerf = _dereq_("./ReactPerf");
var ReactRootIndex = _dereq_("./ReactRootIndex");
var ReactUpdates = _dereq_("./ReactUpdates");
var ReactInjection = {
Component: ReactComponent.injection,
CompositeComponent: ReactCompositeComponent.injection,
DOMProperty: DOMProperty.injection,
EmptyComponent: ReactEmptyComponent.injection,
EventPluginHub: EventPluginHub.injection,
DOM: ReactDOM.injection,
EventEmitter: ReactBrowserEventEmitter.injection,
Perf: ReactPerf.injection,
RootIndex: ReactRootIndex.injection,
Updates: ReactUpdates.injection
};
module.exports = ReactInjection;
},{"./DOMProperty":11,"./EventPluginHub":18,"./ReactBrowserEventEmitter":31,"./ReactComponent":35,"./ReactCompositeComponent":38,"./ReactDOM":41,"./ReactEmptyComponent":58,"./ReactPerf":71,"./ReactRootIndex":78,"./ReactUpdates":87}],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 ReactInputSelection
*/
"use strict";
var ReactDOMSelection = _dereq_("./ReactDOMSelection");
var containsNode = _dereq_("./containsNode");
var focusNode = _dereq_("./focusNode");
var getActiveElement = _dereq_("./getActiveElement");
function isInDocument(node) {
return containsNode(document.documentElement, node);
}
/**
* @ReactInputSelection: React input selection module. Based on Selection.js,
* but modified to be suitable for react and has a couple of bug fixes (doesn't
* assume buttons have range selections allowed).
* Input selection module for React.
*/
var ReactInputSelection = {
hasSelectionCapabilities: function(elem) {
return elem && (
(elem.nodeName === 'INPUT' && elem.type === 'text') ||
elem.nodeName === 'TEXTAREA' ||
elem.contentEditable === 'true'
);
},
getSelectionInformation: function() {
var focusedElem = getActiveElement();
return {
focusedElem: focusedElem,
selectionRange:
ReactInputSelection.hasSelectionCapabilities(focusedElem) ?
ReactInputSelection.getSelection(focusedElem) :
null
};
},
/**
* @restoreSelection: If any selection information was potentially lost,
* restore it. This is useful when performing operations that could remove dom
* nodes and place them back in, resulting in focus being lost.
*/
restoreSelection: function(priorSelectionInformation) {
var curFocusedElem = getActiveElement();
var priorFocusedElem = priorSelectionInformation.focusedElem;
var priorSelectionRange = priorSelectionInformation.selectionRange;
if (curFocusedElem !== priorFocusedElem &&
isInDocument(priorFocusedElem)) {
if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) {
ReactInputSelection.setSelection(
priorFocusedElem,
priorSelectionRange
);
}
focusNode(priorFocusedElem);
}
},
/**
* @getSelection: Gets the selection bounds of a focused textarea, input or
* contentEditable node.
* -@input: Look up selection bounds of this input
* -@return {start: selectionStart, end: selectionEnd}
*/
getSelection: function(input) {
var selection;
if ('selectionStart' in input) {
// Modern browser with input or textarea.
selection = {
start: input.selectionStart,
end: input.selectionEnd
};
} else if (document.selection && input.nodeName === 'INPUT') {
// IE8 input.
var range = document.selection.createRange();
// There can only be one selection per document in IE, so it must
// be in our element.
if (range.parentElement() === input) {
selection = {
start: -range.moveStart('character', -input.value.length),
end: -range.moveEnd('character', -input.value.length)
};
}
} else {
// Content editable or old IE textarea.
selection = ReactDOMSelection.getOffsets(input);
}
return selection || {start: 0, end: 0};
},
/**
* @setSelection: Sets the selection bounds of a textarea or input and focuses
* the input.
* -@input Set selection bounds of this input or textarea
* -@offsets Object of same form that is returned from get*
*/
setSelection: function(input, offsets) {
var start = offsets.start;
var end = offsets.end;
if (typeof end === 'undefined') {
end = start;
}
if ('selectionStart' in input) {
input.selectionStart = start;
input.selectionEnd = Math.min(end, input.value.length);
} else if (document.selection && input.nodeName === 'INPUT') {
var range = input.createTextRange();
range.collapse(true);
range.moveStart('character', start);
range.moveEnd('character', end - start);
range.select();
} else {
ReactDOMSelection.setOffsets(input, offsets);
}
}
};
module.exports = ReactInputSelection;
},{"./ReactDOMSelection":50,"./containsNode":109,"./focusNode":120,"./getActiveElement":122}],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 ReactInstanceHandles
* @typechecks static-only
*/
"use strict";
var ReactRootIndex = _dereq_("./ReactRootIndex");
var invariant = _dereq_("./invariant");
var SEPARATOR = '.';
var SEPARATOR_LENGTH = SEPARATOR.length;
/**
* Maximum depth of traversals before we consider the possibility of a bad ID.
*/
var MAX_TREE_DEPTH = 100;
/**
* Creates a DOM ID prefix to use when mounting React components.
*
* @param {number} index A unique integer
* @return {string} React root ID.
* @internal
*/
function getReactRootIDString(index) {
return SEPARATOR + index.toString(36);
}
/**
* Checks if a character in the supplied ID is a separator or the end.
*
* @param {string} id A React DOM ID.
* @param {number} index Index of the character to check.
* @return {boolean} True if the character is a separator or end of the ID.
* @private
*/
function isBoundary(id, index) {
return id.charAt(index) === SEPARATOR || index === id.length;
}
/**
* Checks if the supplied string is a valid React DOM ID.
*
* @param {string} id A React DOM ID, maybe.
* @return {boolean} True if the string is a valid React DOM ID.
* @private
*/
function isValidID(id) {
return id === '' || (
id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR
);
}
/**
* Checks if the first ID is an ancestor of or equal to the second ID.
*
* @param {string} ancestorID
* @param {string} descendantID
* @return {boolean} True if `ancestorID` is an ancestor of `descendantID`.
* @internal
*/
function isAncestorIDOf(ancestorID, descendantID) {
return (
descendantID.indexOf(ancestorID) === 0 &&
isBoundary(descendantID, ancestorID.length)
);
}
/**
* Gets the parent ID of the supplied React DOM ID, `id`.
*
* @param {string} id ID of a component.
* @return {string} ID of the parent, or an empty string.
* @private
*/
function getParentID(id) {
return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : '';
}
/**
* Gets the next DOM ID on the tree path from the supplied `ancestorID` to the
* supplied `destinationID`. If they are equal, the ID is returned.
*
* @param {string} ancestorID ID of an ancestor node of `destinationID`.
* @param {string} destinationID ID of the destination node.
* @return {string} Next ID on the path from `ancestorID` to `destinationID`.
* @private
*/
function getNextDescendantID(ancestorID, destinationID) {
("production" !== "development" ? invariant(
isValidID(ancestorID) && isValidID(destinationID),
'getNextDescendantID(%s, %s): Received an invalid React DOM ID.',
ancestorID,
destinationID
) : invariant(isValidID(ancestorID) && isValidID(destinationID)));
("production" !== "development" ? invariant(
isAncestorIDOf(ancestorID, destinationID),
'getNextDescendantID(...): React has made an invalid assumption about ' +
'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.',
ancestorID,
destinationID
) : invariant(isAncestorIDOf(ancestorID, destinationID)));
if (ancestorID === destinationID) {
return ancestorID;
}
// Skip over the ancestor and the immediate separator. Traverse until we hit
// another separator or we reach the end of `destinationID`.
var start = ancestorID.length + SEPARATOR_LENGTH;
for (var i = start; i < destinationID.length; i++) {
if (isBoundary(destinationID, i)) {
break;
}
}
return destinationID.substr(0, i);
}
/**
* Gets the nearest common ancestor ID of two IDs.
*
* Using this ID scheme, the nearest common ancestor ID is the longest common
* prefix of the two IDs that immediately preceded a "marker" in both strings.
*
* @param {string} oneID
* @param {string} twoID
* @return {string} Nearest common ancestor ID, or the empty string if none.
* @private
*/
function getFirstCommonAncestorID(oneID, twoID) {
var minLength = Math.min(oneID.length, twoID.length);
if (minLength === 0) {
return '';
}
var lastCommonMarkerIndex = 0;
// Use `<=` to traverse until the "EOL" of the shorter string.
for (var i = 0; i <= minLength; i++) {
if (isBoundary(oneID, i) && isBoundary(twoID, i)) {
lastCommonMarkerIndex = i;
} else if (oneID.charAt(i) !== twoID.charAt(i)) {
break;
}
}
var longestCommonID = oneID.substr(0, lastCommonMarkerIndex);
("production" !== "development" ? invariant(
isValidID(longestCommonID),
'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s',
oneID,
twoID,
longestCommonID
) : invariant(isValidID(longestCommonID)));
return longestCommonID;
}
/**
* Traverses the parent path between two IDs (either up or down). The IDs must
* not be the same, and there must exist a parent path between them. If the
* callback returns `false`, traversal is stopped.
*
* @param {?string} start ID at which to start traversal.
* @param {?string} stop ID at which to end traversal.
* @param {function} cb Callback to invoke each ID with.
* @param {?boolean} skipFirst Whether or not to skip the first node.
* @param {?boolean} skipLast Whether or not to skip the last node.
* @private
*/
function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) {
start = start || '';
stop = stop || '';
("production" !== "development" ? invariant(
start !== stop,
'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.',
start
) : invariant(start !== stop));
var traverseUp = isAncestorIDOf(stop, start);
("production" !== "development" ? invariant(
traverseUp || isAncestorIDOf(start, stop),
'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' +
'not have a parent path.',
start,
stop
) : invariant(traverseUp || isAncestorIDOf(start, stop)));
// Traverse from `start` to `stop` one depth at a time.
var depth = 0;
var traverse = traverseUp ? getParentID : getNextDescendantID;
for (var id = start; /* until break */; id = traverse(id, stop)) {
var ret;
if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) {
ret = cb(id, traverseUp, arg);
}
if (ret === false || id === stop) {
// Only break //after// visiting `stop`.
break;
}
("production" !== "development" ? invariant(
depth++ < MAX_TREE_DEPTH,
'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' +
'traversing the React DOM ID tree. This may be due to malformed IDs: %s',
start, stop
) : invariant(depth++ < MAX_TREE_DEPTH));
}
}
/**
* Manages the IDs assigned to DOM representations of React components. This
* uses a specific scheme in order to traverse the DOM efficiently (e.g. in
* order to simulate events).
*
* @internal
*/
var ReactInstanceHandles = {
/**
* Constructs a React root ID
* @return {string} A React root ID.
*/
createReactRootID: function() {
return getReactRootIDString(ReactRootIndex.createReactRootIndex());
},
/**
* Constructs a React ID by joining a root ID with a name.
*
* @param {string} rootID Root ID of a parent component.
* @param {string} name A component's name (as flattened children).
* @return {string} A React ID.
* @internal
*/
createReactID: function(rootID, name) {
return rootID + name;
},
/**
* Gets the DOM ID of the React component that is the root of the tree that
* contains the React component with the supplied DOM ID.
*
* @param {string} id DOM ID of a React component.
* @return {?string} DOM ID of the React component that is the root.
* @internal
*/
getReactRootIDFromNodeID: function(id) {
if (id && id.charAt(0) === SEPARATOR && id.length > 1) {
var index = id.indexOf(SEPARATOR, 1);
return index > -1 ? id.substr(0, index) : id;
}
return null;
},
/**
* Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
* should would receive a `mouseEnter` or `mouseLeave` event.
*
* NOTE: Does not invoke the callback on the nearest common ancestor because
* nothing "entered" or "left" that element.
*
* @param {string} leaveID ID being left.
* @param {string} enterID ID being entered.
* @param {function} cb Callback to invoke on each entered/left ID.
* @param {*} upArg Argument to invoke the callback with on left IDs.
* @param {*} downArg Argument to invoke the callback with on entered IDs.
* @internal
*/
traverseEnterLeave: function(leaveID, enterID, cb, upArg, downArg) {
var ancestorID = getFirstCommonAncestorID(leaveID, enterID);
if (ancestorID !== leaveID) {
traverseParentPath(leaveID, ancestorID, cb, upArg, false, true);
}
if (ancestorID !== enterID) {
traverseParentPath(ancestorID, enterID, cb, downArg, true, false);
}
},
/**
* Simulates the traversal of a two-phase, capture/bubble event dispatch.
*
* NOTE: This traversal happens on IDs without touching the DOM.
*
* @param {string} targetID ID of the target node.
* @param {function} cb Callback to invoke.
* @param {*} arg Argument to invoke the callback with.
* @internal
*/
traverseTwoPhase: function(targetID, cb, arg) {
if (targetID) {
traverseParentPath('', targetID, cb, arg, true, false);
traverseParentPath(targetID, '', cb, arg, false, true);
}
},
/**
* Traverse a node ID, calling the supplied `cb` for each ancestor ID. For
* example, passing `.0.$row-0.1` would result in `cb` getting called
* with `.0`, `.0.$row-0`, and `.0.$row-0.1`.
*
* NOTE: This traversal happens on IDs without touching the DOM.
*
* @param {string} targetID ID of the target node.
* @param {function} cb Callback to invoke.
* @param {*} arg Argument to invoke the callback with.
* @internal
*/
traverseAncestors: function(targetID, cb, arg) {
traverseParentPath('', targetID, cb, arg, true, false);
},
/**
* Exposed for unit testing.
* @private
*/
_getFirstCommonAncestorID: getFirstCommonAncestorID,
/**
* Exposed for unit testing.
* @private
*/
_getNextDescendantID: getNextDescendantID,
isAncestorIDOf: isAncestorIDOf,
SEPARATOR: SEPARATOR
};
module.exports = ReactInstanceHandles;
},{"./ReactRootIndex":78,"./invariant":134}],65:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactLink
* @typechecks static-only
*/
"use strict";
/**
* ReactLink encapsulates a common pattern in which a component wants to modify
* a prop received from its parent. ReactLink allows the parent to pass down a
* value coupled with a callback that, when invoked, expresses an intent to
* modify that value. For example:
*
* React.createClass({
* getInitialState: function() {
* return {value: ''};
* },
* render: function() {
* var valueLink = new ReactLink(this.state.value, this._handleValueChange);
* return <input valueLink={valueLink} />;
* },
* this._handleValueChange: function(newValue) {
* this.setState({value: newValue});
* }
* });
*
* We have provided some sugary mixins to make the creation and
* consumption of ReactLink easier; see LinkedValueUtils and LinkedStateMixin.
*/
var React = _dereq_("./React");
/**
* @param {*} value current value of the link
* @param {function} requestChange callback to request a change
*/
function ReactLink(value, requestChange) {
this.value = value;
this.requestChange = requestChange;
}
/**
* Creates a PropType that enforces the ReactLink API and optionally checks the
* type of the value being passed inside the link. Example:
*
* MyComponent.propTypes = {
* tabIndexLink: ReactLink.PropTypes.link(React.PropTypes.number)
* }
*/
function createLinkTypeChecker(linkType) {
var shapes = {
value: typeof linkType === 'undefined' ?
React.PropTypes.any.isRequired :
linkType.isRequired,
requestChange: React.PropTypes.func.isRequired
};
return React.PropTypes.shape(shapes);
}
ReactLink.PropTypes = {
link: createLinkTypeChecker
};
module.exports = ReactLink;
},{"./React":29}],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 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":107}],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 ReactMount
*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var ReactDescriptor = _dereq_("./ReactDescriptor");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactPerf = _dereq_("./ReactPerf");
var containsNode = _dereq_("./containsNode");
var getReactRootElementInContainer = _dereq_("./getReactRootElementInContainer");
var instantiateReactComponent = _dereq_("./instantiateReactComponent");
var invariant = _dereq_("./invariant");
var shouldUpdateReactComponent = _dereq_("./shouldUpdateReactComponent");
var warning = _dereq_("./warning");
var SEPARATOR = ReactInstanceHandles.SEPARATOR;
var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME;
var nodeCache = {};
var ELEMENT_NODE_TYPE = 1;
var DOC_NODE_TYPE = 9;
/** Mapping from reactRootID to React component instance. */
var instancesByReactRootID = {};
/** Mapping from reactRootID to `container` nodes. */
var containersByReactRootID = {};
if ("production" !== "development") {
/** __DEV__-only mapping from reactRootID to root elements. */
var rootElementsByReactRootID = {};
}
// Used to store breadth-first search state in findComponentRoot.
var findComponentRootReusableArray = [];
/**
* @param {DOMElement} container DOM element that may contain a React component.
* @return {?string} A "reactRoot" ID, if a React component is rendered.
*/
function getReactRootID(container) {
var rootElement = getReactRootElementInContainer(container);
return rootElement && ReactMount.getID(rootElement);
}
/**
* Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form
* element can return its control whose name or ID equals ATTR_NAME. All
* DOM nodes support `getAttributeNode` but this can also get called on
* other objects so just return '' if we're given something other than a
* DOM node (such as window).
*
* @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node.
* @return {string} ID of the supplied `domNode`.
*/
function getID(node) {
var id = internalGetID(node);
if (id) {
if (nodeCache.hasOwnProperty(id)) {
var cached = nodeCache[id];
if (cached !== node) {
("production" !== "development" ? invariant(
!isValid(cached, id),
'ReactMount: Two valid but unequal nodes with the same `%s`: %s',
ATTR_NAME, id
) : invariant(!isValid(cached, id)));
nodeCache[id] = node;
}
} else {
nodeCache[id] = node;
}
}
return id;
}
function internalGetID(node) {
// If node is something like a window, document, or text node, none of
// which support attributes or a .getAttribute method, gracefully return
// the empty string, as if the attribute were missing.
return node && node.getAttribute && node.getAttribute(ATTR_NAME) || '';
}
/**
* Sets the React-specific ID of the given node.
*
* @param {DOMElement} node The DOM node whose ID will be set.
* @param {string} id The value of the ID attribute.
*/
function setID(node, id) {
var oldID = internalGetID(node);
if (oldID !== id) {
delete nodeCache[oldID];
}
node.setAttribute(ATTR_NAME, id);
nodeCache[id] = node;
}
/**
* Finds the node with the supplied React-generated DOM ID.
*
* @param {string} id A React-generated DOM ID.
* @return {DOMElement} DOM node with the suppled `id`.
* @internal
*/
function getNode(id) {
if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) {
nodeCache[id] = ReactMount.findReactNodeByID(id);
}
return nodeCache[id];
}
/**
* A node is "valid" if it is contained by a currently mounted container.
*
* This means that the node does not have to be contained by a document in
* order to be considered valid.
*
* @param {?DOMElement} node The candidate DOM node.
* @param {string} id The expected ID of the node.
* @return {boolean} Whether the node is contained by a mounted container.
*/
function isValid(node, id) {
if (node) {
("production" !== "development" ? invariant(
internalGetID(node) === id,
'ReactMount: Unexpected modification of `%s`',
ATTR_NAME
) : invariant(internalGetID(node) === id));
var container = ReactMount.findReactContainerForID(id);
if (container && containsNode(container, node)) {
return true;
}
}
return false;
}
/**
* Causes the cache to forget about one React-specific ID.
*
* @param {string} id The ID to forget.
*/
function purgeID(id) {
delete nodeCache[id];
}
var deepestNodeSoFar = null;
function findDeepestCachedAncestorImpl(ancestorID) {
var ancestor = nodeCache[ancestorID];
if (ancestor && isValid(ancestor, ancestorID)) {
deepestNodeSoFar = ancestor;
} else {
// This node isn't populated in the cache, so presumably none of its
// descendants are. Break out of the loop.
return false;
}
}
/**
* Return the deepest cached node whose ID is a prefix of `targetID`.
*/
function findDeepestCachedAncestor(targetID) {
deepestNodeSoFar = null;
ReactInstanceHandles.traverseAncestors(
targetID,
findDeepestCachedAncestorImpl
);
var foundNode = deepestNodeSoFar;
deepestNodeSoFar = null;
return foundNode;
}
/**
* Mounting is the process of initializing a React component by creatings its
* representative DOM elements and inserting them into a supplied `container`.
* Any prior content inside `container` is destroyed in the process.
*
* ReactMount.renderComponent(
* component,
* document.getElementById('container')
* );
*
* <div id="container"> <-- Supplied `container`.
* <div data-reactid=".3"> <-- Rendered reactRoot of React
* // ... component.
* </div>
* </div>
*
* Inside of `container`, the first element rendered is the "reactRoot".
*/
var ReactMount = {
/** Exposed for debugging purposes **/
_instancesByReactRootID: instancesByReactRootID,
/**
* This is a hook provided to support rendering React components while
* ensuring that the apparent scroll position of its `container` does not
* change.
*
* @param {DOMElement} container The `container` being rendered into.
* @param {function} renderCallback This must be called once to do the render.
*/
scrollMonitor: function(container, renderCallback) {
renderCallback();
},
/**
* Take a component that's already mounted into the DOM and replace its props
* @param {ReactComponent} prevComponent component instance already in the DOM
* @param {ReactComponent} nextComponent component instance to render
* @param {DOMElement} container container to render into
* @param {?function} callback function triggered on completion
*/
_updateRootComponent: function(
prevComponent,
nextComponent,
container,
callback) {
var nextProps = nextComponent.props;
ReactMount.scrollMonitor(container, function() {
prevComponent.replaceProps(nextProps, callback);
});
if ("production" !== "development") {
// Record the root element in case it later gets transplanted.
rootElementsByReactRootID[getReactRootID(container)] =
getReactRootElementInContainer(container);
}
return prevComponent;
},
/**
* Register a component into the instance map and starts scroll value
* monitoring
* @param {ReactComponent} nextComponent component instance to render
* @param {DOMElement} container container to render into
* @return {string} reactRoot ID prefix
*/
_registerComponent: function(nextComponent, container) {
("production" !== "development" ? invariant(
container && (
container.nodeType === ELEMENT_NODE_TYPE ||
container.nodeType === DOC_NODE_TYPE
),
'_registerComponent(...): Target container is not a DOM element.'
) : invariant(container && (
container.nodeType === ELEMENT_NODE_TYPE ||
container.nodeType === DOC_NODE_TYPE
)));
ReactBrowserEventEmitter.ensureScrollValueMonitoring();
var reactRootID = ReactMount.registerContainer(container);
instancesByReactRootID[reactRootID] = nextComponent;
return reactRootID;
},
/**
* Render a new component into the DOM.
* @param {ReactComponent} nextComponent component instance to render
* @param {DOMElement} container container to render into
* @param {boolean} shouldReuseMarkup if we should skip the markup insertion
* @return {ReactComponent} nextComponent
*/
_renderNewRootComponent: ReactPerf.measure(
'ReactMount',
'_renderNewRootComponent',
function(
nextComponent,
container,
shouldReuseMarkup) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case.
("production" !== "development" ? warning(
ReactCurrentOwner.current == null,
'_renderNewRootComponent(): Render methods should be a pure function ' +
'of props and state; triggering nested component updates from ' +
'render is not allowed. If necessary, trigger nested updates in ' +
'componentDidUpdate.'
) : null);
var componentInstance = instantiateReactComponent(nextComponent);
var reactRootID = ReactMount._registerComponent(
componentInstance,
container
);
componentInstance.mountComponentIntoNode(
reactRootID,
container,
shouldReuseMarkup
);
if ("production" !== "development") {
// Record the root element in case it later gets transplanted.
rootElementsByReactRootID[reactRootID] =
getReactRootElementInContainer(container);
}
return componentInstance;
}
),
/**
* Renders a React component into the DOM in the supplied `container`.
*
* If the React component was previously rendered into `container`, this will
* perform an update on it and only mutate the DOM as necessary to reflect the
* latest React component.
*
* @param {ReactDescriptor} nextDescriptor Component descriptor to render.
* @param {DOMElement} container DOM element to render into.
* @param {?function} callback function triggered on completion
* @return {ReactComponent} Component instance rendered in `container`.
*/
renderComponent: function(nextDescriptor, container, callback) {
("production" !== "development" ? invariant(
ReactDescriptor.isValidDescriptor(nextDescriptor),
'renderComponent(): Invalid component descriptor.%s',
(
ReactDescriptor.isValidFactory(nextDescriptor) ?
' Instead of passing a component class, make sure to instantiate ' +
'it first by calling it with props.' :
// Check if it quacks like a descriptor
typeof nextDescriptor.props !== "undefined" ?
' This may be caused by unintentionally loading two independent ' +
'copies of React.' :
''
)
) : invariant(ReactDescriptor.isValidDescriptor(nextDescriptor)));
var prevComponent = instancesByReactRootID[getReactRootID(container)];
if (prevComponent) {
var prevDescriptor = prevComponent._descriptor;
if (shouldUpdateReactComponent(prevDescriptor, nextDescriptor)) {
return ReactMount._updateRootComponent(
prevComponent,
nextDescriptor,
container,
callback
);
} else {
ReactMount.unmountComponentAtNode(container);
}
}
var reactRootElement = getReactRootElementInContainer(container);
var containerHasReactMarkup =
reactRootElement && ReactMount.isRenderedByReact(reactRootElement);
var shouldReuseMarkup = containerHasReactMarkup && !prevComponent;
var component = ReactMount._renderNewRootComponent(
nextDescriptor,
container,
shouldReuseMarkup
);
callback && callback.call(component);
return component;
},
/**
* Constructs a component instance of `constructor` with `initialProps` and
* renders it into the supplied `container`.
*
* @param {function} constructor React component constructor.
* @param {?object} props Initial props of the component instance.
* @param {DOMElement} container DOM element to render into.
* @return {ReactComponent} Component instance rendered in `container`.
*/
constructAndRenderComponent: function(constructor, props, container) {
return ReactMount.renderComponent(constructor(props), container);
},
/**
* Constructs a component instance of `constructor` with `initialProps` and
* renders it into a container node identified by supplied `id`.
*
* @param {function} componentConstructor React component constructor
* @param {?object} props Initial props of the component instance.
* @param {string} id ID of the DOM element to render into.
* @return {ReactComponent} Component instance rendered in the container node.
*/
constructAndRenderComponentByID: function(constructor, props, id) {
var domNode = document.getElementById(id);
("production" !== "development" ? invariant(
domNode,
'Tried to get element with id of "%s" but it is not present on the page.',
id
) : invariant(domNode));
return ReactMount.constructAndRenderComponent(constructor, props, domNode);
},
/**
* Registers a container node into which React components will be rendered.
* This also creates the "reactRoot" ID that will be assigned to the element
* rendered within.
*
* @param {DOMElement} container DOM element to register as a container.
* @return {string} The "reactRoot" ID of elements rendered within.
*/
registerContainer: function(container) {
var reactRootID = getReactRootID(container);
if (reactRootID) {
// If one exists, make sure it is a valid "reactRoot" ID.
reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID);
}
if (!reactRootID) {
// No valid "reactRoot" ID found, create one.
reactRootID = ReactInstanceHandles.createReactRootID();
}
containersByReactRootID[reactRootID] = container;
return reactRootID;
},
/**
* Unmounts and destroys the React component rendered in the `container`.
*
* @param {DOMElement} container DOM element containing a React component.
* @return {boolean} True if a component was found in and unmounted from
* `container`
*/
unmountComponentAtNode: function(container) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (Strictly speaking, unmounting won't cause a
// render but we still don't expect to be in a render call here.)
("production" !== "development" ? warning(
ReactCurrentOwner.current == null,
'unmountComponentAtNode(): Render methods should be a pure function of ' +
'props and state; triggering nested component updates from render is ' +
'not allowed. If necessary, trigger nested updates in ' +
'componentDidUpdate.'
) : null);
var reactRootID = getReactRootID(container);
var component = instancesByReactRootID[reactRootID];
if (!component) {
return false;
}
ReactMount.unmountComponentFromNode(component, container);
delete instancesByReactRootID[reactRootID];
delete containersByReactRootID[reactRootID];
if ("production" !== "development") {
delete rootElementsByReactRootID[reactRootID];
}
return true;
},
/**
* Unmounts a component and removes it from the DOM.
*
* @param {ReactComponent} instance React component instance.
* @param {DOMElement} container DOM element to unmount from.
* @final
* @internal
* @see {ReactMount.unmountComponentAtNode}
*/
unmountComponentFromNode: function(instance, container) {
instance.unmountComponent();
if (container.nodeType === DOC_NODE_TYPE) {
container = container.documentElement;
}
// http://jsperf.com/emptying-a-node
while (container.lastChild) {
container.removeChild(container.lastChild);
}
},
/**
* Finds the container DOM element that contains React component to which the
* supplied DOM `id` belongs.
*
* @param {string} id The ID of an element rendered by a React component.
* @return {?DOMElement} DOM element that contains the `id`.
*/
findReactContainerForID: function(id) {
var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id);
var container = containersByReactRootID[reactRootID];
if ("production" !== "development") {
var rootElement = rootElementsByReactRootID[reactRootID];
if (rootElement && rootElement.parentNode !== container) {
("production" !== "development" ? invariant(
// Call internalGetID here because getID calls isValid which calls
// findReactContainerForID (this function).
internalGetID(rootElement) === reactRootID,
'ReactMount: Root element ID differed from reactRootID.'
) : invariant(// Call internalGetID here because getID calls isValid which calls
// findReactContainerForID (this function).
internalGetID(rootElement) === reactRootID));
var containerChild = container.firstChild;
if (containerChild &&
reactRootID === internalGetID(containerChild)) {
// If the container has a new child with the same ID as the old
// root element, then rootElementsByReactRootID[reactRootID] is
// just stale and needs to be updated. The case that deserves a
// warning is when the container is empty.
rootElementsByReactRootID[reactRootID] = containerChild;
} else {
console.warn(
'ReactMount: Root element has been removed from its original ' +
'container. New container:', rootElement.parentNode
);
}
}
}
return container;
},
/**
* Finds an element rendered by React with the supplied ID.
*
* @param {string} id ID of a DOM node in the React component.
* @return {DOMElement} Root DOM node of the React component.
*/
findReactNodeByID: function(id) {
var reactRoot = ReactMount.findReactContainerForID(id);
return ReactMount.findComponentRoot(reactRoot, id);
},
/**
* True if the supplied `node` is rendered by React.
*
* @param {*} node DOM Element to check.
* @return {boolean} True if the DOM Element appears to be rendered by React.
* @internal
*/
isRenderedByReact: function(node) {
if (node.nodeType !== 1) {
// Not a DOMElement, therefore not a React component
return false;
}
var id = ReactMount.getID(node);
return id ? id.charAt(0) === SEPARATOR : false;
},
/**
* Traverses up the ancestors of the supplied node to find a node that is a
* DOM representation of a React component.
*
* @param {*} node
* @return {?DOMEventTarget}
* @internal
*/
getFirstReactDOM: function(node) {
var current = node;
while (current && current.parentNode !== current) {
if (ReactMount.isRenderedByReact(current)) {
return current;
}
current = current.parentNode;
}
return null;
},
/**
* Finds a node with the supplied `targetID` inside of the supplied
* `ancestorNode`. Exploits the ID naming scheme to perform the search
* quickly.
*
* @param {DOMEventTarget} ancestorNode Search from this root.
* @pararm {string} targetID ID of the DOM representation of the component.
* @return {DOMEventTarget} DOM node with the supplied `targetID`.
* @internal
*/
findComponentRoot: function(ancestorNode, targetID) {
var firstChildren = findComponentRootReusableArray;
var childIndex = 0;
var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode;
firstChildren[0] = deepestAncestor.firstChild;
firstChildren.length = 1;
while (childIndex < firstChildren.length) {
var child = firstChildren[childIndex++];
var targetChild;
while (child) {
var childID = ReactMount.getID(child);
if (childID) {
// Even if we find the node we're looking for, we finish looping
// through its siblings to ensure they're cached so that we don't have
// to revisit this node again. Otherwise, we make n^2 calls to getID
// when visiting the many children of a single node in order.
if (targetID === childID) {
targetChild = child;
} else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) {
// If we find a child whose ID is an ancestor of the given ID,
// then we can be sure that we only want to search the subtree
// rooted at this child, so we can throw out the rest of the
// search state.
firstChildren.length = childIndex = 0;
firstChildren.push(child.firstChild);
}
} else {
// If this child had no ID, then there's a chance that it was
// injected automatically by the browser, as when a `<table>`
// element sprouts an extra `<tbody>` child as a side effect of
// `.innerHTML` parsing. Optimistically continue down this
// branch, but not before examining the other siblings.
firstChildren.push(child.firstChild);
}
child = child.nextSibling;
}
if (targetChild) {
// Emptying firstChildren/findComponentRootReusableArray is
// not necessary for correctness, but it helps the GC reclaim
// any nodes that were left at the end of the search.
firstChildren.length = 0;
return targetChild;
}
}
firstChildren.length = 0;
("production" !== "development" ? invariant(
false,
'findComponentRoot(..., %s): Unable to find element. This probably ' +
'means the DOM was unexpectedly mutated (e.g., by the browser), ' +
'usually due to forgetting a <tbody> when using tables, nesting <p> ' +
'or <a> tags, or using non-SVG elements in an <svg> parent. Try ' +
'inspecting the child nodes of the element with React ID `%s`.',
targetID,
ReactMount.getID(ancestorNode)
) : invariant(false));
},
/**
* React ID utilities.
*/
getReactRootID: getReactRootID,
getID: getID,
setID: setID,
getNode: getNode,
purgeID: purgeID
};
module.exports = ReactMount;
},{"./DOMProperty":11,"./ReactBrowserEventEmitter":31,"./ReactCurrentOwner":40,"./ReactDescriptor":56,"./ReactInstanceHandles":64,"./ReactPerf":71,"./containsNode":109,"./getReactRootElementInContainer":128,"./instantiateReactComponent":133,"./invariant":134,"./shouldUpdateReactComponent":154,"./warning":158}],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 ReactMultiChild
* @typechecks static-only
*/
"use strict";
var ReactComponent = _dereq_("./ReactComponent");
var ReactMultiChildUpdateTypes = _dereq_("./ReactMultiChildUpdateTypes");
var flattenChildren = _dereq_("./flattenChildren");
var instantiateReactComponent = _dereq_("./instantiateReactComponent");
var shouldUpdateReactComponent = _dereq_("./shouldUpdateReactComponent");
/**
* Updating children of a component may trigger recursive updates. The depth is
* used to batch recursive updates to render markup more efficiently.
*
* @type {number}
* @private
*/
var updateDepth = 0;
/**
* Queue of update configuration objects.
*
* Each object has a `type` property that is in `ReactMultiChildUpdateTypes`.
*
* @type {array<object>}
* @private
*/
var updateQueue = [];
/**
* Queue of markup to be rendered.
*
* @type {array<string>}
* @private
*/
var markupQueue = [];
/**
* Enqueues markup to be rendered and inserted at a supplied index.
*
* @param {string} parentID ID of the parent component.
* @param {string} markup Markup that renders into an element.
* @param {number} toIndex Destination index.
* @private
*/
function enqueueMarkup(parentID, markup, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.INSERT_MARKUP,
markupIndex: markupQueue.push(markup) - 1,
textContent: null,
fromIndex: null,
toIndex: toIndex
});
}
/**
* Enqueues moving an existing element to another index.
*
* @param {string} parentID ID of the parent component.
* @param {number} fromIndex Source index of the existing element.
* @param {number} toIndex Destination index of the element.
* @private
*/
function enqueueMove(parentID, fromIndex, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.MOVE_EXISTING,
markupIndex: null,
textContent: null,
fromIndex: fromIndex,
toIndex: toIndex
});
}
/**
* Enqueues removing an element at an index.
*
* @param {string} parentID ID of the parent component.
* @param {number} fromIndex Index of the element to remove.
* @private
*/
function enqueueRemove(parentID, fromIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.REMOVE_NODE,
markupIndex: null,
textContent: null,
fromIndex: fromIndex,
toIndex: null
});
}
/**
* Enqueues setting the text content.
*
* @param {string} parentID ID of the parent component.
* @param {string} textContent Text content to set.
* @private
*/
function enqueueTextContent(parentID, textContent) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.TEXT_CONTENT,
markupIndex: null,
textContent: textContent,
fromIndex: null,
toIndex: null
});
}
/**
* Processes any enqueued updates.
*
* @private
*/
function processQueue() {
if (updateQueue.length) {
ReactComponent.BackendIDOperations.dangerouslyProcessChildrenUpdates(
updateQueue,
markupQueue
);
clearQueue();
}
}
/**
* Clears any enqueued updates.
*
* @private
*/
function clearQueue() {
updateQueue.length = 0;
markupQueue.length = 0;
}
/**
* ReactMultiChild are capable of reconciling multiple children.
*
* @class ReactMultiChild
* @internal
*/
var ReactMultiChild = {
/**
* Provides common functionality for components that must reconcile multiple
* children. This is used by `ReactDOMComponent` to mount, update, and
* unmount child components.
*
* @lends {ReactMultiChild.prototype}
*/
Mixin: {
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildren Nested child maps.
* @return {array} An array of mounted representations.
* @internal
*/
mountChildren: function(nestedChildren, transaction) {
var children = flattenChildren(nestedChildren);
var mountImages = [];
var index = 0;
this._renderedChildren = children;
for (var name in children) {
var child = children[name];
if (children.hasOwnProperty(name)) {
// The rendered children must be turned into instances as they're
// mounted.
var childInstance = instantiateReactComponent(child);
children[name] = childInstance;
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + name;
var mountImage = childInstance.mountComponent(
rootID,
transaction,
this._mountDepth + 1
);
childInstance._mountIndex = index;
mountImages.push(mountImage);
index++;
}
}
return mountImages;
},
/**
* Replaces any rendered children with a text content string.
*
* @param {string} nextContent String of content.
* @internal
*/
updateTextContent: function(nextContent) {
updateDepth++;
var errorThrown = true;
try {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
this._unmountChildByName(prevChildren[name], name);
}
}
// Set new text content.
this.setTextContent(nextContent);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
errorThrown ? clearQueue() : processQueue();
}
}
},
/**
* Updates the rendered children with new children.
*
* @param {?object} nextNestedChildren Nested child maps.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
updateChildren: function(nextNestedChildren, transaction) {
updateDepth++;
var errorThrown = true;
try {
this._updateChildren(nextNestedChildren, transaction);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
errorThrown ? clearQueue() : processQueue();
}
}
},
/**
* Improve performance by isolating this hot code path from the try/catch
* block in `updateChildren`.
*
* @param {?object} nextNestedChildren Nested child maps.
* @param {ReactReconcileTransaction} transaction
* @final
* @protected
*/
_updateChildren: function(nextNestedChildren, transaction) {
var nextChildren = flattenChildren(nextNestedChildren);
var prevChildren = this._renderedChildren;
if (!nextChildren && !prevChildren) {
return;
}
var name;
// `nextIndex` will increment for each child in `nextChildren`, but
// `lastIndex` will be the last index visited in `prevChildren`.
var lastIndex = 0;
var nextIndex = 0;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
var prevChild = prevChildren && prevChildren[name];
var prevDescriptor = prevChild && prevChild._descriptor;
var nextDescriptor = nextChildren[name];
if (shouldUpdateReactComponent(prevDescriptor, nextDescriptor)) {
this.moveChild(prevChild, nextIndex, lastIndex);
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
prevChild.receiveComponent(nextDescriptor, transaction);
prevChild._mountIndex = nextIndex;
} else {
if (prevChild) {
// Update `lastIndex` before `_mountIndex` gets unset by unmounting.
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
this._unmountChildByName(prevChild, name);
}
// The child must be instantiated before it's mounted.
var nextChildInstance = instantiateReactComponent(nextDescriptor);
this._mountChildByNameAtIndex(
nextChildInstance, name, nextIndex, transaction
);
}
nextIndex++;
}
// Remove children that are no longer present.
for (name in prevChildren) {
if (prevChildren.hasOwnProperty(name) &&
!(nextChildren && nextChildren[name])) {
this._unmountChildByName(prevChildren[name], name);
}
}
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted.
*
* @internal
*/
unmountChildren: function() {
var renderedChildren = this._renderedChildren;
for (var name in renderedChildren) {
var renderedChild = renderedChildren[name];
// TODO: When is this not true?
if (renderedChild.unmountComponent) {
renderedChild.unmountComponent();
}
}
this._renderedChildren = null;
},
/**
* Moves a child component to the supplied index.
*
* @param {ReactComponent} child Component to move.
* @param {number} toIndex Destination index of the element.
* @param {number} lastIndex Last index visited of the siblings of `child`.
* @protected
*/
moveChild: function(child, toIndex, lastIndex) {
// If the index of `child` is less than `lastIndex`, then it needs to
// be moved. Otherwise, we do not need to move it because a child will be
// inserted or moved before `child`.
if (child._mountIndex < lastIndex) {
enqueueMove(this._rootNodeID, child._mountIndex, toIndex);
}
},
/**
* Creates a child component.
*
* @param {ReactComponent} child Component to create.
* @param {string} mountImage Markup to insert.
* @protected
*/
createChild: function(child, mountImage) {
enqueueMarkup(this._rootNodeID, mountImage, child._mountIndex);
},
/**
* Removes a child component.
*
* @param {ReactComponent} child Child to remove.
* @protected
*/
removeChild: function(child) {
enqueueRemove(this._rootNodeID, child._mountIndex);
},
/**
* Sets this text content string.
*
* @param {string} textContent Text content to set.
* @protected
*/
setTextContent: function(textContent) {
enqueueTextContent(this._rootNodeID, textContent);
},
/**
* Mounts a child with the supplied name.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to mount.
* @param {string} name Name of the child.
* @param {number} index Index at which to insert the child.
* @param {ReactReconcileTransaction} transaction
* @private
*/
_mountChildByNameAtIndex: function(child, name, index, transaction) {
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + name;
var mountImage = child.mountComponent(
rootID,
transaction,
this._mountDepth + 1
);
child._mountIndex = index;
this.createChild(child, mountImage);
this._renderedChildren = this._renderedChildren || {};
this._renderedChildren[name] = child;
},
/**
* Unmounts a rendered child by name.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to unmount.
* @param {string} name Name of the child in `this._renderedChildren`.
* @private
*/
_unmountChildByName: function(child, name) {
this.removeChild(child);
child._mountIndex = null;
child.unmountComponent();
delete this._renderedChildren[name];
}
}
};
module.exports = ReactMultiChild;
},{"./ReactComponent":35,"./ReactMultiChildUpdateTypes":69,"./flattenChildren":119,"./instantiateReactComponent":133,"./shouldUpdateReactComponent":154}],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 ReactMultiChildUpdateTypes
*/
"use strict";
var keyMirror = _dereq_("./keyMirror");
/**
* When a component's children are updated, a series of update configuration
* objects are created in order to batch and serialize the required changes.
*
* Enumerates all the possible types of update configurations.
*
* @internal
*/
var ReactMultiChildUpdateTypes = keyMirror({
INSERT_MARKUP: null,
MOVE_EXISTING: null,
REMOVE_NODE: null,
TEXT_CONTENT: null
});
module.exports = ReactMultiChildUpdateTypes;
},{"./keyMirror":140}],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 ReactOwner
*/
"use strict";
var emptyObject = _dereq_("./emptyObject");
var invariant = _dereq_("./invariant");
/**
* ReactOwners are capable of storing references to owned components.
*
* All components are capable of //being// referenced by owner components, but
* only ReactOwner components are capable of //referencing// owned components.
* The named reference is known as a "ref".
*
* Refs are available when mounted and updated during reconciliation.
*
* var MyComponent = React.createClass({
* render: function() {
* return (
* <div onClick={this.handleClick}>
* <CustomComponent ref="custom" />
* </div>
* );
* },
* handleClick: function() {
* this.refs.custom.handleClick();
* },
* componentDidMount: function() {
* this.refs.custom.initialize();
* }
* });
*
* Refs should rarely be used. When refs are used, they should only be done to
* control data that is not handled by React's data flow.
*
* @class ReactOwner
*/
var ReactOwner = {
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid owner.
* @final
*/
isValidOwner: function(object) {
return !!(
object &&
typeof object.attachRef === 'function' &&
typeof object.detachRef === 'function'
);
},
/**
* Adds a component by ref to an owner component.
*
* @param {ReactComponent} component Component to reference.
* @param {string} ref Name by which to refer to the component.
* @param {ReactOwner} owner Component on which to record the ref.
* @final
* @internal
*/
addComponentAsRefTo: function(component, ref, owner) {
("production" !== "development" ? invariant(
ReactOwner.isValidOwner(owner),
'addComponentAsRefTo(...): Only a ReactOwner can have refs. This ' +
'usually means that you\'re trying to add a ref to a component that ' +
'doesn\'t have an owner (that is, was not created inside of another ' +
'component\'s `render` method). Try rendering this component inside of ' +
'a new top-level component which will hold the ref.'
) : invariant(ReactOwner.isValidOwner(owner)));
owner.attachRef(ref, component);
},
/**
* Removes a component by ref from an owner component.
*
* @param {ReactComponent} component Component to dereference.
* @param {string} ref Name of the ref to remove.
* @param {ReactOwner} owner Component on which the ref is recorded.
* @final
* @internal
*/
removeComponentAsRefFrom: function(component, ref, owner) {
("production" !== "development" ? invariant(
ReactOwner.isValidOwner(owner),
'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. This ' +
'usually means that you\'re trying to remove a ref to a component that ' +
'doesn\'t have an owner (that is, was not created inside of another ' +
'component\'s `render` method). Try rendering this component inside of ' +
'a new top-level component which will hold the ref.'
) : invariant(ReactOwner.isValidOwner(owner)));
// Check that `component` is still the current ref because we do not want to
// detach the ref if another component stole it.
if (owner.refs[ref] === component) {
owner.detachRef(ref);
}
},
/**
* A ReactComponent must mix this in to have refs.
*
* @lends {ReactOwner.prototype}
*/
Mixin: {
construct: function() {
this.refs = emptyObject;
},
/**
* Lazily allocates the refs object and stores `component` as `ref`.
*
* @param {string} ref Reference name.
* @param {component} component Component to store as `ref`.
* @final
* @private
*/
attachRef: function(ref, component) {
("production" !== "development" ? invariant(
component.isOwnedBy(this),
'attachRef(%s, ...): Only a component\'s owner can store a ref to it.',
ref
) : invariant(component.isOwnedBy(this)));
var refs = this.refs === emptyObject ? (this.refs = {}) : this.refs;
refs[ref] = component;
},
/**
* Detaches a reference name.
*
* @param {string} ref Name to dereference.
* @final
* @private
*/
detachRef: function(ref) {
delete this.refs[ref];
}
}
};
module.exports = ReactOwner;
},{"./emptyObject":117,"./invariant":134}],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 ReactPerf
* @typechecks static-only
*/
"use strict";
/**
* ReactPerf is a general AOP system designed to measure performance. This
* module only has the hooks: see ReactDefaultPerf for the analysis tool.
*/
var ReactPerf = {
/**
* Boolean to enable/disable measurement. Set to false by default to prevent
* accidental logging and perf loss.
*/
enableMeasure: false,
/**
* Holds onto the measure function in use. By default, don't measure
* anything, but we'll override this if we inject a measure function.
*/
storedMeasure: _noMeasure,
/**
* Use this to wrap methods you want to measure. Zero overhead in production.
*
* @param {string} objName
* @param {string} fnName
* @param {function} func
* @return {function}
*/
measure: function(objName, fnName, func) {
if ("production" !== "development") {
var measuredFunc = null;
return function() {
if (ReactPerf.enableMeasure) {
if (!measuredFunc) {
measuredFunc = ReactPerf.storedMeasure(objName, fnName, func);
}
return measuredFunc.apply(this, arguments);
}
return func.apply(this, arguments);
};
}
return func;
},
injection: {
/**
* @param {function} measure
*/
injectMeasure: function(measure) {
ReactPerf.storedMeasure = measure;
}
}
};
/**
* Simply passes through the measured function, without measuring it.
*
* @param {string} objName
* @param {string} fnName
* @param {function} func
* @return {function}
*/
function _noMeasure(objName, fnName, func) {
return func;
}
module.exports = ReactPerf;
},{}],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 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" !== "development" ? 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":116,"./invariant":134,"./joinClasses":139,"./merge":144}],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 ReactPropTypeLocationNames
*/
"use strict";
var ReactPropTypeLocationNames = {};
if ("production" !== "development") {
ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context'
};
}
module.exports = ReactPropTypeLocationNames;
},{}],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 ReactPropTypeLocations
*/
"use strict";
var keyMirror = _dereq_("./keyMirror");
var ReactPropTypeLocations = keyMirror({
prop: null,
context: null,
childContext: null
});
module.exports = ReactPropTypeLocations;
},{"./keyMirror":140}],75:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactPropTypes
*/
"use strict";
var ReactDescriptor = _dereq_("./ReactDescriptor");
var ReactPropTypeLocationNames = _dereq_("./ReactPropTypeLocationNames");
var emptyFunction = _dereq_("./emptyFunction");
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
component: createComponentTypeChecker(),
instanceOf: createInstanceTypeChecker,
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
renderable: createRenderableTypeChecker(),
shape: createShapeTypeChecker
};
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location) {
componentName = componentName || ANONYMOUS;
if (props[propName] == null) {
var locationName = ReactPropTypeLocationNames[location];
if (isRequired) {
return new Error(
("Required " + locationName + " `" + propName + "` was not specified in ")+
("`" + componentName + "`.")
);
}
} else {
return validate(props, propName, componentName, location);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
var locationName = ReactPropTypeLocationNames[location];
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new Error(
("Invalid " + locationName + " `" + propName + "` of type `" + preciseType + "` ") +
("supplied to `" + componentName + "`, expected `" + expectedType + "`.")
);
}
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturns());
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location) {
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var locationName = ReactPropTypeLocationNames[location];
var propType = getPropType(propValue);
return new Error(
("Invalid " + locationName + " `" + propName + "` of type ") +
("`" + propType + "` supplied to `" + componentName + "`, expected an array.")
);
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location);
if (error instanceof Error) {
return error;
}
}
}
return createChainableTypeChecker(validate);
}
function createComponentTypeChecker() {
function validate(props, propName, componentName, location) {
if (!ReactDescriptor.isValidDescriptor(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error(
("Invalid " + locationName + " `" + propName + "` supplied to ") +
("`" + componentName + "`, expected a React component.")
);
}
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location) {
if (!(props[propName] instanceof expectedClass)) {
var locationName = ReactPropTypeLocationNames[location];
var expectedClassName = expectedClass.name || ANONYMOUS;
return new Error(
("Invalid " + locationName + " `" + propName + "` supplied to ") +
("`" + componentName + "`, expected instance of `" + expectedClassName + "`.")
);
}
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
function validate(props, propName, componentName, location) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (propValue === expectedValues[i]) {
return;
}
}
var locationName = ReactPropTypeLocationNames[location];
var valuesString = JSON.stringify(expectedValues);
return new Error(
("Invalid " + locationName + " `" + propName + "` of value `" + propValue + "` ") +
("supplied to `" + componentName + "`, expected one of " + valuesString + ".")
);
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new Error(
("Invalid " + locationName + " `" + propName + "` of type ") +
("`" + propType + "` supplied to `" + componentName + "`, expected an object.")
);
}
for (var key in propValue) {
if (propValue.hasOwnProperty(key)) {
var error = typeChecker(propValue, key, componentName, location);
if (error instanceof Error) {
return error;
}
}
}
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
function validate(props, propName, componentName, location) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location) == null) {
return;
}
}
var locationName = ReactPropTypeLocationNames[location];
return new Error(
("Invalid " + locationName + " `" + propName + "` supplied to ") +
("`" + componentName + "`.")
);
}
return createChainableTypeChecker(validate);
}
function createRenderableTypeChecker() {
function validate(props, propName, componentName, location) {
if (!isRenderable(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error(
("Invalid " + locationName + " `" + propName + "` supplied to ") +
("`" + componentName + "`, expected a renderable prop.")
);
}
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new Error(
("Invalid " + locationName + " `" + propName + "` of type `" + propType + "` ") +
("supplied to `" + componentName + "`, expected `object`.")
);
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location);
if (error) {
return error;
}
}
}
return createChainableTypeChecker(validate, 'expected `object`');
}
function isRenderable(propValue) {
switch(typeof propValue) {
// TODO: this was probably written with the assumption that we're not
// returning `this.props.component` directly from `render`. This is
// currently not supported but we should, to make it consistent.
case 'number':
case 'string':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isRenderable);
}
if (ReactDescriptor.isValidDescriptor(propValue)) {
return true;
}
for (var k in propValue) {
if (!isRenderable(propValue[k])) {
return false;
}
}
return true;
default:
return false;
}
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
module.exports = ReactPropTypes;
},{"./ReactDescriptor":56,"./ReactPropTypeLocationNames":73,"./emptyFunction":116}],76:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule 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":28,"./ReactBrowserEventEmitter":31,"./mixInto":147}],77:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactReconcileTransaction
* @typechecks static-only
*/
"use strict";
var CallbackQueue = _dereq_("./CallbackQueue");
var PooledClass = _dereq_("./PooledClass");
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var ReactInputSelection = _dereq_("./ReactInputSelection");
var ReactPutListenerQueue = _dereq_("./ReactPutListenerQueue");
var Transaction = _dereq_("./Transaction");
var mixInto = _dereq_("./mixInto");
/**
* Ensures that, when possible, the selection range (currently selected text
* input) is not disturbed by performing the transaction.
*/
var SELECTION_RESTORATION = {
/**
* @return {Selection} Selection information.
*/
initialize: ReactInputSelection.getSelectionInformation,
/**
* @param {Selection} sel Selection information returned from `initialize`.
*/
close: ReactInputSelection.restoreSelection
};
/**
* Suppresses events (blur/focus) that could be inadvertently dispatched due to
* high level DOM manipulations (like temporarily removing a text input from the
* DOM).
*/
var EVENT_SUPPRESSION = {
/**
* @return {boolean} The enabled status of `ReactBrowserEventEmitter` before
* the reconciliation.
*/
initialize: function() {
var currentlyEnabled = ReactBrowserEventEmitter.isEnabled();
ReactBrowserEventEmitter.setEnabled(false);
return currentlyEnabled;
},
/**
* @param {boolean} previouslyEnabled Enabled status of
* `ReactBrowserEventEmitter` before the reconciliation occured. `close`
* restores the previous value.
*/
close: function(previouslyEnabled) {
ReactBrowserEventEmitter.setEnabled(previouslyEnabled);
}
};
/**
* Provides a queue for collecting `componentDidMount` and
* `componentDidUpdate` callbacks during the the transaction.
*/
var ON_DOM_READY_QUEUEING = {
/**
* Initializes the internal `onDOMReady` queue.
*/
initialize: function() {
this.reactMountReady.reset();
},
/**
* After DOM is flushed, invoke all registered `onDOMReady` callbacks.
*/
close: function() {
this.reactMountReady.notifyAll();
}
};
var PUT_LISTENER_QUEUEING = {
initialize: function() {
this.putListenerQueue.reset();
},
close: function() {
this.putListenerQueue.putListeners();
}
};
/**
* Executed within the scope of the `Transaction` instance. Consider these as
* being member methods, but with an implied ordering while being isolated from
* each other.
*/
var TRANSACTION_WRAPPERS = [
PUT_LISTENER_QUEUEING,
SELECTION_RESTORATION,
EVENT_SUPPRESSION,
ON_DOM_READY_QUEUEING
];
/**
* Currently:
* - The order that these are listed in the transaction is critical:
* - Suppresses events.
* - Restores selection range.
*
* Future:
* - Restore document/overflow scroll positions that were unintentionally
* modified via DOM insertions above the top viewport boundary.
* - Implement/integrate with customized constraint based layout system and keep
* track of which dimensions must be remeasured.
*
* @class ReactReconcileTransaction
*/
function ReactReconcileTransaction() {
this.reinitializeTransaction();
// Only server-side rendering really needs this option (see
// `ReactServerRendering`), but server-side uses
// `ReactServerRenderingTransaction` instead. This option is here so that it's
// accessible and defaults to false when `ReactDOMComponent` and
// `ReactTextComponent` checks it in `mountComponent`.`
this.renderToStaticMarkup = false;
this.reactMountReady = CallbackQueue.getPooled(null);
this.putListenerQueue = ReactPutListenerQueue.getPooled();
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array<object>} List of operation wrap proceedures.
* TODO: convert to array<TransactionWrapper>
*/
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
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(ReactReconcileTransaction, Transaction.Mixin);
mixInto(ReactReconcileTransaction, Mixin);
PooledClass.addPoolingTo(ReactReconcileTransaction);
module.exports = ReactReconcileTransaction;
},{"./CallbackQueue":6,"./PooledClass":28,"./ReactBrowserEventEmitter":31,"./ReactInputSelection":63,"./ReactPutListenerQueue":76,"./Transaction":104,"./mixInto":147}],78:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactRootIndex
* @typechecks
*/
"use strict";
var ReactRootIndexInjection = {
/**
* @param {function} _createReactRootIndex
*/
injectCreateReactRootIndex: function(_createReactRootIndex) {
ReactRootIndex.createReactRootIndex = _createReactRootIndex;
}
};
var ReactRootIndex = {
createReactRootIndex: null,
injection: ReactRootIndexInjection
};
module.exports = ReactRootIndex;
},{}],79:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @typechecks static-only
* @providesModule ReactServerRendering
*/
"use strict";
var ReactDescriptor = _dereq_("./ReactDescriptor");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactMarkupChecksum = _dereq_("./ReactMarkupChecksum");
var ReactServerRenderingTransaction =
_dereq_("./ReactServerRenderingTransaction");
var instantiateReactComponent = _dereq_("./instantiateReactComponent");
var invariant = _dereq_("./invariant");
/**
* @param {ReactComponent} component
* @return {string} the HTML markup
*/
function renderComponentToString(component) {
("production" !== "development" ? invariant(
ReactDescriptor.isValidDescriptor(component),
'renderComponentToString(): You must pass a valid ReactComponent.'
) : invariant(ReactDescriptor.isValidDescriptor(component)));
("production" !== "development" ? invariant(
!(arguments.length === 2 && typeof arguments[1] === 'function'),
'renderComponentToString(): This function became synchronous and now ' +
'returns the generated markup. Please remove the second parameter.'
) : invariant(!(arguments.length === 2 && typeof arguments[1] === 'function')));
var transaction;
try {
var id = ReactInstanceHandles.createReactRootID();
transaction = ReactServerRenderingTransaction.getPooled(false);
return transaction.perform(function() {
var componentInstance = instantiateReactComponent(component);
var markup = componentInstance.mountComponent(id, transaction, 0);
return ReactMarkupChecksum.addChecksumToMarkup(markup);
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
}
}
/**
* @param {ReactComponent} component
* @return {string} the HTML markup, without the extra React ID and checksum
* (for generating static pages)
*/
function renderComponentToStaticMarkup(component) {
("production" !== "development" ? invariant(
ReactDescriptor.isValidDescriptor(component),
'renderComponentToStaticMarkup(): You must pass a valid ReactComponent.'
) : invariant(ReactDescriptor.isValidDescriptor(component)));
var transaction;
try {
var id = ReactInstanceHandles.createReactRootID();
transaction = ReactServerRenderingTransaction.getPooled(true);
return transaction.perform(function() {
var componentInstance = instantiateReactComponent(component);
return componentInstance.mountComponent(id, transaction, 0);
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
}
}
module.exports = {
renderComponentToString: renderComponentToString,
renderComponentToStaticMarkup: renderComponentToStaticMarkup
};
},{"./ReactDescriptor":56,"./ReactInstanceHandles":64,"./ReactMarkupChecksum":66,"./ReactServerRenderingTransaction":80,"./instantiateReactComponent":133,"./invariant":134}],80:[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":6,"./PooledClass":28,"./ReactPutListenerQueue":76,"./Transaction":104,"./emptyFunction":116,"./mixInto":147}],81:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactStateSetters
*/
"use strict";
var ReactStateSetters = {
/**
* Returns a function that calls the provided function, and uses the result
* of that to set the component's state.
*
* @param {ReactCompositeComponent} component
* @param {function} funcReturningState Returned callback uses this to
* determine how to update state.
* @return {function} callback that when invoked uses funcReturningState to
* determined the object literal to setState.
*/
createStateSetter: function(component, funcReturningState) {
return function(a, b, c, d, e, f) {
var partialState = funcReturningState.call(component, a, b, c, d, e, f);
if (partialState) {
component.setState(partialState);
}
};
},
/**
* Returns a single-argument callback that can be used to update a single
* key in the component's state.
*
* Note: this is memoized function, which makes it inexpensive to call.
*
* @param {ReactCompositeComponent} component
* @param {string} key The key in the state that you should update.
* @return {function} callback of 1 argument which calls setState() with
* the provided keyName and callback argument.
*/
createStateKeySetter: function(component, key) {
// Memoize the setters.
var cache = component.__keySetters || (component.__keySetters = {});
return cache[key] || (cache[key] = createStateKeySetter(component, key));
}
};
function createStateKeySetter(component, key) {
// Partial state is allocated outside of the function closure so it can be
// reused with every call, avoiding memory allocation when this function
// is called.
var partialState = {};
return function stateKeySetter(value) {
partialState[key] = value;
component.setState(partialState);
};
}
ReactStateSetters.Mixin = {
/**
* Returns a function that calls the provided function, and uses the result
* of that to set the component's state.
*
* For example, these statements are equivalent:
*
* this.setState({x: 1});
* this.createStateSetter(function(xValue) {
* return {x: xValue};
* })(1);
*
* @param {function} funcReturningState Returned callback uses this to
* determine how to update state.
* @return {function} callback that when invoked uses funcReturningState to
* determined the object literal to setState.
*/
createStateSetter: function(funcReturningState) {
return ReactStateSetters.createStateSetter(this, funcReturningState);
},
/**
* Returns a single-argument callback that can be used to update a single
* key in the component's state.
*
* For example, these statements are equivalent:
*
* this.setState({x: 1});
* this.createStateKeySetter('x')(1);
*
* Note: this is memoized function, which makes it inexpensive to call.
*
* @param {string} key The key in the state that you should update.
* @return {function} callback of 1 argument which calls setState() with
* the provided keyName and callback argument.
*/
createStateKeySetter: function(key) {
return ReactStateSetters.createStateKeySetter(this, key);
}
};
module.exports = ReactStateSetters;
},{}],82:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactTestUtils
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPluginHub = _dereq_("./EventPluginHub");
var EventPropagators = _dereq_("./EventPropagators");
var React = _dereq_("./React");
var ReactDescriptor = _dereq_("./ReactDescriptor");
var ReactDOM = _dereq_("./ReactDOM");
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var ReactMount = _dereq_("./ReactMount");
var ReactTextComponent = _dereq_("./ReactTextComponent");
var ReactUpdates = _dereq_("./ReactUpdates");
var SyntheticEvent = _dereq_("./SyntheticEvent");
var mergeInto = _dereq_("./mergeInto");
var copyProperties = _dereq_("./copyProperties");
var topLevelTypes = EventConstants.topLevelTypes;
function Event(suffix) {}
/**
* @class ReactTestUtils
*/
/**
* Todo: Support the entire DOM.scry query syntax. For now, these simple
* utilities will suffice for testing purposes.
* @lends ReactTestUtils
*/
var ReactTestUtils = {
renderIntoDocument: function(instance) {
var div = document.createElement('div');
// None of our tests actually require attaching the container to the
// DOM, and doing so creates a mess that we rely on test isolation to
// clean up, so we're going to stop honoring the name of this method
// (and probably rename it eventually) if no problems arise.
// document.documentElement.appendChild(div);
return React.renderComponent(instance, div);
},
isDescriptor: function(descriptor) {
return ReactDescriptor.isValidDescriptor(descriptor);
},
isDescriptorOfType: function(inst, convenienceConstructor) {
return (
ReactDescriptor.isValidDescriptor(inst) &&
inst.type === convenienceConstructor.type
);
},
isDOMComponent: function(inst) {
return !!(inst && inst.mountComponent && inst.tagName);
},
isDOMComponentDescriptor: function(inst) {
return !!(inst &&
ReactDescriptor.isValidDescriptor(inst) &&
!!inst.tagName);
},
isCompositeComponent: function(inst) {
return typeof inst.render === 'function' &&
typeof inst.setState === 'function';
},
isCompositeComponentWithType: function(inst, type) {
return !!(ReactTestUtils.isCompositeComponent(inst) &&
(inst.constructor === type.type));
},
isCompositeComponentDescriptor: function(inst) {
if (!ReactDescriptor.isValidDescriptor(inst)) {
return false;
}
// We check the prototype of the type that will get mounted, not the
// instance itself. This is a future proof way of duck typing.
var prototype = inst.type.prototype;
return (
typeof prototype.render === 'function' &&
typeof prototype.setState === 'function'
);
},
isCompositeComponentDescriptorWithType: function(inst, type) {
return !!(ReactTestUtils.isCompositeComponentDescriptor(inst) &&
(inst.constructor === type));
},
isTextComponent: function(inst) {
return inst instanceof ReactTextComponent.type;
},
findAllInRenderedTree: function(inst, test) {
if (!inst) {
return [];
}
var ret = test(inst) ? [inst] : [];
if (ReactTestUtils.isDOMComponent(inst)) {
var renderedChildren = inst._renderedChildren;
var key;
for (key in renderedChildren) {
if (!renderedChildren.hasOwnProperty(key)) {
continue;
}
ret = ret.concat(
ReactTestUtils.findAllInRenderedTree(renderedChildren[key], test)
);
}
} else if (ReactTestUtils.isCompositeComponent(inst)) {
ret = ret.concat(
ReactTestUtils.findAllInRenderedTree(inst._renderedComponent, test)
);
}
return ret;
},
/**
* Finds all instance of components in the rendered tree that are DOM
* components with the class name matching `className`.
* @return an array of all the matches.
*/
scryRenderedDOMComponentsWithClass: function(root, className) {
return ReactTestUtils.findAllInRenderedTree(root, function(inst) {
var instClassName = inst.props.className;
return ReactTestUtils.isDOMComponent(inst) && (
instClassName &&
(' ' + instClassName + ' ').indexOf(' ' + className + ' ') !== -1
);
});
},
/**
* Like scryRenderedDOMComponentsWithClass but expects there to be one result,
* and returns that one result, or throws exception if there is any other
* number of matches besides one.
* @return {!ReactDOMComponent} The one match.
*/
findRenderedDOMComponentWithClass: function(root, className) {
var all =
ReactTestUtils.scryRenderedDOMComponentsWithClass(root, className);
if (all.length !== 1) {
throw new Error('Did not find exactly one match for class:' + className);
}
return all[0];
},
/**
* Finds all instance of components in the rendered tree that are DOM
* components with the tag name matching `tagName`.
* @return an array of all the matches.
*/
scryRenderedDOMComponentsWithTag: function(root, tagName) {
return ReactTestUtils.findAllInRenderedTree(root, function(inst) {
return ReactTestUtils.isDOMComponent(inst) &&
inst.tagName === tagName.toUpperCase();
});
},
/**
* Like scryRenderedDOMComponentsWithTag but expects there to be one result,
* and returns that one result, or throws exception if there is any other
* number of matches besides one.
* @return {!ReactDOMComponent} The one match.
*/
findRenderedDOMComponentWithTag: function(root, tagName) {
var all = ReactTestUtils.scryRenderedDOMComponentsWithTag(root, tagName);
if (all.length !== 1) {
throw new Error('Did not find exactly one match for tag:' + tagName);
}
return all[0];
},
/**
* Finds all instances of components with type equal to `componentType`.
* @return an array of all the matches.
*/
scryRenderedComponentsWithType: function(root, componentType) {
return ReactTestUtils.findAllInRenderedTree(root, function(inst) {
return ReactTestUtils.isCompositeComponentWithType(
inst,
componentType
);
});
},
/**
* Same as `scryRenderedComponentsWithType` but expects there to be one result
* and returns that one result, or throws exception if there is any other
* number of matches besides one.
* @return {!ReactComponent} The one match.
*/
findRenderedComponentWithType: function(root, componentType) {
var all = ReactTestUtils.scryRenderedComponentsWithType(
root,
componentType
);
if (all.length !== 1) {
throw new Error(
'Did not find exactly one match for componentType:' + componentType
);
}
return all[0];
},
/**
* Pass a mocked component module to this method to augment it with
* useful methods that allow it to be used as a dummy React component.
* Instead of rendering as usual, the component will become a simple
* <div> containing any provided children.
*
* @param {object} module the mock function object exported from a
* module that defines the component to be mocked
* @param {?string} mockTagName optional dummy root tag name to return
* from render method (overrides
* module.mockTagName if provided)
* @return {object} the ReactTestUtils object (for chaining)
*/
mockComponent: function(module, mockTagName) {
var ConvenienceConstructor = React.createClass({
render: function() {
var mockTagName = mockTagName || module.mockTagName || "div";
return ReactDOM[mockTagName](null, this.props.children);
}
});
copyProperties(module, ConvenienceConstructor);
module.mockImplementation(ConvenienceConstructor);
return this;
},
/**
* Simulates a top level event being dispatched from a raw event that occured
* on an `Element` node.
* @param topLevelType {Object} A type from `EventConstants.topLevelTypes`
* @param {!Element} node The dom to simulate an event occurring on.
* @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent.
*/
simulateNativeEventOnNode: function(topLevelType, node, fakeNativeEvent) {
fakeNativeEvent.target = node;
ReactBrowserEventEmitter.ReactEventListener.dispatchEvent(
topLevelType,
fakeNativeEvent
);
},
/**
* Simulates a top level event being dispatched from a raw event that occured
* on the `ReactDOMComponent` `comp`.
* @param topLevelType {Object} A type from `EventConstants.topLevelTypes`.
* @param comp {!ReactDOMComponent}
* @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent.
*/
simulateNativeEventOnDOMComponent: function(
topLevelType,
comp,
fakeNativeEvent) {
ReactTestUtils.simulateNativeEventOnNode(
topLevelType,
comp.getDOMNode(),
fakeNativeEvent
);
},
nativeTouchData: function(x, y) {
return {
touches: [
{pageX: x, pageY: y}
]
};
},
Simulate: null,
SimulateNative: {}
};
/**
* Exports:
*
* - `ReactTestUtils.Simulate.click(Element/ReactDOMComponent)`
* - `ReactTestUtils.Simulate.mouseMove(Element/ReactDOMComponent)`
* - `ReactTestUtils.Simulate.change(Element/ReactDOMComponent)`
* - ... (All keys from event plugin `eventTypes` objects)
*/
function makeSimulator(eventType) {
return function(domComponentOrNode, eventData) {
var node;
if (ReactTestUtils.isDOMComponent(domComponentOrNode)) {
node = domComponentOrNode.getDOMNode();
} else if (domComponentOrNode.tagName) {
node = domComponentOrNode;
}
var fakeNativeEvent = new Event();
fakeNativeEvent.target = node;
// We don't use SyntheticEvent.getPooled in order to not have to worry about
// properly destroying any properties assigned from `eventData` upon release
var event = new SyntheticEvent(
ReactBrowserEventEmitter.eventNameDispatchConfigs[eventType],
ReactMount.getID(node),
fakeNativeEvent
);
mergeInto(event, eventData);
EventPropagators.accumulateTwoPhaseDispatches(event);
ReactUpdates.batchedUpdates(function() {
EventPluginHub.enqueueEvents(event);
EventPluginHub.processEventQueue();
});
};
}
function buildSimulators() {
ReactTestUtils.Simulate = {};
var eventType;
for (eventType in ReactBrowserEventEmitter.eventNameDispatchConfigs) {
/**
* @param {!Element || ReactDOMComponent} domComponentOrNode
* @param {?object} eventData Fake event data to use in SyntheticEvent.
*/
ReactTestUtils.Simulate[eventType] = makeSimulator(eventType);
}
}
// Rebuild ReactTestUtils.Simulate whenever event plugins are injected
var oldInjectEventPluginOrder = EventPluginHub.injection.injectEventPluginOrder;
EventPluginHub.injection.injectEventPluginOrder = function() {
oldInjectEventPluginOrder.apply(this, arguments);
buildSimulators();
};
var oldInjectEventPlugins = EventPluginHub.injection.injectEventPluginsByName;
EventPluginHub.injection.injectEventPluginsByName = function() {
oldInjectEventPlugins.apply(this, arguments);
buildSimulators();
};
buildSimulators();
/**
* Exports:
*
* - `ReactTestUtils.SimulateNative.click(Element/ReactDOMComponent)`
* - `ReactTestUtils.SimulateNative.mouseMove(Element/ReactDOMComponent)`
* - `ReactTestUtils.SimulateNative.mouseIn/ReactDOMComponent)`
* - `ReactTestUtils.SimulateNative.mouseOut(Element/ReactDOMComponent)`
* - ... (All keys from `EventConstants.topLevelTypes`)
*
* Note: Top level event types are a subset of the entire set of handler types
* (which include a broader set of "synthetic" events). For example, onDragDone
* is a synthetic event. Except when testing an event plugin or React's event
* handling code specifically, you probably want to use ReactTestUtils.Simulate
* to dispatch synthetic events.
*/
function makeNativeSimulator(eventType) {
return function(domComponentOrNode, nativeEventData) {
var fakeNativeEvent = new Event(eventType);
mergeInto(fakeNativeEvent, nativeEventData);
if (ReactTestUtils.isDOMComponent(domComponentOrNode)) {
ReactTestUtils.simulateNativeEventOnDOMComponent(
eventType,
domComponentOrNode,
fakeNativeEvent
);
} else if (!!domComponentOrNode.tagName) {
// Will allow on actual dom nodes.
ReactTestUtils.simulateNativeEventOnNode(
eventType,
domComponentOrNode,
fakeNativeEvent
);
}
};
}
var eventType;
for (eventType in topLevelTypes) {
// Event type is stored as 'topClick' - we transform that to 'click'
var convenienceName = eventType.indexOf('top') === 0 ?
eventType.charAt(3).toLowerCase() + eventType.substr(4) : eventType;
/**
* @param {!Element || ReactDOMComponent} domComponentOrNode
* @param {?Event} nativeEventData Fake native event to use in SyntheticEvent.
*/
ReactTestUtils.SimulateNative[convenienceName] =
makeNativeSimulator(eventType);
}
module.exports = ReactTestUtils;
},{"./EventConstants":16,"./EventPluginHub":18,"./EventPropagators":21,"./React":29,"./ReactBrowserEventEmitter":31,"./ReactDOM":41,"./ReactDescriptor":56,"./ReactMount":67,"./ReactTextComponent":83,"./ReactUpdates":87,"./SyntheticEvent":96,"./copyProperties":110,"./mergeInto":146}],83:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactTextComponent
* @typechecks static-only
*/
"use strict";
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactComponent = _dereq_("./ReactComponent");
var ReactDescriptor = _dereq_("./ReactDescriptor");
var escapeTextForBrowser = _dereq_("./escapeTextForBrowser");
var mixInto = _dereq_("./mixInto");
/**
* Text nodes violate a couple assumptions that React makes about components:
*
* - When mounting text into the DOM, adjacent text nodes are merged.
* - Text nodes cannot be assigned a React root ID.
*
* This component is used to wrap strings in elements so that they can undergo
* the same reconciliation that is applied to elements.
*
* TODO: Investigate representing React components in the DOM with text nodes.
*
* @class ReactTextComponent
* @extends ReactComponent
* @internal
*/
var ReactTextComponent = function(descriptor) {
this.construct(descriptor);
};
mixInto(ReactTextComponent, ReactComponent.Mixin);
mixInto(ReactTextComponent, ReactBrowserComponentMixin);
mixInto(ReactTextComponent, {
/**
* Creates the markup for this text node. This node is not intended to have
* any features besides containing text content.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {number} mountDepth number of components in the owner hierarchy
* @return {string} Markup for this text node.
* @internal
*/
mountComponent: function(rootID, transaction, mountDepth) {
ReactComponent.Mixin.mountComponent.call(
this,
rootID,
transaction,
mountDepth
);
var escapedText = escapeTextForBrowser(this.props);
if (transaction.renderToStaticMarkup) {
// Normally we'd wrap this in a `span` for the reasons stated above, but
// since this is a situation where React won't take over (static pages),
// we can simply return the text as it is.
return escapedText;
}
return (
'<span ' + DOMPropertyOperations.createMarkupForID(rootID) + '>' +
escapedText +
'</span>'
);
},
/**
* Updates this component by updating the text content.
*
* @param {object} nextComponent Contains the next text content.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveComponent: function(nextComponent, transaction) {
var nextProps = nextComponent.props;
if (nextProps !== this.props) {
this.props = nextProps;
ReactComponent.BackendIDOperations.updateTextContentByID(
this._rootNodeID,
nextProps
);
}
}
});
module.exports = ReactDescriptor.createFactory(ReactTextComponent);
},{"./DOMPropertyOperations":12,"./ReactBrowserComponentMixin":30,"./ReactComponent":35,"./ReactDescriptor":56,"./escapeTextForBrowser":118,"./mixInto":147}],84:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @typechecks static-only
* @providesModule ReactTransitionChildMapping
*/
"use strict";
var ReactChildren = _dereq_("./ReactChildren");
var ReactTransitionChildMapping = {
/**
* Given `this.props.children`, return an object mapping key to child. Just
* simple syntactic sugar around ReactChildren.map().
*
* @param {*} children `this.props.children`
* @return {object} Mapping of key to child
*/
getChildMapping: function(children) {
return ReactChildren.map(children, function(child) {
return child;
});
},
/**
* When you're adding or removing children some may be added or removed in the
* same render pass. We want ot show *both* since we want to simultaneously
* animate elements in and out. This function takes a previous set of keys
* and a new set of keys and merges them with its best guess of the correct
* ordering. In the future we may expose some of the utilities in
* ReactMultiChild to make this easy, but for now React itself does not
* directly have this concept of the union of prevChildren and nextChildren
* so we implement it here.
*
* @param {object} prev prev children as returned from
* `ReactTransitionChildMapping.getChildMapping()`.
* @param {object} next next children as returned from
* `ReactTransitionChildMapping.getChildMapping()`.
* @return {object} a key set that contains all keys in `prev` and all keys
* in `next` in a reasonable order.
*/
mergeChildMappings: function(prev, next) {
prev = prev || {};
next = next || {};
function getValueForKey(key) {
if (next.hasOwnProperty(key)) {
return next[key];
} else {
return prev[key];
}
}
// For each key of `next`, the list of keys to insert before that key in
// the combined list
var nextKeysPending = {};
var pendingKeys = [];
for (var prevKey in prev) {
if (next.hasOwnProperty(prevKey)) {
if (pendingKeys.length) {
nextKeysPending[prevKey] = pendingKeys;
pendingKeys = [];
}
} else {
pendingKeys.push(prevKey);
}
}
var i;
var childMapping = {};
for (var nextKey in next) {
if (nextKeysPending.hasOwnProperty(nextKey)) {
for (i = 0; i < nextKeysPending[nextKey].length; i++) {
var pendingNextKey = nextKeysPending[nextKey][i];
childMapping[nextKeysPending[nextKey][i]] = getValueForKey(
pendingNextKey
);
}
}
childMapping[nextKey] = getValueForKey(nextKey);
}
// Finally, add the keys which didn't appear before any key in `next`
for (i = 0; i < pendingKeys.length; i++) {
childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]);
}
return childMapping;
}
};
module.exports = ReactTransitionChildMapping;
},{"./ReactChildren":34}],85:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactTransitionEvents
*/
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
/**
* EVENT_NAME_MAP is used to determine which event fired when a
* transition/animation ends, based on the style property used to
* define that event.
*/
var EVENT_NAME_MAP = {
transitionend: {
'transition': 'transitionend',
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'mozTransitionEnd',
'OTransition': 'oTransitionEnd',
'msTransition': 'MSTransitionEnd'
},
animationend: {
'animation': 'animationend',
'WebkitAnimation': 'webkitAnimationEnd',
'MozAnimation': 'mozAnimationEnd',
'OAnimation': 'oAnimationEnd',
'msAnimation': 'MSAnimationEnd'
}
};
var endEvents = [];
function detectEvents() {
var testEl = document.createElement('div');
var style = testEl.style;
// On some platforms, in particular some releases of Android 4.x,
// the un-prefixed "animation" and "transition" properties are defined on the
// style object but the events that fire will still be prefixed, so we need
// to check if the un-prefixed events are useable, and if not remove them
// from the map
if (!('AnimationEvent' in window)) {
delete EVENT_NAME_MAP.animationend.animation;
}
if (!('TransitionEvent' in window)) {
delete EVENT_NAME_MAP.transitionend.transition;
}
for (var baseEventName in EVENT_NAME_MAP) {
var baseEvents = EVENT_NAME_MAP[baseEventName];
for (var styleName in baseEvents) {
if (styleName in style) {
endEvents.push(baseEvents[styleName]);
break;
}
}
}
}
if (ExecutionEnvironment.canUseDOM) {
detectEvents();
}
// We use the raw {add|remove}EventListener() call because EventListener
// does not know how to remove event listeners and we really should
// clean up. Also, these events are not triggered in older browsers
// so we should be A-OK here.
function addEventListener(node, eventName, eventListener) {
node.addEventListener(eventName, eventListener, false);
}
function removeEventListener(node, eventName, eventListener) {
node.removeEventListener(eventName, eventListener, false);
}
var ReactTransitionEvents = {
addEndEventListener: function(node, eventListener) {
if (endEvents.length === 0) {
// If CSS transitions are not supported, trigger an "end animation"
// event immediately.
window.setTimeout(eventListener, 0);
return;
}
endEvents.forEach(function(endEvent) {
addEventListener(node, endEvent, eventListener);
});
},
removeEndEventListener: function(node, eventListener) {
if (endEvents.length === 0) {
return;
}
endEvents.forEach(function(endEvent) {
removeEventListener(node, endEvent, eventListener);
});
}
};
module.exports = ReactTransitionEvents;
},{"./ExecutionEnvironment":22}],86:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactTransitionGroup
*/
"use strict";
var React = _dereq_("./React");
var ReactTransitionChildMapping = _dereq_("./ReactTransitionChildMapping");
var cloneWithProps = _dereq_("./cloneWithProps");
var emptyFunction = _dereq_("./emptyFunction");
var merge = _dereq_("./merge");
var ReactTransitionGroup = React.createClass({
displayName: 'ReactTransitionGroup',
propTypes: {
component: React.PropTypes.func,
childFactory: React.PropTypes.func
},
getDefaultProps: function() {
return {
component: React.DOM.span,
childFactory: emptyFunction.thatReturnsArgument
};
},
getInitialState: function() {
return {
children: ReactTransitionChildMapping.getChildMapping(this.props.children)
};
},
componentWillReceiveProps: function(nextProps) {
var nextChildMapping = ReactTransitionChildMapping.getChildMapping(
nextProps.children
);
var prevChildMapping = this.state.children;
this.setState({
children: ReactTransitionChildMapping.mergeChildMappings(
prevChildMapping,
nextChildMapping
)
});
var key;
for (key in nextChildMapping) {
var hasPrev = prevChildMapping && prevChildMapping.hasOwnProperty(key);
if (nextChildMapping[key] && !hasPrev &&
!this.currentlyTransitioningKeys[key]) {
this.keysToEnter.push(key);
}
}
for (key in prevChildMapping) {
var hasNext = nextChildMapping && nextChildMapping.hasOwnProperty(key);
if (prevChildMapping[key] && !hasNext &&
!this.currentlyTransitioningKeys[key]) {
this.keysToLeave.push(key);
}
}
// If we want to someday check for reordering, we could do it here.
},
componentWillMount: function() {
this.currentlyTransitioningKeys = {};
this.keysToEnter = [];
this.keysToLeave = [];
},
componentDidUpdate: function() {
var keysToEnter = this.keysToEnter;
this.keysToEnter = [];
keysToEnter.forEach(this.performEnter);
var keysToLeave = this.keysToLeave;
this.keysToLeave = [];
keysToLeave.forEach(this.performLeave);
},
performEnter: function(key) {
this.currentlyTransitioningKeys[key] = true;
var component = this.refs[key];
if (component.componentWillEnter) {
component.componentWillEnter(
this._handleDoneEntering.bind(this, key)
);
} else {
this._handleDoneEntering(key);
}
},
_handleDoneEntering: function(key) {
var component = this.refs[key];
if (component.componentDidEnter) {
component.componentDidEnter();
}
delete this.currentlyTransitioningKeys[key];
var currentChildMapping = ReactTransitionChildMapping.getChildMapping(
this.props.children
);
if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) {
// This was removed before it had fully entered. Remove it.
this.performLeave(key);
}
},
performLeave: function(key) {
this.currentlyTransitioningKeys[key] = true;
var component = this.refs[key];
if (component.componentWillLeave) {
component.componentWillLeave(this._handleDoneLeaving.bind(this, key));
} else {
// Note that this is somewhat dangerous b/c it calls setState()
// again, effectively mutating the component before all the work
// is done.
this._handleDoneLeaving(key);
}
},
_handleDoneLeaving: function(key) {
var component = this.refs[key];
if (component.componentDidLeave) {
component.componentDidLeave();
}
delete this.currentlyTransitioningKeys[key];
var currentChildMapping = ReactTransitionChildMapping.getChildMapping(
this.props.children
);
if (currentChildMapping && currentChildMapping.hasOwnProperty(key)) {
// This entered again before it fully left. Add it again.
this.performEnter(key);
} else {
var newChildren = merge(this.state.children);
delete newChildren[key];
this.setState({children: newChildren});
}
},
render: function() {
// TODO: we could get rid of the need for the wrapper node
// by cloning a single child
var childrenToRender = {};
for (var key in this.state.children) {
var child = this.state.children[key];
if (child) {
// You may need to apply reactive updates to a child as it is leaving.
// The normal React way to do it won't work since the child will have
// already been removed. In case you need this behavior you can provide
// a childFactory function to wrap every child, even the ones that are
// leaving.
childrenToRender[key] = cloneWithProps(
this.props.childFactory(child),
{ref: key}
);
}
}
return this.transferPropsTo(this.props.component(null, childrenToRender));
}
});
module.exports = ReactTransitionGroup;
},{"./React":29,"./ReactTransitionChildMapping":84,"./cloneWithProps":108,"./emptyFunction":116,"./merge":144}],87:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactUpdates
*/
"use strict";
var CallbackQueue = _dereq_("./CallbackQueue");
var PooledClass = _dereq_("./PooledClass");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var ReactPerf = _dereq_("./ReactPerf");
var Transaction = _dereq_("./Transaction");
var invariant = _dereq_("./invariant");
var mixInto = _dereq_("./mixInto");
var warning = _dereq_("./warning");
var dirtyComponents = [];
var batchingStrategy = null;
function ensureInjected() {
("production" !== "development" ? invariant(
ReactUpdates.ReactReconcileTransaction && batchingStrategy,
'ReactUpdates: must inject a reconcile transaction class and batching ' +
'strategy'
) : invariant(ReactUpdates.ReactReconcileTransaction && batchingStrategy));
}
var NESTED_UPDATES = {
initialize: function() {
this.dirtyComponentsLength = dirtyComponents.length;
},
close: function() {
if (this.dirtyComponentsLength !== dirtyComponents.length) {
// Additional updates were enqueued by componentDidUpdate handlers or
// similar; before our own UPDATE_QUEUEING wrapper closes, we want to run
// these new updates so that if A's componentDidUpdate calls setState on
// B, B will update before the callback A's updater provided when calling
// setState.
dirtyComponents.splice(0, this.dirtyComponentsLength);
flushBatchedUpdates();
} else {
dirtyComponents.length = 0;
}
}
};
var UPDATE_QUEUEING = {
initialize: function() {
this.callbackQueue.reset();
},
close: function() {
this.callbackQueue.notifyAll();
}
};
var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING];
function ReactUpdatesFlushTransaction() {
this.reinitializeTransaction();
this.dirtyComponentsLength = null;
this.callbackQueue = CallbackQueue.getPooled(null);
this.reconcileTransaction =
ReactUpdates.ReactReconcileTransaction.getPooled();
}
mixInto(ReactUpdatesFlushTransaction, Transaction.Mixin);
mixInto(ReactUpdatesFlushTransaction, {
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS;
},
destructor: function() {
this.dirtyComponentsLength = null;
CallbackQueue.release(this.callbackQueue);
this.callbackQueue = null;
ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction);
this.reconcileTransaction = null;
},
perform: function(method, scope, a) {
// Essentially calls `this.reconcileTransaction.perform(method, scope, a)`
// with this transaction's wrappers around it.
return Transaction.Mixin.perform.call(
this,
this.reconcileTransaction.perform,
this.reconcileTransaction,
method,
scope,
a
);
}
});
PooledClass.addPoolingTo(ReactUpdatesFlushTransaction);
function batchedUpdates(callback, a, b) {
ensureInjected();
batchingStrategy.batchedUpdates(callback, a, b);
}
/**
* Array comparator for ReactComponents by owner depth
*
* @param {ReactComponent} c1 first component you're comparing
* @param {ReactComponent} c2 second component you're comparing
* @return {number} Return value usable by Array.prototype.sort().
*/
function mountDepthComparator(c1, c2) {
return c1._mountDepth - c2._mountDepth;
}
function runBatchedUpdates(transaction) {
var len = transaction.dirtyComponentsLength;
("production" !== "development" ? invariant(
len === dirtyComponents.length,
'Expected flush transaction\'s stored dirty-components length (%s) to ' +
'match dirty-components array length (%s).',
len,
dirtyComponents.length
) : invariant(len === dirtyComponents.length));
// Since reconciling a component higher in the owner hierarchy usually (not
// always -- see shouldComponentUpdate()) will reconcile children, reconcile
// them before their children by sorting the array.
dirtyComponents.sort(mountDepthComparator);
for (var i = 0; i < len; i++) {
// If a component is unmounted before pending changes apply, ignore them
// TODO: Queue unmounts in the same list to avoid this happening at all
var component = dirtyComponents[i];
if (component.isMounted()) {
// If performUpdateIfNecessary happens to enqueue any new updates, we
// shouldn't execute the callbacks until the next render happens, so
// stash the callbacks first
var callbacks = component._pendingCallbacks;
component._pendingCallbacks = null;
component.performUpdateIfNecessary(transaction.reconcileTransaction);
if (callbacks) {
for (var j = 0; j < callbacks.length; j++) {
transaction.callbackQueue.enqueue(
callbacks[j],
component
);
}
}
}
}
}
var flushBatchedUpdates = ReactPerf.measure(
'ReactUpdates',
'flushBatchedUpdates',
function() {
// ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents
// array and perform any updates enqueued by mount-ready handlers (i.e.,
// componentDidUpdate) but we need to check here too in order to catch
// updates enqueued by setState callbacks.
while (dirtyComponents.length) {
var transaction = ReactUpdatesFlushTransaction.getPooled();
transaction.perform(runBatchedUpdates, null, transaction);
ReactUpdatesFlushTransaction.release(transaction);
}
}
);
/**
* Mark a component as needing a rerender, adding an optional callback to a
* list of functions which will be executed once the rerender occurs.
*/
function enqueueUpdate(component, callback) {
("production" !== "development" ? invariant(
!callback || typeof callback === "function",
'enqueueUpdate(...): You called `setProps`, `replaceProps`, ' +
'`setState`, `replaceState`, or `forceUpdate` with a callback that ' +
'isn\'t callable.'
) : invariant(!callback || typeof callback === "function"));
ensureInjected();
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (This is called by each top-level update
// function, like setProps, setState, forceUpdate, etc.; creation and
// destruction of top-level components is guarded in ReactMount.)
("production" !== "development" ? warning(
ReactCurrentOwner.current == null,
'enqueueUpdate(): Render methods should be a pure function of props ' +
'and state; triggering nested component updates from render is not ' +
'allowed. If necessary, trigger nested updates in ' +
'componentDidUpdate.'
) : null);
if (!batchingStrategy.isBatchingUpdates) {
batchingStrategy.batchedUpdates(enqueueUpdate, component, callback);
return;
}
dirtyComponents.push(component);
if (callback) {
if (component._pendingCallbacks) {
component._pendingCallbacks.push(callback);
} else {
component._pendingCallbacks = [callback];
}
}
}
var ReactUpdatesInjection = {
injectReconcileTransaction: function(ReconcileTransaction) {
("production" !== "development" ? invariant(
ReconcileTransaction,
'ReactUpdates: must provide a reconcile transaction class'
) : invariant(ReconcileTransaction));
ReactUpdates.ReactReconcileTransaction = ReconcileTransaction;
},
injectBatchingStrategy: function(_batchingStrategy) {
("production" !== "development" ? invariant(
_batchingStrategy,
'ReactUpdates: must provide a batching strategy'
) : invariant(_batchingStrategy));
("production" !== "development" ? invariant(
typeof _batchingStrategy.batchedUpdates === 'function',
'ReactUpdates: must provide a batchedUpdates() function'
) : invariant(typeof _batchingStrategy.batchedUpdates === 'function'));
("production" !== "development" ? invariant(
typeof _batchingStrategy.isBatchingUpdates === 'boolean',
'ReactUpdates: must provide an isBatchingUpdates boolean attribute'
) : invariant(typeof _batchingStrategy.isBatchingUpdates === 'boolean'));
batchingStrategy = _batchingStrategy;
}
};
var ReactUpdates = {
/**
* React references `ReactReconcileTransaction` using this property in order
* to allow dependency injection.
*
* @internal
*/
ReactReconcileTransaction: null,
batchedUpdates: batchedUpdates,
enqueueUpdate: enqueueUpdate,
flushBatchedUpdates: flushBatchedUpdates,
injection: ReactUpdatesInjection
};
module.exports = ReactUpdates;
},{"./CallbackQueue":6,"./PooledClass":28,"./ReactCurrentOwner":40,"./ReactPerf":71,"./Transaction":104,"./invariant":134,"./mixInto":147,"./warning":158}],88:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactWithAddons
*/
/**
* This module exists purely in the open source project, and is meant as a way
* to create a separate standalone build of React. This build has "addons", or
* functionality we've built and think might be useful but doesn't have a good
* place to live inside React core.
*/
"use strict";
var LinkedStateMixin = _dereq_("./LinkedStateMixin");
var React = _dereq_("./React");
var ReactComponentWithPureRenderMixin =
_dereq_("./ReactComponentWithPureRenderMixin");
var ReactCSSTransitionGroup = _dereq_("./ReactCSSTransitionGroup");
var ReactTransitionGroup = _dereq_("./ReactTransitionGroup");
var cx = _dereq_("./cx");
var cloneWithProps = _dereq_("./cloneWithProps");
var update = _dereq_("./update");
React.addons = {
CSSTransitionGroup: ReactCSSTransitionGroup,
LinkedStateMixin: LinkedStateMixin,
PureRenderMixin: ReactComponentWithPureRenderMixin,
TransitionGroup: ReactTransitionGroup,
classSet: cx,
cloneWithProps: cloneWithProps,
update: update
};
if ("production" !== "development") {
React.addons.Perf = _dereq_("./ReactDefaultPerf");
React.addons.TestUtils = _dereq_("./ReactTestUtils");
}
module.exports = React;
},{"./LinkedStateMixin":24,"./React":29,"./ReactCSSTransitionGroup":32,"./ReactComponentWithPureRenderMixin":37,"./ReactDefaultPerf":54,"./ReactTestUtils":82,"./ReactTransitionGroup":86,"./cloneWithProps":108,"./cx":114,"./update":157}],89:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SVGDOMPropertyConfig
*/
/*jslint bitwise: true*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var SVGDOMPropertyConfig = {
Properties: {
cx: MUST_USE_ATTRIBUTE,
cy: MUST_USE_ATTRIBUTE,
d: MUST_USE_ATTRIBUTE,
dx: MUST_USE_ATTRIBUTE,
dy: MUST_USE_ATTRIBUTE,
fill: MUST_USE_ATTRIBUTE,
fillOpacity: MUST_USE_ATTRIBUTE,
fontFamily: MUST_USE_ATTRIBUTE,
fontSize: MUST_USE_ATTRIBUTE,
fx: MUST_USE_ATTRIBUTE,
fy: MUST_USE_ATTRIBUTE,
gradientTransform: MUST_USE_ATTRIBUTE,
gradientUnits: MUST_USE_ATTRIBUTE,
markerEnd: MUST_USE_ATTRIBUTE,
markerMid: MUST_USE_ATTRIBUTE,
markerStart: MUST_USE_ATTRIBUTE,
offset: MUST_USE_ATTRIBUTE,
opacity: MUST_USE_ATTRIBUTE,
patternContentUnits: MUST_USE_ATTRIBUTE,
patternUnits: MUST_USE_ATTRIBUTE,
points: MUST_USE_ATTRIBUTE,
preserveAspectRatio: MUST_USE_ATTRIBUTE,
r: MUST_USE_ATTRIBUTE,
rx: MUST_USE_ATTRIBUTE,
ry: MUST_USE_ATTRIBUTE,
spreadMethod: MUST_USE_ATTRIBUTE,
stopColor: MUST_USE_ATTRIBUTE,
stopOpacity: MUST_USE_ATTRIBUTE,
stroke: MUST_USE_ATTRIBUTE,
strokeDasharray: MUST_USE_ATTRIBUTE,
strokeLinecap: MUST_USE_ATTRIBUTE,
strokeOpacity: MUST_USE_ATTRIBUTE,
strokeWidth: MUST_USE_ATTRIBUTE,
textAnchor: MUST_USE_ATTRIBUTE,
transform: MUST_USE_ATTRIBUTE,
version: MUST_USE_ATTRIBUTE,
viewBox: MUST_USE_ATTRIBUTE,
x1: MUST_USE_ATTRIBUTE,
x2: MUST_USE_ATTRIBUTE,
x: MUST_USE_ATTRIBUTE,
y1: MUST_USE_ATTRIBUTE,
y2: MUST_USE_ATTRIBUTE,
y: MUST_USE_ATTRIBUTE
},
DOMAttributeNames: {
fillOpacity: 'fill-opacity',
fontFamily: 'font-family',
fontSize: 'font-size',
gradientTransform: 'gradientTransform',
gradientUnits: 'gradientUnits',
markerEnd: 'marker-end',
markerMid: 'marker-mid',
markerStart: 'marker-start',
patternContentUnits: 'patternContentUnits',
patternUnits: 'patternUnits',
preserveAspectRatio: 'preserveAspectRatio',
spreadMethod: 'spreadMethod',
stopColor: 'stop-color',
stopOpacity: 'stop-opacity',
strokeDasharray: 'stroke-dasharray',
strokeLinecap: 'stroke-linecap',
strokeOpacity: 'stroke-opacity',
strokeWidth: 'stroke-width',
textAnchor: 'text-anchor',
viewBox: 'viewBox'
}
};
module.exports = SVGDOMPropertyConfig;
},{"./DOMProperty":11}],90:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SelectEventPlugin
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPropagators = _dereq_("./EventPropagators");
var ReactInputSelection = _dereq_("./ReactInputSelection");
var SyntheticEvent = _dereq_("./SyntheticEvent");
var getActiveElement = _dereq_("./getActiveElement");
var isTextInputElement = _dereq_("./isTextInputElement");
var keyOf = _dereq_("./keyOf");
var shallowEqual = _dereq_("./shallowEqual");
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
select: {
phasedRegistrationNames: {
bubbled: keyOf({onSelect: null}),
captured: keyOf({onSelectCapture: null})
},
dependencies: [
topLevelTypes.topBlur,
topLevelTypes.topContextMenu,
topLevelTypes.topFocus,
topLevelTypes.topKeyDown,
topLevelTypes.topMouseDown,
topLevelTypes.topMouseUp,
topLevelTypes.topSelectionChange
]
}
};
var activeElement = null;
var activeElementID = null;
var lastSelection = null;
var mouseDown = false;
/**
* Get an object which is a unique representation of the current selection.
*
* The return value will not be consistent across nodes or browsers, but
* two identical selections on the same node will return identical objects.
*
* @param {DOMElement} node
* @param {object}
*/
function getSelection(node) {
if ('selectionStart' in node &&
ReactInputSelection.hasSelectionCapabilities(node)) {
return {
start: node.selectionStart,
end: node.selectionEnd
};
} else if (document.selection) {
var range = document.selection.createRange();
return {
parentElement: range.parentElement(),
text: range.text,
top: range.boundingTop,
left: range.boundingLeft
};
} else {
var selection = window.getSelection();
return {
anchorNode: selection.anchorNode,
anchorOffset: selection.anchorOffset,
focusNode: selection.focusNode,
focusOffset: selection.focusOffset
};
}
}
/**
* Poll selection to see whether it's changed.
*
* @param {object} nativeEvent
* @return {?SyntheticEvent}
*/
function constructSelectEvent(nativeEvent) {
// Ensure we have the right element, and that the user is not dragging a
// selection (this matches native `select` event behavior). In HTML5, select
// fires only on input and textarea thus if there's no focused element we
// won't dispatch.
if (mouseDown ||
activeElement == null ||
activeElement != getActiveElement()) {
return;
}
// Only fire when selection has actually changed.
var currentSelection = getSelection(activeElement);
if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
lastSelection = currentSelection;
var syntheticEvent = SyntheticEvent.getPooled(
eventTypes.select,
activeElementID,
nativeEvent
);
syntheticEvent.type = 'select';
syntheticEvent.target = activeElement;
EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent);
return syntheticEvent;
}
}
/**
* This plugin creates an `onSelect` event that normalizes select events
* across form elements.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - contentEditable
*
* This differs from native browser implementations in the following ways:
* - Fires on contentEditable fields as well as inputs.
* - Fires for collapsed selection.
* - Fires after user input.
*/
var SelectEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
switch (topLevelType) {
// Track the input node that has focus.
case topLevelTypes.topFocus:
if (isTextInputElement(topLevelTarget) ||
topLevelTarget.contentEditable === 'true') {
activeElement = topLevelTarget;
activeElementID = topLevelTargetID;
lastSelection = null;
}
break;
case topLevelTypes.topBlur:
activeElement = null;
activeElementID = null;
lastSelection = null;
break;
// Don't fire the event while the user is dragging. This matches the
// semantics of the native select event.
case topLevelTypes.topMouseDown:
mouseDown = true;
break;
case topLevelTypes.topContextMenu:
case topLevelTypes.topMouseUp:
mouseDown = false;
return constructSelectEvent(nativeEvent);
// Chrome and IE fire non-standard event when selection is changed (and
// sometimes when it hasn't).
// Firefox doesn't support selectionchange, so check selection status
// after each key entry. The selection changes after keydown and before
// keyup, but we check on keydown as well in the case of holding down a
// key, when multiple keydown events are fired but only one keyup is.
case topLevelTypes.topSelectionChange:
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyUp:
return constructSelectEvent(nativeEvent);
}
}
};
module.exports = SelectEventPlugin;
},{"./EventConstants":16,"./EventPropagators":21,"./ReactInputSelection":63,"./SyntheticEvent":96,"./getActiveElement":122,"./isTextInputElement":137,"./keyOf":141,"./shallowEqual":153}],91:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ServerReactRootIndex
* @typechecks
*/
"use strict";
/**
* Size of the reactRoot ID space. We generate random numbers for React root
* IDs and if there's a collision the events and DOM update system will
* get confused. In the future we need a way to generate GUIDs but for
* now this will work on a smaller scale.
*/
var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53);
var ServerReactRootIndex = {
createReactRootIndex: function() {
return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX);
}
};
module.exports = ServerReactRootIndex;
},{}],92:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SimpleEventPlugin
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPluginUtils = _dereq_("./EventPluginUtils");
var EventPropagators = _dereq_("./EventPropagators");
var SyntheticClipboardEvent = _dereq_("./SyntheticClipboardEvent");
var SyntheticEvent = _dereq_("./SyntheticEvent");
var SyntheticFocusEvent = _dereq_("./SyntheticFocusEvent");
var SyntheticKeyboardEvent = _dereq_("./SyntheticKeyboardEvent");
var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent");
var SyntheticDragEvent = _dereq_("./SyntheticDragEvent");
var SyntheticTouchEvent = _dereq_("./SyntheticTouchEvent");
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
var SyntheticWheelEvent = _dereq_("./SyntheticWheelEvent");
var invariant = _dereq_("./invariant");
var keyOf = _dereq_("./keyOf");
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
blur: {
phasedRegistrationNames: {
bubbled: keyOf({onBlur: true}),
captured: keyOf({onBlurCapture: true})
}
},
click: {
phasedRegistrationNames: {
bubbled: keyOf({onClick: true}),
captured: keyOf({onClickCapture: true})
}
},
contextMenu: {
phasedRegistrationNames: {
bubbled: keyOf({onContextMenu: true}),
captured: keyOf({onContextMenuCapture: true})
}
},
copy: {
phasedRegistrationNames: {
bubbled: keyOf({onCopy: true}),
captured: keyOf({onCopyCapture: true})
}
},
cut: {
phasedRegistrationNames: {
bubbled: keyOf({onCut: true}),
captured: keyOf({onCutCapture: true})
}
},
doubleClick: {
phasedRegistrationNames: {
bubbled: keyOf({onDoubleClick: true}),
captured: keyOf({onDoubleClickCapture: true})
}
},
drag: {
phasedRegistrationNames: {
bubbled: keyOf({onDrag: true}),
captured: keyOf({onDragCapture: true})
}
},
dragEnd: {
phasedRegistrationNames: {
bubbled: keyOf({onDragEnd: true}),
captured: keyOf({onDragEndCapture: true})
}
},
dragEnter: {
phasedRegistrationNames: {
bubbled: keyOf({onDragEnter: true}),
captured: keyOf({onDragEnterCapture: true})
}
},
dragExit: {
phasedRegistrationNames: {
bubbled: keyOf({onDragExit: true}),
captured: keyOf({onDragExitCapture: true})
}
},
dragLeave: {
phasedRegistrationNames: {
bubbled: keyOf({onDragLeave: true}),
captured: keyOf({onDragLeaveCapture: true})
}
},
dragOver: {
phasedRegistrationNames: {
bubbled: keyOf({onDragOver: true}),
captured: keyOf({onDragOverCapture: true})
}
},
dragStart: {
phasedRegistrationNames: {
bubbled: keyOf({onDragStart: true}),
captured: keyOf({onDragStartCapture: true})
}
},
drop: {
phasedRegistrationNames: {
bubbled: keyOf({onDrop: true}),
captured: keyOf({onDropCapture: true})
}
},
focus: {
phasedRegistrationNames: {
bubbled: keyOf({onFocus: true}),
captured: keyOf({onFocusCapture: true})
}
},
input: {
phasedRegistrationNames: {
bubbled: keyOf({onInput: true}),
captured: keyOf({onInputCapture: true})
}
},
keyDown: {
phasedRegistrationNames: {
bubbled: keyOf({onKeyDown: true}),
captured: keyOf({onKeyDownCapture: true})
}
},
keyPress: {
phasedRegistrationNames: {
bubbled: keyOf({onKeyPress: true}),
captured: keyOf({onKeyPressCapture: true})
}
},
keyUp: {
phasedRegistrationNames: {
bubbled: keyOf({onKeyUp: true}),
captured: keyOf({onKeyUpCapture: true})
}
},
load: {
phasedRegistrationNames: {
bubbled: keyOf({onLoad: true}),
captured: keyOf({onLoadCapture: true})
}
},
error: {
phasedRegistrationNames: {
bubbled: keyOf({onError: true}),
captured: keyOf({onErrorCapture: true})
}
},
// Note: We do not allow listening to mouseOver events. Instead, use the
// onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`.
mouseDown: {
phasedRegistrationNames: {
bubbled: keyOf({onMouseDown: true}),
captured: keyOf({onMouseDownCapture: true})
}
},
mouseMove: {
phasedRegistrationNames: {
bubbled: keyOf({onMouseMove: true}),
captured: keyOf({onMouseMoveCapture: true})
}
},
mouseOut: {
phasedRegistrationNames: {
bubbled: keyOf({onMouseOut: true}),
captured: keyOf({onMouseOutCapture: true})
}
},
mouseOver: {
phasedRegistrationNames: {
bubbled: keyOf({onMouseOver: true}),
captured: keyOf({onMouseOverCapture: true})
}
},
mouseUp: {
phasedRegistrationNames: {
bubbled: keyOf({onMouseUp: true}),
captured: keyOf({onMouseUpCapture: true})
}
},
paste: {
phasedRegistrationNames: {
bubbled: keyOf({onPaste: true}),
captured: keyOf({onPasteCapture: true})
}
},
reset: {
phasedRegistrationNames: {
bubbled: keyOf({onReset: true}),
captured: keyOf({onResetCapture: true})
}
},
scroll: {
phasedRegistrationNames: {
bubbled: keyOf({onScroll: true}),
captured: keyOf({onScrollCapture: true})
}
},
submit: {
phasedRegistrationNames: {
bubbled: keyOf({onSubmit: true}),
captured: keyOf({onSubmitCapture: true})
}
},
touchCancel: {
phasedRegistrationNames: {
bubbled: keyOf({onTouchCancel: true}),
captured: keyOf({onTouchCancelCapture: true})
}
},
touchEnd: {
phasedRegistrationNames: {
bubbled: keyOf({onTouchEnd: true}),
captured: keyOf({onTouchEndCapture: true})
}
},
touchMove: {
phasedRegistrationNames: {
bubbled: keyOf({onTouchMove: true}),
captured: keyOf({onTouchMoveCapture: true})
}
},
touchStart: {
phasedRegistrationNames: {
bubbled: keyOf({onTouchStart: true}),
captured: keyOf({onTouchStartCapture: true})
}
},
wheel: {
phasedRegistrationNames: {
bubbled: keyOf({onWheel: true}),
captured: keyOf({onWheelCapture: true})
}
}
};
var topLevelEventsToDispatchConfig = {
topBlur: eventTypes.blur,
topClick: eventTypes.click,
topContextMenu: eventTypes.contextMenu,
topCopy: eventTypes.copy,
topCut: eventTypes.cut,
topDoubleClick: eventTypes.doubleClick,
topDrag: eventTypes.drag,
topDragEnd: eventTypes.dragEnd,
topDragEnter: eventTypes.dragEnter,
topDragExit: eventTypes.dragExit,
topDragLeave: eventTypes.dragLeave,
topDragOver: eventTypes.dragOver,
topDragStart: eventTypes.dragStart,
topDrop: eventTypes.drop,
topError: eventTypes.error,
topFocus: eventTypes.focus,
topInput: eventTypes.input,
topKeyDown: eventTypes.keyDown,
topKeyPress: eventTypes.keyPress,
topKeyUp: eventTypes.keyUp,
topLoad: eventTypes.load,
topMouseDown: eventTypes.mouseDown,
topMouseMove: eventTypes.mouseMove,
topMouseOut: eventTypes.mouseOut,
topMouseOver: eventTypes.mouseOver,
topMouseUp: eventTypes.mouseUp,
topPaste: eventTypes.paste,
topReset: eventTypes.reset,
topScroll: eventTypes.scroll,
topSubmit: eventTypes.submit,
topTouchCancel: eventTypes.touchCancel,
topTouchEnd: eventTypes.touchEnd,
topTouchMove: eventTypes.touchMove,
topTouchStart: eventTypes.touchStart,
topWheel: eventTypes.wheel
};
for (var topLevelType in topLevelEventsToDispatchConfig) {
topLevelEventsToDispatchConfig[topLevelType].dependencies = [topLevelType];
}
var SimpleEventPlugin = {
eventTypes: eventTypes,
/**
* Same as the default implementation, except cancels the event when return
* value is false.
*
* @param {object} Event to be dispatched.
* @param {function} Application-level callback.
* @param {string} domID DOM ID to pass to the callback.
*/
executeDispatch: function(event, listener, domID) {
var returnValue = EventPluginUtils.executeDispatch(event, listener, domID);
if (returnValue === false) {
event.stopPropagation();
event.preventDefault();
}
},
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
if (!dispatchConfig) {
return null;
}
var EventConstructor;
switch (topLevelType) {
case topLevelTypes.topInput:
case topLevelTypes.topLoad:
case topLevelTypes.topError:
case topLevelTypes.topReset:
case topLevelTypes.topSubmit:
// HTML Events
// @see http://www.w3.org/TR/html5/index.html#events-0
EventConstructor = SyntheticEvent;
break;
case topLevelTypes.topKeyPress:
// FireFox creates a keypress event for function keys too. This removes
// the unwanted keypress events.
if (nativeEvent.charCode === 0) {
return null;
}
/* falls through */
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyUp:
EventConstructor = SyntheticKeyboardEvent;
break;
case topLevelTypes.topBlur:
case topLevelTypes.topFocus:
EventConstructor = SyntheticFocusEvent;
break;
case topLevelTypes.topClick:
// Firefox creates a click event on right mouse clicks. This removes the
// unwanted click events.
if (nativeEvent.button === 2) {
return null;
}
/* falls through */
case topLevelTypes.topContextMenu:
case topLevelTypes.topDoubleClick:
case topLevelTypes.topMouseDown:
case topLevelTypes.topMouseMove:
case topLevelTypes.topMouseOut:
case topLevelTypes.topMouseOver:
case topLevelTypes.topMouseUp:
EventConstructor = SyntheticMouseEvent;
break;
case topLevelTypes.topDrag:
case topLevelTypes.topDragEnd:
case topLevelTypes.topDragEnter:
case topLevelTypes.topDragExit:
case topLevelTypes.topDragLeave:
case topLevelTypes.topDragOver:
case topLevelTypes.topDragStart:
case topLevelTypes.topDrop:
EventConstructor = SyntheticDragEvent;
break;
case topLevelTypes.topTouchCancel:
case topLevelTypes.topTouchEnd:
case topLevelTypes.topTouchMove:
case topLevelTypes.topTouchStart:
EventConstructor = SyntheticTouchEvent;
break;
case topLevelTypes.topScroll:
EventConstructor = SyntheticUIEvent;
break;
case topLevelTypes.topWheel:
EventConstructor = SyntheticWheelEvent;
break;
case topLevelTypes.topCopy:
case topLevelTypes.topCut:
case topLevelTypes.topPaste:
EventConstructor = SyntheticClipboardEvent;
break;
}
("production" !== "development" ? invariant(
EventConstructor,
'SimpleEventPlugin: Unhandled event type, `%s`.',
topLevelType
) : invariant(EventConstructor));
var event = EventConstructor.getPooled(
dispatchConfig,
topLevelTargetID,
nativeEvent
);
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
};
module.exports = SimpleEventPlugin;
},{"./EventConstants":16,"./EventPluginUtils":20,"./EventPropagators":21,"./SyntheticClipboardEvent":93,"./SyntheticDragEvent":95,"./SyntheticEvent":96,"./SyntheticFocusEvent":97,"./SyntheticKeyboardEvent":99,"./SyntheticMouseEvent":100,"./SyntheticTouchEvent":101,"./SyntheticUIEvent":102,"./SyntheticWheelEvent":103,"./invariant":134,"./keyOf":141}],93:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticClipboardEvent
* @typechecks static-only
*/
"use strict";
var SyntheticEvent = _dereq_("./SyntheticEvent");
/**
* @interface Event
* @see http://www.w3.org/TR/clipboard-apis/
*/
var ClipboardEventInterface = {
clipboardData: function(event) {
return (
'clipboardData' in event ?
event.clipboardData :
window.clipboardData
);
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface);
module.exports = SyntheticClipboardEvent;
},{"./SyntheticEvent":96}],94:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticCompositionEvent
* @typechecks static-only
*/
"use strict";
var SyntheticEvent = _dereq_("./SyntheticEvent");
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
*/
var CompositionEventInterface = {
data: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticCompositionEvent(
dispatchConfig,
dispatchMarker,
nativeEvent) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(
SyntheticCompositionEvent,
CompositionEventInterface
);
module.exports = SyntheticCompositionEvent;
},{"./SyntheticEvent":96}],95:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticDragEvent
* @typechecks static-only
*/
"use strict";
var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent");
/**
* @interface DragEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var DragEventInterface = {
dataTransfer: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface);
module.exports = SyntheticDragEvent;
},{"./SyntheticMouseEvent":100}],96:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticEvent
* @typechecks static-only
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var emptyFunction = _dereq_("./emptyFunction");
var getEventTarget = _dereq_("./getEventTarget");
var merge = _dereq_("./merge");
var mergeInto = _dereq_("./mergeInto");
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var EventInterface = {
type: null,
target: getEventTarget,
// currentTarget is set when dispatching; no use in copying it here
currentTarget: emptyFunction.thatReturnsNull,
eventPhase: null,
bubbles: null,
cancelable: null,
timeStamp: function(event) {
return event.timeStamp || Date.now();
},
defaultPrevented: null,
isTrusted: null
};
/**
* Synthetic events are dispatched by event plugins, typically in response to a
* top-level event delegation handler.
*
* These systems should generally use pooling to reduce the frequency of garbage
* collection. The system should check `isPersistent` to determine whether the
* event should be released into the pool after being dispatched. Users that
* need a persisted event should invoke `persist`.
*
* Synthetic events (and subclasses) implement the DOM Level 3 Events API by
* normalizing browser quirks. Subclasses do not necessarily have to implement a
* DOM interface; custom application-specific events can also subclass this.
*
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
*/
function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent) {
this.dispatchConfig = dispatchConfig;
this.dispatchMarker = dispatchMarker;
this.nativeEvent = nativeEvent;
var Interface = this.constructor.Interface;
for (var propName in Interface) {
if (!Interface.hasOwnProperty(propName)) {
continue;
}
var normalize = Interface[propName];
if (normalize) {
this[propName] = normalize(nativeEvent);
} else {
this[propName] = nativeEvent[propName];
}
}
var defaultPrevented = nativeEvent.defaultPrevented != null ?
nativeEvent.defaultPrevented :
nativeEvent.returnValue === false;
if (defaultPrevented) {
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
} else {
this.isDefaultPrevented = emptyFunction.thatReturnsFalse;
}
this.isPropagationStopped = emptyFunction.thatReturnsFalse;
}
mergeInto(SyntheticEvent.prototype, {
preventDefault: function() {
this.defaultPrevented = true;
var event = this.nativeEvent;
event.preventDefault ? event.preventDefault() : event.returnValue = false;
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
},
stopPropagation: function() {
var event = this.nativeEvent;
event.stopPropagation ? event.stopPropagation() : event.cancelBubble = true;
this.isPropagationStopped = emptyFunction.thatReturnsTrue;
},
/**
* We release all dispatched `SyntheticEvent`s after each event loop, adding
* them back into the pool. This allows a way to hold onto a reference that
* won't be added back into the pool.
*/
persist: function() {
this.isPersistent = emptyFunction.thatReturnsTrue;
},
/**
* Checks if this event should be released back into the pool.
*
* @return {boolean} True if this should not be released, false otherwise.
*/
isPersistent: emptyFunction.thatReturnsFalse,
/**
* `PooledClass` looks for `destructor` on each instance it releases.
*/
destructor: function() {
var Interface = this.constructor.Interface;
for (var propName in Interface) {
this[propName] = null;
}
this.dispatchConfig = null;
this.dispatchMarker = null;
this.nativeEvent = null;
}
});
SyntheticEvent.Interface = EventInterface;
/**
* Helper to reduce boilerplate when creating subclasses.
*
* @param {function} Class
* @param {?object} Interface
*/
SyntheticEvent.augmentClass = function(Class, Interface) {
var Super = this;
var prototype = Object.create(Super.prototype);
mergeInto(prototype, Class.prototype);
Class.prototype = prototype;
Class.prototype.constructor = Class;
Class.Interface = merge(Super.Interface, Interface);
Class.augmentClass = Super.augmentClass;
PooledClass.addPoolingTo(Class, PooledClass.threeArgumentPooler);
};
PooledClass.addPoolingTo(SyntheticEvent, PooledClass.threeArgumentPooler);
module.exports = SyntheticEvent;
},{"./PooledClass":28,"./emptyFunction":116,"./getEventTarget":125,"./merge":144,"./mergeInto":146}],97:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticFocusEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
/**
* @interface FocusEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var FocusEventInterface = {
relatedTarget: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface);
module.exports = SyntheticFocusEvent;
},{"./SyntheticUIEvent":102}],98:[function(_dereq_,module,exports){
/**
* Copyright 2013 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 SyntheticInputEvent
* @typechecks static-only
*/
"use strict";
var SyntheticEvent = _dereq_("./SyntheticEvent");
/**
* @interface Event
* @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
* /#events-inputevents
*/
var InputEventInterface = {
data: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticInputEvent(
dispatchConfig,
dispatchMarker,
nativeEvent) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(
SyntheticInputEvent,
InputEventInterface
);
module.exports = SyntheticInputEvent;
},{"./SyntheticEvent":96}],99:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticKeyboardEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
var getEventKey = _dereq_("./getEventKey");
var getEventModifierState = _dereq_("./getEventModifierState");
/**
* @interface KeyboardEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var KeyboardEventInterface = {
key: getEventKey,
location: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
repeat: null,
locale: null,
getModifierState: getEventModifierState,
// Legacy Interface
charCode: function(event) {
// `charCode` is the result of a KeyPress event and represents the value of
// the actual printable character.
// KeyPress is deprecated but its replacement is not yet final and not
// implemented in any major browser.
if (event.type === 'keypress') {
// IE8 does not implement "charCode", but "keyCode" has the correct value.
return 'charCode' in event ? event.charCode : event.keyCode;
}
return 0;
},
keyCode: function(event) {
// `keyCode` is the result of a KeyDown/Up event and represents the value of
// physical keyboard key.
// The actual meaning of the value depends on the users' keyboard layout
// which cannot be detected. Assuming that it is a US keyboard layout
// provides a surprisingly accurate mapping for US and European users.
// Due to this, it is left to the user to implement at this time.
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
},
which: function(event) {
// `which` is an alias for either `keyCode` or `charCode` depending on the
// type of the event. There is no need to determine the type of the event
// as `keyCode` and `charCode` are either aliased or default to zero.
return event.keyCode || event.charCode;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface);
module.exports = SyntheticKeyboardEvent;
},{"./SyntheticUIEvent":102,"./getEventKey":123,"./getEventModifierState":124}],100:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticMouseEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
var ViewportMetrics = _dereq_("./ViewportMetrics");
var getEventModifierState = _dereq_("./getEventModifierState");
/**
* @interface MouseEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var MouseEventInterface = {
screenX: null,
screenY: null,
clientX: null,
clientY: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
getModifierState: getEventModifierState,
button: function(event) {
// Webkit, Firefox, IE9+
// which: 1 2 3
// button: 0 1 2 (standard)
var button = event.button;
if ('which' in event) {
return button;
}
// IE<9
// which: undefined
// button: 0 0 0
// button: 1 4 2 (onmouseup)
return button === 2 ? 2 : button === 4 ? 1 : 0;
},
buttons: null,
relatedTarget: function(event) {
return event.relatedTarget || (
event.fromElement === event.srcElement ?
event.toElement :
event.fromElement
);
},
// "Proprietary" Interface.
pageX: function(event) {
return 'pageX' in event ?
event.pageX :
event.clientX + ViewportMetrics.currentScrollLeft;
},
pageY: function(event) {
return 'pageY' in event ?
event.pageY :
event.clientY + ViewportMetrics.currentScrollTop;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface);
module.exports = SyntheticMouseEvent;
},{"./SyntheticUIEvent":102,"./ViewportMetrics":105,"./getEventModifierState":124}],101:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticTouchEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
var getEventModifierState = _dereq_("./getEventModifierState");
/**
* @interface TouchEvent
* @see http://www.w3.org/TR/touch-events/
*/
var TouchEventInterface = {
touches: null,
targetTouches: null,
changedTouches: null,
altKey: null,
metaKey: null,
ctrlKey: null,
shiftKey: null,
getModifierState: getEventModifierState
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface);
module.exports = SyntheticTouchEvent;
},{"./SyntheticUIEvent":102,"./getEventModifierState":124}],102:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticUIEvent
* @typechecks static-only
*/
"use strict";
var SyntheticEvent = _dereq_("./SyntheticEvent");
var getEventTarget = _dereq_("./getEventTarget");
/**
* @interface UIEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var UIEventInterface = {
view: function(event) {
if (event.view) {
return event.view;
}
var target = getEventTarget(event);
if (target != null && target.window === target) {
// target is a window object
return target;
}
var doc = target.ownerDocument;
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
if (doc) {
return doc.defaultView || doc.parentWindow;
} else {
return window;
}
},
detail: function(event) {
return event.detail || 0;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticEvent}
*/
function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface);
module.exports = SyntheticUIEvent;
},{"./SyntheticEvent":96,"./getEventTarget":125}],103:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule SyntheticWheelEvent
* @typechecks static-only
*/
"use strict";
var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent");
/**
* @interface WheelEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var WheelEventInterface = {
deltaX: function(event) {
return (
'deltaX' in event ? event.deltaX :
// Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
'wheelDeltaX' in event ? -event.wheelDeltaX : 0
);
},
deltaY: function(event) {
return (
'deltaY' in event ? event.deltaY :
// Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
'wheelDeltaY' in event ? -event.wheelDeltaY :
// Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
'wheelDelta' in event ? -event.wheelDelta : 0
);
},
deltaZ: null,
// Browsers without "deltaMode" is reporting in raw wheel delta where one
// notch on the scroll is always +/- 120, roughly equivalent to pixels.
// A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
// ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
deltaMode: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticMouseEvent}
*/
function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface);
module.exports = SyntheticWheelEvent;
},{"./SyntheticMouseEvent":100}],104:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule 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" !== "development" ? 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" !== "development" ? 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":134}],105:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule 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":130}],106:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule accumulate
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* Accumulates items that must not be null or undefined.
*
* This is used to conserve memory by avoiding array allocations.
*
* @return {*|array<*>} An accumulation of items.
*/
function accumulate(current, next) {
("production" !== "development" ? invariant(
next != null,
'accumulate(...): Accumulated items must be not be null or undefined.'
) : invariant(next != null));
if (current == null) {
return next;
} else {
// Both are not empty. Warning: Never call x.concat(y) when you are not
// certain that x is an Array (x could be a string with concat method).
var currentIsArray = Array.isArray(current);
var nextIsArray = Array.isArray(next);
if (currentIsArray) {
return current.concat(next);
} else {
if (nextIsArray) {
return [current].concat(next);
} else {
return [current, next];
}
}
}
}
module.exports = accumulate;
},{"./invariant":134}],107:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule 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;
},{}],108:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @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" !== "development") {
("production" !== "development" ? 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":72,"./keyOf":141,"./warning":158}],109:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule containsNode
* @typechecks
*/
var isTextNode = _dereq_("./isTextNode");
/*jslint bitwise:true */
/**
* Checks if a given DOM node contains or is another DOM node.
*
* @param {?DOMNode} outerNode Outer DOM node.
* @param {?DOMNode} innerNode Inner DOM node.
* @return {boolean} True if `outerNode` contains or is `innerNode`.
*/
function containsNode(outerNode, innerNode) {
if (!outerNode || !innerNode) {
return false;
} else if (outerNode === innerNode) {
return true;
} else if (isTextNode(outerNode)) {
return false;
} else if (isTextNode(innerNode)) {
return containsNode(outerNode, innerNode.parentNode);
} else if (outerNode.contains) {
return outerNode.contains(innerNode);
} else if (outerNode.compareDocumentPosition) {
return !!(outerNode.compareDocumentPosition(innerNode) & 16);
} else {
return false;
}
}
module.exports = containsNode;
},{"./isTextNode":138}],110:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule copyProperties
*/
/**
* Copy properties from one or more objects (up to 5) into the first object.
* This is a shallow copy. It mutates the first object and also returns it.
*
* NOTE: `arguments` has a very significant performance penalty, which is why
* we don't support unlimited arguments.
*/
function copyProperties(obj, a, b, c, d, e, f) {
obj = obj || {};
if ("production" !== "development") {
if (f) {
throw new Error('Too many arguments passed to copyProperties');
}
}
var args = [a, b, c, d, e];
var ii = 0, v;
while (args[ii]) {
v = args[ii++];
for (var k in v) {
obj[k] = v[k];
}
// IE ignores toString in object iteration.. See:
// webreflection.blogspot.com/2007/07/quick-fix-internet-explorer-and.html
if (v.hasOwnProperty && v.hasOwnProperty('toString') &&
(typeof v.toString != 'undefined') && (obj.toString !== v.toString)) {
obj.toString = v.toString;
}
}
return obj;
}
module.exports = copyProperties;
},{}],111:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule createArrayFrom
* @typechecks
*/
var toArray = _dereq_("./toArray");
/**
* Perform a heuristic test to determine if an object is "array-like".
*
* A monk asked Joshu, a Zen master, "Has a dog Buddha nature?"
* Joshu replied: "Mu."
*
* This function determines if its argument has "array nature": it returns
* true if the argument is an actual array, an `arguments' object, or an
* HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()).
*
* It will return false for other array-like objects like Filelist.
*
* @param {*} obj
* @return {boolean}
*/
function hasArrayNature(obj) {
return (
// not null/false
!!obj &&
// arrays are objects, NodeLists are functions in Safari
(typeof obj == 'object' || typeof obj == 'function') &&
// quacks like an array
('length' in obj) &&
// not window
!('setInterval' in obj) &&
// no DOM node should be considered an array-like
// a 'select' element has 'length' and 'item' properties on IE8
(typeof obj.nodeType != 'number') &&
(
// a real array
(// HTMLCollection/NodeList
(Array.isArray(obj) ||
// arguments
('callee' in obj) || 'item' in obj))
)
);
}
/**
* Ensure that the argument is an array by wrapping it in an array if it is not.
* Creates a copy of the argument if it is already an array.
*
* This is mostly useful idiomatically:
*
* var createArrayFrom = require('createArrayFrom');
*
* function takesOneOrMoreThings(things) {
* things = createArrayFrom(things);
* ...
* }
*
* This allows you to treat `things' as an array, but accept scalars in the API.
*
* If you need to convert an array-like object, like `arguments`, into an array
* use toArray instead.
*
* @param {*} obj
* @return {array}
*/
function createArrayFrom(obj) {
if (!hasArrayNature(obj)) {
return [obj];
} else if (Array.isArray(obj)) {
return obj.slice();
} else {
return toArray(obj);
}
}
module.exports = createArrayFrom;
},{"./toArray":155}],112:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule createFullPageComponent
* @typechecks
*/
"use strict";
// Defeat circular references by requiring this directly.
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var invariant = _dereq_("./invariant");
/**
* Create a component that will throw an exception when unmounted.
*
* Components like <html> <head> and <body> can't be removed or added
* easily in a cross-browser way, however it's valuable to be able to
* take advantage of React's reconciliation for styling and <title>
* management. So we just document it and throw in dangerous cases.
*
* @param {function} componentClass convenience constructor to wrap
* @return {function} convenience constructor of new component
*/
function createFullPageComponent(componentClass) {
var FullPageComponent = ReactCompositeComponent.createClass({
displayName: 'ReactFullPageComponent' + (
componentClass.type.displayName || ''
),
componentWillUnmount: function() {
("production" !== "development" ? invariant(
false,
'%s tried to unmount. Because of cross-browser quirks it is ' +
'impossible to unmount some top-level components (eg <html>, <head>, ' +
'and <body>) reliably and efficiently. To fix this, have a single ' +
'top-level component that never unmounts render these elements.',
this.constructor.displayName
) : invariant(false));
},
render: function() {
return this.transferPropsTo(componentClass(null, this.props.children));
}
});
return FullPageComponent;
}
module.exports = createFullPageComponent;
},{"./ReactCompositeComponent":38,"./invariant":134}],113:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule createNodesFromMarkup
* @typechecks
*/
/*jslint evil: true, sub: true */
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var createArrayFrom = _dereq_("./createArrayFrom");
var getMarkupWrap = _dereq_("./getMarkupWrap");
var invariant = _dereq_("./invariant");
/**
* Dummy container used to render all markup.
*/
var dummyNode =
ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Pattern used by `getNodeName`.
*/
var nodeNamePattern = /^\s*<(\w+)/;
/**
* Extracts the `nodeName` of the first element in a string of markup.
*
* @param {string} markup String of markup.
* @return {?string} Node name of the supplied markup.
*/
function getNodeName(markup) {
var nodeNameMatch = markup.match(nodeNamePattern);
return nodeNameMatch && nodeNameMatch[1].toLowerCase();
}
/**
* Creates an array containing the nodes rendered from the supplied markup. The
* optionally supplied `handleScript` function will be invoked once for each
* <script> element that is rendered. If no `handleScript` function is supplied,
* an exception is thrown if any <script> elements are rendered.
*
* @param {string} markup A string of valid HTML markup.
* @param {?function} handleScript Invoked once for each rendered <script>.
* @return {array<DOMElement|DOMTextNode>} An array of rendered nodes.
*/
function createNodesFromMarkup(markup, handleScript) {
var node = dummyNode;
("production" !== "development" ? invariant(!!dummyNode, 'createNodesFromMarkup dummy not initialized') : invariant(!!dummyNode));
var nodeName = getNodeName(markup);
var wrap = nodeName && getMarkupWrap(nodeName);
if (wrap) {
node.innerHTML = wrap[1] + markup + wrap[2];
var wrapDepth = wrap[0];
while (wrapDepth--) {
node = node.lastChild;
}
} else {
node.innerHTML = markup;
}
var scripts = node.getElementsByTagName('script');
if (scripts.length) {
("production" !== "development" ? invariant(
handleScript,
'createNodesFromMarkup(...): Unexpected <script> element rendered.'
) : invariant(handleScript));
createArrayFrom(scripts).forEach(handleScript);
}
var nodes = createArrayFrom(node.childNodes);
while (node.lastChild) {
node.removeChild(node.lastChild);
}
return nodes;
}
module.exports = createNodesFromMarkup;
},{"./ExecutionEnvironment":22,"./createArrayFrom":111,"./getMarkupWrap":126,"./invariant":134}],114:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule 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;
},{}],115:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule dangerousStyleValue
* @typechecks static-only
*/
"use strict";
var CSSProperty = _dereq_("./CSSProperty");
var isUnitlessNumber = CSSProperty.isUnitlessNumber;
/**
* Convert a value into the proper css writable value. The style name `name`
* should be logical (no hyphens), as specified
* in `CSSProperty.isUnitlessNumber`.
*
* @param {string} name CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(name, value) {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
var isEmpty = value == null || typeof value === 'boolean' || value === '';
if (isEmpty) {
return '';
}
var isNonNumeric = isNaN(value);
if (isNonNumeric || value === 0 ||
isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) {
return '' + value; // cast to string
}
if (typeof value === 'string') {
value = value.trim();
}
return value + 'px';
}
module.exports = dangerousStyleValue;
},{"./CSSProperty":4}],116:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule 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":110}],117:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule emptyObject
*/
"use strict";
var emptyObject = {};
if ("production" !== "development") {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
},{}],118:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule escapeTextForBrowser
* @typechecks static-only
*/
"use strict";
var ESCAPE_LOOKUP = {
"&": "&",
">": ">",
"<": "<",
"\"": """,
"'": "'"
};
var ESCAPE_REGEX = /[&><"']/g;
function escaper(match) {
return ESCAPE_LOOKUP[match];
}
/**
* Escapes text to prevent scripting attacks.
*
* @param {*} text Text value to escape.
* @return {string} An escaped string.
*/
function escapeTextForBrowser(text) {
return ('' + text).replace(ESCAPE_REGEX, escaper);
}
module.exports = escapeTextForBrowser;
},{}],119:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule flattenChildren
*/
"use strict";
var traverseAllChildren = _dereq_("./traverseAllChildren");
var warning = _dereq_("./warning");
/**
* @param {function} traverseContext Context passed through traversal.
* @param {?ReactComponent} child React child component.
* @param {!string} name String name of key path to child.
*/
function flattenSingleChildIntoContext(traverseContext, child, name) {
// We found a component instance.
var result = traverseContext;
var keyUnique = !result.hasOwnProperty(name);
("production" !== "development" ? warning(
keyUnique,
'flattenChildren(...): Encountered two children with the same key, ' +
'`%s`. Child keys must be unique; when two children share a key, only ' +
'the first child will be used.',
name
) : null);
if (keyUnique && child != null) {
result[name] = child;
}
}
/**
* Flattens children that are typically specified as `props.children`. Any null
* children will not be included in the resulting object.
* @return {!object} flattened children keyed by name.
*/
function flattenChildren(children) {
if (children == null) {
return children;
}
var result = {};
traverseAllChildren(children, flattenSingleChildIntoContext, result);
return result;
}
module.exports = flattenChildren;
},{"./traverseAllChildren":156,"./warning":158}],120:[function(_dereq_,module,exports){
/**
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule focusNode
*/
"use strict";
/**
* IE8 throws if an input/textarea is disabled and we try to focus it.
* Focus only when necessary.
*
* @param {DOMElement} node input/textarea to focus
*/
function focusNode(node) {
if (!node.disabled) {
node.focus();
}
}
module.exports = focusNode;
},{}],121:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule 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;
},{}],122:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule getActiveElement
* @typechecks
*/
/**
* Same as document.activeElement but wraps in a try-catch block. In IE it is
* not safe to call document.activeElement if there is nothing focused.
*
* The activeElement will be null only if the document body is not yet defined.
*/
function getActiveElement() /*?DOMElement*/ {
try {
return document.activeElement || document.body;
} catch (e) {
return document.body;
}
}
module.exports = getActiveElement;
},{}],123:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule getEventKey
* @typechecks static-only
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* Normalization of deprecated HTML5 `key` values
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/
var normalizeKey = {
'Esc': 'Escape',
'Spacebar': ' ',
'Left': 'ArrowLeft',
'Up': 'ArrowUp',
'Right': 'ArrowRight',
'Down': 'ArrowDown',
'Del': 'Delete',
'Win': 'OS',
'Menu': 'ContextMenu',
'Apps': 'ContextMenu',
'Scroll': 'ScrollLock',
'MozPrintableKey': 'Unidentified'
};
/**
* Translation from legacy `which`/`keyCode` to HTML5 `key`
* Only special keys supported, all others depend on keyboard layout or browser
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/
var translateToKey = {
8: 'Backspace',
9: 'Tab',
12: 'Clear',
13: 'Enter',
16: 'Shift',
17: 'Control',
18: 'Alt',
19: 'Pause',
20: 'CapsLock',
27: 'Escape',
32: ' ',
33: 'PageUp',
34: 'PageDown',
35: 'End',
36: 'Home',
37: 'ArrowLeft',
38: 'ArrowUp',
39: 'ArrowRight',
40: 'ArrowDown',
45: 'Insert',
46: 'Delete',
112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6',
118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12',
144: 'NumLock',
145: 'ScrollLock',
224: 'Meta'
};
/**
* @param {object} nativeEvent Native browser event.
* @return {string} Normalized `key` property.
*/
function getEventKey(nativeEvent) {
if (nativeEvent.key) {
// Normalize inconsistent values reported by browsers due to
// implementations of a working draft specification.
// FireFox implements `key` but returns `MozPrintableKey` for all
// printable characters (normalized to `Unidentified`), ignore it.
var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
if (key !== 'Unidentified') {
return key;
}
}
// Browser does not implement `key`, polyfill as much of it as we can.
if (nativeEvent.type === 'keypress') {
// Create the character from the `charCode` ourselves and use as an almost
// perfect replacement.
var charCode = 'charCode' in nativeEvent ?
nativeEvent.charCode :
nativeEvent.keyCode;
// The enter-key is technically both printable and non-printable and can
// thus be captured by `keypress`, no other non-printable key should.
return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
}
if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
// While user keyboard layout determines the actual meaning of each
// `keyCode` value, almost all function keys have a universal value.
return translateToKey[nativeEvent.keyCode] || 'Unidentified';
}
("production" !== "development" ? invariant(false, "Unexpected keyboard event type: %s", nativeEvent.type) : invariant(false));
}
module.exports = getEventKey;
},{"./invariant":134}],124:[function(_dereq_,module,exports){
/**
* Copyright 2013 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 getEventModifierState
* @typechecks static-only
*/
"use strict";
/**
* Translation from modifier key to the associated property in the event.
* @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
*/
var modifierKeyToProp = {
'Alt': 'altKey',
'Control': 'ctrlKey',
'Meta': 'metaKey',
'Shift': 'shiftKey'
};
// IE8 does not implement getModifierState so we simply map it to the only
// modifier keys exposed by the event itself, does not support Lock-keys.
// Currently, all major browsers except Chrome seems to support Lock-keys.
function modifierStateGetter(keyArg) {
/*jshint validthis:true */
var syntheticEvent = this;
var nativeEvent = syntheticEvent.nativeEvent;
if (nativeEvent.getModifierState) {
return nativeEvent.getModifierState(keyArg);
}
var keyProp = modifierKeyToProp[keyArg];
return keyProp ? !!nativeEvent[keyProp] : false;
}
function getEventModifierState(nativeEvent) {
return modifierStateGetter;
}
module.exports = getEventModifierState;
},{}],125:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule getEventTarget
* @typechecks static-only
*/
"use strict";
/**
* Gets the target node from a native browser event by accounting for
* inconsistencies in browser DOM APIs.
*
* @param {object} nativeEvent Native browser event.
* @return {DOMEventTarget} Target node.
*/
function getEventTarget(nativeEvent) {
var target = nativeEvent.target || nativeEvent.srcElement || window;
// Safari may fire events on text nodes (Node.TEXT_NODE is 3).
// @see http://www.quirksmode.org/js/events_properties.html
return target.nodeType === 3 ? target.parentNode : target;
}
module.exports = getEventTarget;
},{}],126:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule getMarkupWrap
*/
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var invariant = _dereq_("./invariant");
/**
* Dummy container used to detect which wraps are necessary.
*/
var dummyNode =
ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Some browsers cannot use `innerHTML` to render certain elements standalone,
* so we wrap them, render the wrapped nodes, then extract the desired node.
*
* In IE8, certain elements cannot render alone, so wrap all elements ('*').
*/
var shouldWrap = {
// Force wrapping for SVG elements because if they get created inside a <div>,
// they will be initialized in the wrong namespace (and will not display).
'circle': true,
'defs': true,
'ellipse': true,
'g': true,
'line': true,
'linearGradient': true,
'path': true,
'polygon': true,
'polyline': true,
'radialGradient': true,
'rect': true,
'stop': true,
'text': true
};
var selectWrap = [1, '<select multiple="true">', '</select>'];
var tableWrap = [1, '<table>', '</table>'];
var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
var svgWrap = [1, '<svg>', '</svg>'];
var markupWrap = {
'*': [1, '?<div>', '</div>'],
'area': [1, '<map>', '</map>'],
'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
'legend': [1, '<fieldset>', '</fieldset>'],
'param': [1, '<object>', '</object>'],
'tr': [2, '<table><tbody>', '</tbody></table>'],
'optgroup': selectWrap,
'option': selectWrap,
'caption': tableWrap,
'colgroup': tableWrap,
'tbody': tableWrap,
'tfoot': tableWrap,
'thead': tableWrap,
'td': trWrap,
'th': trWrap,
'circle': svgWrap,
'defs': svgWrap,
'ellipse': svgWrap,
'g': svgWrap,
'line': svgWrap,
'linearGradient': svgWrap,
'path': svgWrap,
'polygon': svgWrap,
'polyline': svgWrap,
'radialGradient': svgWrap,
'rect': svgWrap,
'stop': svgWrap,
'text': svgWrap
};
/**
* Gets the markup wrap configuration for the supplied `nodeName`.
*
* NOTE: This lazily detects which wraps are necessary for the current browser.
*
* @param {string} nodeName Lowercase `nodeName`.
* @return {?array} Markup wrap configuration, if applicable.
*/
function getMarkupWrap(nodeName) {
("production" !== "development" ? invariant(!!dummyNode, 'Markup wrapping node not initialized') : invariant(!!dummyNode));
if (!markupWrap.hasOwnProperty(nodeName)) {
nodeName = '*';
}
if (!shouldWrap.hasOwnProperty(nodeName)) {
if (nodeName === '*') {
dummyNode.innerHTML = '<link />';
} else {
dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>';
}
shouldWrap[nodeName] = !dummyNode.firstChild;
}
return shouldWrap[nodeName] ? markupWrap[nodeName] : null;
}
module.exports = getMarkupWrap;
},{"./ExecutionEnvironment":22,"./invariant":134}],127:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule getNodeForCharacterOffset
*/
"use strict";
/**
* Given any node return the first leaf node without children.
*
* @param {DOMElement|DOMTextNode} node
* @return {DOMElement|DOMTextNode}
*/
function getLeafNode(node) {
while (node && node.firstChild) {
node = node.firstChild;
}
return node;
}
/**
* Get the next sibling within a container. This will walk up the
* DOM if a node's siblings have been exhausted.
*
* @param {DOMElement|DOMTextNode} node
* @return {?DOMElement|DOMTextNode}
*/
function getSiblingNode(node) {
while (node) {
if (node.nextSibling) {
return node.nextSibling;
}
node = node.parentNode;
}
}
/**
* Get object describing the nodes which contain characters at offset.
*
* @param {DOMElement|DOMTextNode} root
* @param {number} offset
* @return {?object}
*/
function getNodeForCharacterOffset(root, offset) {
var node = getLeafNode(root);
var nodeStart = 0;
var nodeEnd = 0;
while (node) {
if (node.nodeType == 3) {
nodeEnd = nodeStart + node.textContent.length;
if (nodeStart <= offset && nodeEnd >= offset) {
return {
node: node,
offset: offset - nodeStart
};
}
nodeStart = nodeEnd;
}
node = getLeafNode(getSiblingNode(node));
}
}
module.exports = getNodeForCharacterOffset;
},{}],128:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule getReactRootElementInContainer
*/
"use strict";
var DOC_NODE_TYPE = 9;
/**
* @param {DOMElement|DOMDocument} container DOM element that may contain
* a React component
* @return {?*} DOM element that may have the reactRoot ID, or null.
*/
function getReactRootElementInContainer(container) {
if (!container) {
return null;
}
if (container.nodeType === DOC_NODE_TYPE) {
return container.documentElement;
} else {
return container.firstChild;
}
}
module.exports = getReactRootElementInContainer;
},{}],129:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule getTextContentAccessor
*/
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var contentKey = null;
/**
* Gets the key used to access text content on a DOM node.
*
* @return {?string} Key used to access text content.
* @internal
*/
function getTextContentAccessor() {
if (!contentKey && ExecutionEnvironment.canUseDOM) {
// Prefer textContent to innerText because many browsers support both but
// SVG <text> elements don't support innerText even when <div> does.
contentKey = 'textContent' in document.documentElement ?
'textContent' :
'innerText';
}
return contentKey;
}
module.exports = getTextContentAccessor;
},{"./ExecutionEnvironment":22}],130:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule 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;
},{}],131:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule hyphenate
* @typechecks
*/
var _uppercasePattern = /([A-Z])/g;
/**
* Hyphenates a camelcased string, for example:
*
* > hyphenate('backgroundColor')
* < "background-color"
*
* For CSS style names, use `hyphenateStyleName` instead which works properly
* with all vendor prefixes, including `ms`.
*
* @param {string} string
* @return {string}
*/
function hyphenate(string) {
return string.replace(_uppercasePattern, '-$1').toLowerCase();
}
module.exports = hyphenate;
},{}],132:[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 hyphenateStyleName
* @typechecks
*/
"use strict";
var hyphenate = _dereq_("./hyphenate");
var msPattern = /^ms-/;
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenate('backgroundColor')
* < "background-color"
* > hyphenate('MozTransition')
* < "-moz-transition"
* > hyphenate('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*
* @param {string} string
* @return {string}
*/
function hyphenateStyleName(string) {
return hyphenate(string).replace(msPattern, '-ms-');
}
module.exports = hyphenateStyleName;
},{"./hyphenate":131}],133:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule 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" !== "development" ? invariant(
isValidComponentDescriptor(descriptor),
'Only React Components are valid for mounting.'
) : invariant(isValidComponentDescriptor(descriptor)));
// }
return new descriptor.type(descriptor);
}
module.exports = instantiateReactComponent;
},{"./invariant":134}],134:[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" !== "development") {
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;
},{}],135:[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":22}],136:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule isNode
* @typechecks
*/
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM node.
*/
function isNode(object) {
return !!(object && (
typeof Node === 'function' ? object instanceof Node :
typeof object === 'object' &&
typeof object.nodeType === 'number' &&
typeof object.nodeName === 'string'
));
}
module.exports = isNode;
},{}],137:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule isTextInputElement
*/
"use strict";
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
*/
var supportedInputTypes = {
'color': true,
'date': true,
'datetime': true,
'datetime-local': true,
'email': true,
'month': true,
'number': true,
'password': true,
'range': true,
'search': true,
'tel': true,
'text': true,
'time': true,
'url': true,
'week': true
};
function isTextInputElement(elem) {
return elem && (
(elem.nodeName === 'INPUT' && supportedInputTypes[elem.type]) ||
elem.nodeName === 'TEXTAREA'
);
}
module.exports = isTextInputElement;
},{}],138:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule isTextNode
* @typechecks
*/
var isNode = _dereq_("./isNode");
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM text node.
*/
function isTextNode(object) {
return isNode(object) && object.nodeType == 3;
}
module.exports = isTextNode;
},{"./isNode":136}],139:[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;
},{}],140:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule keyMirror
* @typechecks static-only
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* Constructs an enumeration with keys equal to their value.
*
* For example:
*
* var COLORS = keyMirror({blue: null, red: null});
* var myColor = COLORS.blue;
* var isColorValid = !!COLORS[myColor];
*
* The last line could not be performed if the values of the generated enum were
* not equal to their keys.
*
* Input: {key1: val1, key2: val2}
* Output: {key1: key1, key2: key2}
*
* @param {object} obj
* @return {object}
*/
var keyMirror = function(obj) {
var ret = {};
var key;
("production" !== "development" ? invariant(
obj instanceof Object && !Array.isArray(obj),
'keyMirror(...): Argument must be an object.'
) : invariant(obj instanceof Object && !Array.isArray(obj)));
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
};
module.exports = keyMirror;
},{"./invariant":134}],141:[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;
},{}],142:[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 mapObject
*/
"use strict";
/**
* For each key/value pair, invokes callback func and constructs a resulting
* object which contains, for every key in obj, values that are the result of
* of invoking the function:
*
* func(value, key, iteration)
*
* Grepable names:
*
* function objectMap()
* function objMap()
*
* @param {?object} obj Object to map keys over
* @param {function} func Invoked for each key/val pair.
* @param {?*} context
* @return {?object} Result of mapping or null if obj is falsey
*/
function mapObject(obj, func, context) {
if (!obj) {
return null;
}
var i = 0;
var ret = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
ret[key] = func.call(context, obj[key], key, i++);
}
}
return ret;
}
module.exports = mapObject;
},{}],143:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule memoizeStringOnly
* @typechecks static-only
*/
"use strict";
/**
* Memoizes the return value of a function that accepts one string argument.
*
* @param {function} callback
* @return {function}
*/
function memoizeStringOnly(callback) {
var cache = {};
return function(string) {
if (cache.hasOwnProperty(string)) {
return cache[string];
} else {
return cache[string] = callback.call(this, string);
}
};
}
module.exports = memoizeStringOnly;
},{}],144:[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":146}],145:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule mergeHelpers
*
* requiresPolyfills: Array.isArray
*/
"use strict";
var invariant = _dereq_("./invariant");
var keyMirror = _dereq_("./keyMirror");
/**
* Maximum number of levels to traverse. Will catch circular structures.
* @const
*/
var MAX_MERGE_DEPTH = 36;
/**
* We won't worry about edge cases like new String('x') or new Boolean(true).
* Functions are considered terminals, and arrays are not.
* @param {*} o The item/object/value to test.
* @return {boolean} true iff the argument is a terminal.
*/
var isTerminal = function(o) {
return typeof o !== 'object' || o === null;
};
var mergeHelpers = {
MAX_MERGE_DEPTH: MAX_MERGE_DEPTH,
isTerminal: isTerminal,
/**
* Converts null/undefined values into empty object.
*
* @param {?Object=} arg Argument to be normalized (nullable optional)
* @return {!Object}
*/
normalizeMergeArg: function(arg) {
return arg === undefined || arg === null ? {} : arg;
},
/**
* If merging Arrays, a merge strategy *must* be supplied. If not, it is
* likely the caller's fault. If this function is ever called with anything
* but `one` and `two` being `Array`s, it is the fault of the merge utilities.
*
* @param {*} one Array to merge into.
* @param {*} two Array to merge from.
*/
checkMergeArrayArgs: function(one, two) {
("production" !== "development" ? invariant(
Array.isArray(one) && Array.isArray(two),
'Tried to merge arrays, instead got %s and %s.',
one,
two
) : invariant(Array.isArray(one) && Array.isArray(two)));
},
/**
* @param {*} one Object to merge into.
* @param {*} two Object to merge from.
*/
checkMergeObjectArgs: function(one, two) {
mergeHelpers.checkMergeObjectArg(one);
mergeHelpers.checkMergeObjectArg(two);
},
/**
* @param {*} arg
*/
checkMergeObjectArg: function(arg) {
("production" !== "development" ? invariant(
!isTerminal(arg) && !Array.isArray(arg),
'Tried to merge an object, instead got %s.',
arg
) : invariant(!isTerminal(arg) && !Array.isArray(arg)));
},
/**
* @param {*} arg
*/
checkMergeIntoObjectArg: function(arg) {
("production" !== "development" ? 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" !== "development" ? invariant(
level < MAX_MERGE_DEPTH,
'Maximum deep merge depth exceeded. You may be attempting to merge ' +
'circular structures in an unsupported way.'
) : invariant(level < MAX_MERGE_DEPTH));
},
/**
* Checks that the supplied merge strategy is valid.
*
* @param {string} Array merge strategy.
*/
checkArrayStrategy: function(strategy) {
("production" !== "development" ? invariant(
strategy === undefined || strategy in mergeHelpers.ArrayStrategies,
'You must provide an array strategy to deep merge functions to ' +
'instruct the deep merge how to resolve merging two arrays.'
) : invariant(strategy === undefined || strategy in mergeHelpers.ArrayStrategies));
},
/**
* Set of possible behaviors of merge algorithms when encountering two Arrays
* that must be merged together.
* - `clobber`: The left `Array` is ignored.
* - `indexByIndex`: The result is achieved by recursively deep merging at
* each index. (not yet supported.)
*/
ArrayStrategies: keyMirror({
Clobber: true,
IndexByIndex: true
})
};
module.exports = mergeHelpers;
},{"./invariant":134,"./keyMirror":140}],146:[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":145}],147:[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;
},{}],148:[function(_dereq_,module,exports){
/**
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule monitorCodeUse
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* Provides open-source compatible instrumentation for monitoring certain API
* uses before we're ready to issue a warning or refactor. It accepts an event
* name which may only contain the characters [a-z0-9_] and an optional data
* object with further information.
*/
function monitorCodeUse(eventName, data) {
("production" !== "development" ? invariant(
eventName && !/[^a-z0-9_]/.test(eventName),
'You must provide an eventName using only the characters [a-z0-9_]'
) : invariant(eventName && !/[^a-z0-9_]/.test(eventName)));
}
module.exports = monitorCodeUse;
},{"./invariant":134}],149:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule onlyChild
*/
"use strict";
var ReactDescriptor = _dereq_("./ReactDescriptor");
var invariant = _dereq_("./invariant");
/**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection. The current implementation of this
* function assumes that a single child gets passed without a wrapper, but the
* purpose of this helper function is to abstract away the particular structure
* of children.
*
* @param {?object} children Child collection structure.
* @return {ReactComponent} The first and only `ReactComponent` contained in the
* structure.
*/
function onlyChild(children) {
("production" !== "development" ? invariant(
ReactDescriptor.isValidDescriptor(children),
'onlyChild must be passed a children with exactly one child.'
) : invariant(ReactDescriptor.isValidDescriptor(children)));
return children;
}
module.exports = onlyChild;
},{"./ReactDescriptor":56,"./invariant":134}],150:[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 performance
* @typechecks
*/
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var performance;
if (ExecutionEnvironment.canUseDOM) {
performance =
window.performance ||
window.msPerformance ||
window.webkitPerformance;
}
module.exports = performance || {};
},{"./ExecutionEnvironment":22}],151:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule performanceNow
* @typechecks
*/
var performance = _dereq_("./performance");
/**
* Detect if we can use `window.performance.now()` and gracefully fallback to
* `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now
* because of Facebook's testing infrastructure.
*/
if (!performance || !performance.now) {
performance = Date;
}
var performanceNow = performance.now.bind(performance);
module.exports = performanceNow;
},{"./performance":150}],152:[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 setInnerHTML
*/
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
/**
* Set the innerHTML property of a node, ensuring that whitespace is preserved
* even in IE8.
*
* @param {DOMElement} node
* @param {string} html
* @internal
*/
var setInnerHTML = function(node, html) {
node.innerHTML = html;
};
if (ExecutionEnvironment.canUseDOM) {
// IE8: When updating a just created node with innerHTML only leading
// whitespace is removed. When updating an existing node with innerHTML
// whitespace in root TextNodes is also collapsed.
// @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html
// Feature detection; only IE8 is known to behave improperly like this.
var testElement = document.createElement('div');
testElement.innerHTML = ' ';
if (testElement.innerHTML === '') {
setInnerHTML = function(node, html) {
// Magic theory: IE8 supposedly differentiates between added and updated
// nodes when processing innerHTML, innerHTML on updated nodes suffers
// from worse whitespace behavior. Re-adding a node like this triggers
// the initial and more favorable whitespace behavior.
// TODO: What to do on a detached node?
if (node.parentNode) {
node.parentNode.replaceChild(node, node);
}
// We also implement a workaround for non-visible tags disappearing into
// thin air on IE8, this only happens if there is no visible text
// in-front of the non-visible tags. Piggyback on the whitespace fix
// and simply check if any non-visible tags appear in the source.
if (html.match(/^[ \r\n\t\f]/) ||
html[0] === '<' && (
html.indexOf('<noscript') !== -1 ||
html.indexOf('<script') !== -1 ||
html.indexOf('<style') !== -1 ||
html.indexOf('<meta') !== -1 ||
html.indexOf('<link') !== -1)) {
// Recover leading whitespace by temporarily prepending any character.
// \uFEFF has the potential advantage of being zero-width/invisible.
node.innerHTML = '\uFEFF' + html;
// deleteData leaves an empty `TextNode` which offsets the index of all
// children. Definitely want to avoid this.
var textNode = node.firstChild;
if (textNode.data.length === 1) {
node.removeChild(textNode);
} else {
textNode.deleteData(0, 1);
}
} else {
node.innerHTML = html;
}
};
}
}
module.exports = setInnerHTML;
},{"./ExecutionEnvironment":22}],153:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule shallowEqual
*/
"use strict";
/**
* Performs equality by iterating through keys on an object and returning
* false when any key has values which are not strictly equal between
* objA and objB. Returns true when the values of all keys are strictly equal.
*
* @return {boolean}
*/
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
var key;
// Test for A's keys different from B.
for (key in objA) {
if (objA.hasOwnProperty(key) &&
(!objB.hasOwnProperty(key) || objA[key] !== objB[key])) {
return false;
}
}
// Test for B'a keys missing from A.
for (key in objB) {
if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
},{}],154:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule shouldUpdateReactComponent
* @typechecks static-only
*/
"use strict";
/**
* Given a `prevDescriptor` and `nextDescriptor`, determines if the existing
* instance should be updated as opposed to being destroyed or replaced by a new
* instance. Both arguments are descriptors. This ensures that this logic can
* operate on stateless trees without any backing instance.
*
* @param {?object} prevDescriptor
* @param {?object} nextDescriptor
* @return {boolean} True if the existing instance should be updated.
* @protected
*/
function shouldUpdateReactComponent(prevDescriptor, nextDescriptor) {
if (prevDescriptor && nextDescriptor &&
prevDescriptor.type === nextDescriptor.type && (
(prevDescriptor.props && prevDescriptor.props.key) ===
(nextDescriptor.props && nextDescriptor.props.key)
) && prevDescriptor._owner === nextDescriptor._owner) {
return true;
}
return false;
}
module.exports = shouldUpdateReactComponent;
},{}],155:[function(_dereq_,module,exports){
/**
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule toArray
* @typechecks
*/
var invariant = _dereq_("./invariant");
/**
* Convert array-like objects to arrays.
*
* This API assumes the caller knows the contents of the data type. For less
* well defined inputs use createArrayFrom.
*
* @param {object|function|filelist} obj
* @return {array}
*/
function toArray(obj) {
var length = obj.length;
// Some browse builtin objects can report typeof 'function' (e.g. NodeList in
// old versions of Safari).
("production" !== "development" ? invariant(
!Array.isArray(obj) &&
(typeof obj === 'object' || typeof obj === 'function'),
'toArray: Array-like object expected'
) : invariant(!Array.isArray(obj) &&
(typeof obj === 'object' || typeof obj === 'function')));
("production" !== "development" ? invariant(
typeof length === 'number',
'toArray: Object needs a length property'
) : invariant(typeof length === 'number'));
("production" !== "development" ? invariant(
length === 0 ||
(length - 1) in obj,
'toArray: Object should have keys for indices'
) : invariant(length === 0 ||
(length - 1) in obj));
// Old IE doesn't give collections access to hasOwnProperty. Assume inputs
// without method will throw during the slice call and skip straight to the
// fallback.
if (obj.hasOwnProperty) {
try {
return Array.prototype.slice.call(obj);
} catch (e) {
// IE < 9 does not support Array#slice on collections objects
}
}
// Fall back to copying key by key. This assumes all keys have a value,
// so will not preserve sparsely populated inputs.
var ret = Array(length);
for (var ii = 0; ii < length; ii++) {
ret[ii] = obj[ii];
}
return ret;
}
module.exports = toArray;
},{"./invariant":134}],156:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule traverseAllChildren
*/
"use strict";
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactTextComponent = _dereq_("./ReactTextComponent");
var invariant = _dereq_("./invariant");
var SEPARATOR = ReactInstanceHandles.SEPARATOR;
var SUBSEPARATOR = ':';
/**
* TODO: Test that:
* 1. `mapChildren` transforms strings and numbers into `ReactTextComponent`.
* 2. it('should fail when supplied duplicate key', function() {
* 3. That a single child and an array with one item have the same key pattern.
* });
*/
var userProvidedKeyEscaperLookup = {
'=': '=0',
'.': '=1',
':': '=2'
};
var userProvidedKeyEscapeRegex = /[=.:]/g;
function userProvidedKeyEscaper(match) {
return userProvidedKeyEscaperLookup[match];
}
/**
* Generate a key string that identifies a component within a set.
*
* @param {*} component A component that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
*/
function getComponentKey(component, index) {
if (component && component.props && component.props.key != null) {
// Explicit key
return wrapUserProvidedKey(component.props.key);
}
// Implicit key determined by the index in the set
return index.toString(36);
}
/**
* Escape a component key so that it is safe to use in a reactid.
*
* @param {*} key Component key to be escaped.
* @return {string} An escaped string.
*/
function escapeUserProvidedKey(text) {
return ('' + text).replace(
userProvidedKeyEscapeRegex,
userProvidedKeyEscaper
);
}
/**
* Wrap a `key` value explicitly provided by the user to distinguish it from
* implicitly-generated keys generated by a component's index in its parent.
*
* @param {string} key Value of a user-provided `key` attribute
* @return {string}
*/
function wrapUserProvidedKey(key) {
return '$' + escapeUserProvidedKey(key);
}
/**
* @param {?*} children Children tree container.
* @param {!string} nameSoFar Name of the key path so far.
* @param {!number} indexSoFar Number of children encountered until this point.
* @param {!function} callback Callback to invoke with each child found.
* @param {?*} traverseContext Used to pass information throughout the traversal
* process.
* @return {!number} The number of children in this subtree.
*/
var traverseAllChildrenImpl =
function(children, nameSoFar, indexSoFar, callback, traverseContext) {
var subtreeCount = 0; // Count of children found in the current subtree.
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
var child = children[i];
var nextName = (
nameSoFar +
(nameSoFar ? SUBSEPARATOR : SEPARATOR) +
getComponentKey(child, i)
);
var nextIndex = indexSoFar + subtreeCount;
subtreeCount += traverseAllChildrenImpl(
child,
nextName,
nextIndex,
callback,
traverseContext
);
}
} else {
var type = typeof children;
var isOnlyChild = nameSoFar === '';
// If it's the only child, treat the name as if it was wrapped in an array
// so that it's consistent if the number of children grows
var storageName =
isOnlyChild ? SEPARATOR + getComponentKey(children, 0) : nameSoFar;
if (children == null || type === 'boolean') {
// All of the above are perceived as null.
callback(traverseContext, null, storageName, indexSoFar);
subtreeCount = 1;
} else if (children.type && children.type.prototype &&
children.type.prototype.mountComponentIntoNode) {
callback(traverseContext, children, storageName, indexSoFar);
subtreeCount = 1;
} else {
if (type === 'object') {
("production" !== "development" ? invariant(
!children || children.nodeType !== 1,
'traverseAllChildren(...): Encountered an invalid child; DOM ' +
'elements are not valid children of React components.'
) : invariant(!children || children.nodeType !== 1));
for (var key in children) {
if (children.hasOwnProperty(key)) {
subtreeCount += traverseAllChildrenImpl(
children[key],
(
nameSoFar + (nameSoFar ? SUBSEPARATOR : SEPARATOR) +
wrapUserProvidedKey(key) + SUBSEPARATOR +
getComponentKey(children[key], 0)
),
indexSoFar + subtreeCount,
callback,
traverseContext
);
}
}
} else if (type === 'string') {
var normalizedText = ReactTextComponent(children);
callback(traverseContext, normalizedText, storageName, indexSoFar);
subtreeCount += 1;
} else if (type === 'number') {
var normalizedNumber = ReactTextComponent('' + children);
callback(traverseContext, normalizedNumber, storageName, indexSoFar);
subtreeCount += 1;
}
}
}
return subtreeCount;
};
/**
* Traverses children that are typically specified as `props.children`, but
* might also be specified through attributes:
*
* - `traverseAllChildren(this.props.children, ...)`
* - `traverseAllChildren(this.props.leftPanelChildren, ...)`
*
* The `traverseContext` is an optional argument that is passed through the
* entire traversal. It can be used to store accumulations or anything else that
* the callback might find relevant.
*
* @param {?*} children Children tree object.
* @param {!function} callback To invoke upon traversing each child.
* @param {?*} traverseContext Context for traversal.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildren(children, callback, traverseContext) {
if (children == null) {
return 0;
}
return traverseAllChildrenImpl(children, '', 0, callback, traverseContext);
}
module.exports = traverseAllChildren;
},{"./ReactInstanceHandles":64,"./ReactTextComponent":83,"./invariant":134}],157:[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 update
*/
"use strict";
var copyProperties = _dereq_("./copyProperties");
var keyOf = _dereq_("./keyOf");
var invariant = _dereq_("./invariant");
function shallowCopy(x) {
if (Array.isArray(x)) {
return x.concat();
} else if (x && typeof x === 'object') {
return copyProperties(new x.constructor(), x);
} else {
return x;
}
}
var COMMAND_PUSH = keyOf({$push: null});
var COMMAND_UNSHIFT = keyOf({$unshift: null});
var COMMAND_SPLICE = keyOf({$splice: null});
var COMMAND_SET = keyOf({$set: null});
var COMMAND_MERGE = keyOf({$merge: null});
var COMMAND_APPLY = keyOf({$apply: null});
var ALL_COMMANDS_LIST = [
COMMAND_PUSH,
COMMAND_UNSHIFT,
COMMAND_SPLICE,
COMMAND_SET,
COMMAND_MERGE,
COMMAND_APPLY
];
var ALL_COMMANDS_SET = {};
ALL_COMMANDS_LIST.forEach(function(command) {
ALL_COMMANDS_SET[command] = true;
});
function invariantArrayCase(value, spec, command) {
("production" !== "development" ? invariant(
Array.isArray(value),
'update(): expected target of %s to be an array; got %s.',
command,
value
) : invariant(Array.isArray(value)));
var specValue = spec[command];
("production" !== "development" ? invariant(
Array.isArray(specValue),
'update(): expected spec of %s to be an array; got %s. ' +
'Did you forget to wrap your parameter in an array?',
command,
specValue
) : invariant(Array.isArray(specValue)));
}
function update(value, spec) {
("production" !== "development" ? invariant(
typeof spec === 'object',
'update(): You provided a key path to update() that did not contain one ' +
'of %s. Did you forget to include {%s: ...}?',
ALL_COMMANDS_LIST.join(', '),
COMMAND_SET
) : invariant(typeof spec === 'object'));
if (spec.hasOwnProperty(COMMAND_SET)) {
("production" !== "development" ? invariant(
Object.keys(spec).length === 1,
'Cannot have more than one key in an object with %s',
COMMAND_SET
) : invariant(Object.keys(spec).length === 1));
return spec[COMMAND_SET];
}
var nextValue = shallowCopy(value);
if (spec.hasOwnProperty(COMMAND_MERGE)) {
var mergeObj = spec[COMMAND_MERGE];
("production" !== "development" ? invariant(
mergeObj && typeof mergeObj === 'object',
'update(): %s expects a spec of type \'object\'; got %s',
COMMAND_MERGE,
mergeObj
) : invariant(mergeObj && typeof mergeObj === 'object'));
("production" !== "development" ? invariant(
nextValue && typeof nextValue === 'object',
'update(): %s expects a target of type \'object\'; got %s',
COMMAND_MERGE,
nextValue
) : invariant(nextValue && typeof nextValue === 'object'));
copyProperties(nextValue, spec[COMMAND_MERGE]);
}
if (spec.hasOwnProperty(COMMAND_PUSH)) {
invariantArrayCase(value, spec, COMMAND_PUSH);
spec[COMMAND_PUSH].forEach(function(item) {
nextValue.push(item);
});
}
if (spec.hasOwnProperty(COMMAND_UNSHIFT)) {
invariantArrayCase(value, spec, COMMAND_UNSHIFT);
spec[COMMAND_UNSHIFT].forEach(function(item) {
nextValue.unshift(item);
});
}
if (spec.hasOwnProperty(COMMAND_SPLICE)) {
("production" !== "development" ? invariant(
Array.isArray(value),
'Expected %s target to be an array; got %s',
COMMAND_SPLICE,
value
) : invariant(Array.isArray(value)));
("production" !== "development" ? invariant(
Array.isArray(spec[COMMAND_SPLICE]),
'update(): expected spec of %s to be an array of arrays; got %s. ' +
'Did you forget to wrap your parameters in an array?',
COMMAND_SPLICE,
spec[COMMAND_SPLICE]
) : invariant(Array.isArray(spec[COMMAND_SPLICE])));
spec[COMMAND_SPLICE].forEach(function(args) {
("production" !== "development" ? invariant(
Array.isArray(args),
'update(): expected spec of %s to be an array of arrays; got %s. ' +
'Did you forget to wrap your parameters in an array?',
COMMAND_SPLICE,
spec[COMMAND_SPLICE]
) : invariant(Array.isArray(args)));
nextValue.splice.apply(nextValue, args);
});
}
if (spec.hasOwnProperty(COMMAND_APPLY)) {
("production" !== "development" ? invariant(
typeof spec[COMMAND_APPLY] === 'function',
'update(): expected spec of %s to be a function; got %s.',
COMMAND_APPLY,
spec[COMMAND_APPLY]
) : invariant(typeof spec[COMMAND_APPLY] === 'function'));
nextValue = spec[COMMAND_APPLY](nextValue);
}
for (var k in spec) {
if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) {
nextValue[k] = update(value[k], spec[k]);
}
}
return nextValue;
}
module.exports = update;
},{"./copyProperties":110,"./invariant":134,"./keyOf":141}],158:[function(_dereq_,module,exports){
/**
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule warning
*/
"use strict";
var emptyFunction = _dereq_("./emptyFunction");
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if ("production" !== "development") {
warning = function(condition, format ) {var args=Array.prototype.slice.call(arguments,2);
if (format === undefined) {
throw new Error(
'`warning(condition, format, ...args)` requires a warning ' +
'message argument'
);
}
if (!condition) {
var argIndex = 0;
console.warn('Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];}));
}
};
}
module.exports = warning;
},{"./emptyFunction":116}]},{},[88])
(88)
}); |
src/components/todo/TodoForm.js | RafaelDelboni/todo-react-redux | import React from 'react';
const TodoForm = ({todo, error, onKeyPress, onChange, onSave}) => {
return (
<div className="input-field">
<input className="add-todo"
type="text"
name="description"
label="Todo"
placeholder="Add new todo..."
value={todo.description}
onKeyPress={onKeyPress}
onChange={onChange} />
<input type="submit"
value="Add"
className="add-button btn add"
onClick={onSave} />
{error && <div>{error}</div>}
</div>
);
};
TodoForm.propTypes = {
todo: React.PropTypes.object.isRequired,
error: React.PropTypes.string,
onKeyPress: React.PropTypes.func.isRequired,
onChange: React.PropTypes.func.isRequired,
onSave: React.PropTypes.func.isRequired
};
export default TodoForm; |
src/components/Feedback/Feedback.js | como-quesito/react-starter-kit | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react';
import styles from './Feedback.css';
import withStyles from '../../decorators/withStyles';
@withStyles(styles)
class Feedback extends Component {
render() {
return (
<div className="Feedback">
<div className="Feedback-container">
<a className="Feedback-link" href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a>
<span className="Feedback-spacer">|</span>
<a className="Feedback-link" href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a>
</div>
</div>
);
}
}
export default Feedback;
|
node_modules/enzyme/src/ShallowWrapper.js | PanJ/SimplerCityGlide | import React from 'react';
import ComplexSelector from './ComplexSelector';
import flatten from 'lodash/flatten';
import unique from 'lodash/uniq';
import compact from 'lodash/compact';
import cheerio from 'cheerio';
import {
nodeEqual,
containsChildrenSubArray,
propFromEvent,
withSetStateAllowed,
propsOfNode,
typeOfNode,
isReactElementAlike,
displayNameOfNode,
isFunctionalComponent,
} from './Utils';
import {
debugNodes,
} from './Debug';
import {
getTextFromNode,
hasClassName,
childrenOfNode,
parentsOfNode,
treeFilter,
buildPredicate,
} from './ShallowTraversal';
import {
createShallowRenderer,
renderToStaticMarkup,
} from './react-compat';
/**
* Finds all nodes in the current wrapper nodes' render trees that match the provided predicate
* function.
*
* @param {ShallowWrapper} wrapper
* @param {Function} predicate
* @param {Function} filter
* @returns {ShallowWrapper}
*/
function findWhereUnwrapped(wrapper, predicate, filter = treeFilter) {
return wrapper.flatMap(n => filter(n.node, predicate));
}
/**
* Returns a new wrapper instance with only the nodes of the current wrapper instance that match
* the provided predicate function.
*
* @param {ShallowWrapper} wrapper
* @param {Function} predicate
* @returns {ShallowWrapper}
*/
function filterWhereUnwrapped(wrapper, predicate) {
return wrapper.wrap(compact(wrapper.nodes.filter(predicate)));
}
/**
* @class ShallowWrapper
*/
export default class ShallowWrapper {
constructor(nodes, root, options = {}) {
if (!root) {
this.root = this;
this.unrendered = nodes;
this.renderer = createShallowRenderer();
this.renderer.render(nodes, options.context);
this.node = this.renderer.getRenderOutput();
this.nodes = [this.node];
this.length = 1;
} else {
this.root = root;
this.unrendered = null;
this.renderer = null;
if (!Array.isArray(nodes)) {
this.node = nodes;
this.nodes = [nodes];
} else {
this.node = nodes[0];
this.nodes = nodes;
}
this.length = this.nodes.length;
}
this.options = options;
this.complexSelector = new ComplexSelector(buildPredicate, findWhereUnwrapped, childrenOfNode);
}
/**
* Gets the instance of the component being rendered as the root node passed into `shallow()`.
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
*
* Example:
* ```
* const wrapper = shallow(<MyComponent />);
* const inst = wrapper.instance();
* expect(inst).to.be.instanceOf(MyComponent);
* ```
* @returns {ReactComponent}
*/
instance() {
if (this.root !== this) {
throw new Error('ShallowWrapper::instance() can only be called on the root');
}
return this.renderer._instance._instance;
}
/**
* Forces a re-render. Useful to run before checking the render output if something external
* may be updating the state of the component somewhere.
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
*
* @returns {ShallowWrapper}
*/
update() {
if (this.root !== this) {
throw new Error('ShallowWrapper::update() can only be called on the root');
}
this.single(() => {
this.node = this.renderer.getRenderOutput();
this.nodes = [this.node];
});
return this;
}
/**
* A method that sets the props of the root component, and re-renders. Useful for when you are
* wanting to test how the component behaves over time with changing props. Calling this, for
* instance, will call the `componentWillReceiveProps` lifecycle method.
*
* Similar to `setState`, this method accepts a props object and will merge it in with the already
* existing props.
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
*
* @param {Object} props object
* @returns {ShallowWrapper}
*/
setProps(props) {
if (this.root !== this) {
throw new Error('ShallowWrapper::setProps() can only be called on the root');
}
this.single(() => {
withSetStateAllowed(() => {
this.unrendered = React.cloneElement(this.unrendered, props);
this.renderer.render(this.unrendered, this.options.context);
this.update();
});
});
return this;
}
/**
* A method to invoke `setState` on the root component instance similar to how you might in the
* definition of the component, and re-renders. This method is useful for testing your component
* in hard to achieve states, however should be used sparingly. If possible, you should utilize
* your component's external API in order to get it into whatever state you want to test, in order
* to be as accurate of a test as possible. This is not always practical, however.
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
*
* @param {Object} state to merge
* @returns {ShallowWrapper}
*/
setState(state) {
if (this.root !== this) {
throw new Error('ShallowWrapper::setState() can only be called on the root');
}
if (isFunctionalComponent(this.instance())) {
throw new Error('ShallowWrapper::setState() can only be called on class components');
}
this.single(() => {
withSetStateAllowed(() => {
this.instance().setState(state);
this.update();
});
});
return this;
}
/**
* A method that sets the context of the root component, and re-renders. Useful for when you are
* wanting to test how the component behaves over time with changing contexts.
*
* NOTE: can only be called on a wrapper instance that is also the root instance.
*
* @param {Object} context object
* @returns {ShallowWrapper}
*/
setContext(context) {
if (this.root !== this) {
throw new Error('ShallowWrapper::setContext() can only be called on the root');
}
if (!this.options.context) {
throw new Error(
'ShallowWrapper::setContext() can only be called on a wrapper that was originally passed ' +
'a context option'
);
}
this.renderer.render(this.unrendered, context);
this.update();
return this;
}
/**
* Whether or not a given react element exists in the shallow render tree.
*
* Example:
* ```
* const wrapper = shallow(<MyComponent />);
* expect(wrapper.contains(<div className="foo bar" />)).to.equal(true);
* ```
*
* @param {ReactElement|Array<ReactElement>} nodeOrNodes
* @returns {Boolean}
*/
contains(nodeOrNodes) {
if (!isReactElementAlike(nodeOrNodes)) {
throw new Error(
'ShallowWrapper::contains() can only be called with ReactElement (or array of them), ' +
'string or number as argument.'
);
}
const predicate = Array.isArray(nodeOrNodes)
? other => containsChildrenSubArray(nodeEqual, other, nodeOrNodes)
: other => nodeEqual(nodeOrNodes, other);
return findWhereUnwrapped(this, predicate).length > 0;
}
/**
* Whether or not a given react element exists in the shallow render tree.
* Match is based on the expected element and not on wrappers element.
* It will determine if one of the wrappers element "looks like" the expected
* element by checking if all props of the expected element are present
* on the wrappers element and equals to each other.
*
* Example:
* ```
* // MyComponent outputs <div><div class="foo">Hello</div></div>
* const wrapper = shallow(<MyComponent />);
* expect(wrapper.containsMatchingElement(<div>Hello</div>)).to.equal(true);
* ```
*
* @param {ReactElement} node
* @returns {Boolean}
*/
containsMatchingElement(node) {
const predicate = other => nodeEqual(node, other, (a, b) => a <= b);
return findWhereUnwrapped(this, predicate).length > 0;
}
/**
* Whether or not all the given react elements exists in the shallow render tree.
* Match is based on the expected element and not on wrappers element.
* It will determine if one of the wrappers element "looks like" the expected
* element by checking if all props of the expected element are present
* on the wrappers element and equals to each other.
*
* Example:
* ```
* const wrapper = shallow(<MyComponent />);
* expect(wrapper.containsAllMatchingElements([
* <div>Hello</div>,
* <div>Goodbye</div>,
* ])).to.equal(true);
* ```
*
* @param {Array<ReactElement>} nodes
* @returns {Boolean}
*/
containsAllMatchingElements(nodes) {
const invertedEquals = (n1, n2) => nodeEqual(n2, n1, (a, b) => a <= b);
const predicate = other => containsChildrenSubArray(invertedEquals, other, nodes);
return findWhereUnwrapped(this, predicate).length > 0;
}
/**
* Whether or not one of the given react elements exists in the shallow render tree.
* Match is based on the expected element and not on wrappers element.
* It will determine if one of the wrappers element "looks like" the expected
* element by checking if all props of the expected element are present
* on the wrappers element and equals to each other.
*
* Example:
* ```
* const wrapper = shallow(<MyComponent />);
* expect(wrapper.containsAnyMatchingElements([
* <div>Hello</div>,
* <div>Goodbye</div>,
* ])).to.equal(true);
* ```
*
* @param {Array<ReactElement>} nodes
* @returns {Boolean}
*/
containsAnyMatchingElements(nodes) {
if (!Array.isArray(nodes)) return false;
if (nodes.length <= 0) return false;
for (let i = 0; i < nodes.length; i++) {
if (this.containsMatchingElement(nodes[i])) {
return true;
}
}
return false;
}
/**
* Whether or not a given react element exists in the shallow render tree.
*
* Example:
* ```
* const wrapper = shallow(<MyComponent />);
* expect(wrapper.contains(<div className="foo bar" />)).to.equal(true);
* ```
*
* @param {ReactElement} node
* @returns {Boolean}
*/
equals(node) {
return this.single(() => nodeEqual(this.node, node));
}
/**
* Whether or not a given react element matches the shallow render tree.
* Match is based on the expected element and not on wrapper root node.
* It will determine if the wrapper root node "looks like" the expected
* element by checking if all props of the expected element are present
* on the wrapper root node and equals to each other.
*
* Example:
* ```
* // MyComponent outputs <div class="foo">Hello</div>
* const wrapper = shallow(<MyComponent />);
* expect(wrapper.matchesElement(<div>Hello</div>)).to.equal(true);
* ```
*
* @param {ReactElement} node
* @returns {Boolean}
*/
matchesElement(node) {
return this.single(() => nodeEqual(node, this.node, (a, b) => a <= b));
}
/**
* Finds every node in the render tree of the current wrapper that matches the provided selector.
*
* @param {String|Function} selector
* @returns {ShallowWrapper}
*/
find(selector) {
return this.complexSelector.find(selector, this);
}
/**
* Returns whether or not current node matches a provided selector.
*
* NOTE: can only be called on a wrapper of a single node.
*
* @param {String|Function} selector
* @returns {boolean}
*/
is(selector) {
const predicate = buildPredicate(selector);
return this.single(predicate);
}
/**
* Returns a new wrapper instance with only the nodes of the current wrapper instance that match
* the provided predicate function. The predicate should receive a wrapped node as its first
* argument.
*
* @param {Function} predicate
* @returns {ShallowWrapper}
*/
filterWhere(predicate) {
return filterWhereUnwrapped(this, n => predicate(this.wrap(n)));
}
/**
* Returns a new wrapper instance with only the nodes of the current wrapper instance that match
* the provided selector.
*
* @param {String|Function} selector
* @returns {ShallowWrapper}
*/
filter(selector) {
const predicate = buildPredicate(selector);
return filterWhereUnwrapped(this, predicate);
}
/**
* Returns a new wrapper instance with only the nodes of the current wrapper that did not match
* the provided selector. Essentially the inverse of `filter`.
*
* @param {String|Function} selector
* @returns {ShallowWrapper}
*/
not(selector) {
const predicate = buildPredicate(selector);
return filterWhereUnwrapped(this, n => !predicate(n));
}
/**
* Returns a string of the rendered text of the current render tree. This function should be
* looked at with skepticism if being used to test what the actual HTML output of the component
* will be. If that is what you would like to test, use enzyme's `render` function instead.
*
* NOTE: can only be called on a wrapper of a single node.
*
* @returns {String}
*/
text() {
return this.single(getTextFromNode);
}
/**
* Returns the HTML of the node.
*
* NOTE: can only be called on a wrapper of a single node.
*
* @returns {String}
*/
html() {
return this.single(n => {
// NOTE: splitting this into two statements is required to make the linter happy.
const isNull = this.type() === null;
return isNull ? null : renderToStaticMarkup(n);
});
}
/**
* Returns the current node rendered to HTML and wrapped in a CheerioWrapper.
*
* NOTE: can only be called on a wrapper of a single node.
*
* @returns {CheerioWrapper}
*/
render() {
return this.type() === null ? cheerio() : cheerio.load(this.html()).root();
}
/**
* A method that unmounts the component. This can be used to simulate a component going through
* and unmount/mount lifecycle.
* @returns {ShallowWrapper}
*/
unmount() {
this.renderer.unmount();
return this;
}
/**
* Used to simulate events. Pass an eventname and (optionally) event arguments. This method of
* testing events should be met with some skepticism.
*
* @param {String} event
* @param {Array} args
* @returns {ShallowWrapper}
*/
simulate(event, ...args) {
const handler = this.prop(propFromEvent(event));
if (handler) {
withSetStateAllowed(() => {
// TODO(lmr): create/use synthetic events
// TODO(lmr): emulate React's event propagation
handler(...args);
this.root.update();
});
}
return this;
}
/**
* Returns the props hash for the root node of the wrapper.
*
* NOTE: can only be called on a wrapper of a single node.
*
* @returns {Object}
*/
props() {
return this.single(propsOfNode);
}
/**
* Returns the state hash for the root node of the wrapper. Optionally pass in a prop name and it
* will return just that value.
*
* NOTE: can only be called on a wrapper of a single node.
*
* @param {String} name (optional)
* @returns {*}
*/
state(name) {
if (this.root !== this) {
throw new Error('ShallowWrapper::state() can only be called on the root');
}
if (isFunctionalComponent(this.instance())) {
throw new Error('ShallowWrapper::state() can only be called on class components');
}
const _state = this.single(() => this.instance().state);
if (name !== undefined) {
return _state[name];
}
return _state;
}
/**
* Returns the context hash for the root node of the wrapper.
* Optionally pass in a prop name and it will return just that value.
*
* NOTE: can only be called on a wrapper of a single node.
*
* @param {String} name (optional)
* @returns {*}
*/
context(name) {
if (this.root !== this) {
throw new Error('ShallowWrapper::context() can only be called on the root');
}
if (!this.options.context) {
throw new Error(
'ShallowWrapper::context() can only be called on a wrapper that was originally passed ' +
'a context option'
);
}
const _context = this.single(() => this.instance().context);
if (name) {
return _context[name];
}
return _context;
}
/**
* Returns a new wrapper with all of the children of the current wrapper.
*
* @param {String|Function} [selector]
* @returns {ShallowWrapper}
*/
children(selector) {
const allChildren = this.flatMap(n => childrenOfNode(n.node));
return selector ? allChildren.filter(selector) : allChildren;
}
/**
* Returns a new wrapper with a specific child
*
* @param {Number} [index]
* @returns {ShallowWrapper}
*/
childAt(index) {
return this.single(() => this.children().at(index));
}
/**
* Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node
* in the current wrapper.
*
* NOTE: can only be called on a wrapper of a single node.
*
* @param {String|Function} [selector]
* @returns {ShallowWrapper}
*/
parents(selector) {
const allParents = this.wrap(this.single(n => parentsOfNode(n, this.root.node)));
return selector ? allParents.filter(selector) : allParents;
}
/**
* Returns a wrapper around the immediate parent of the current node.
*
* @returns {ShallowWrapper}
*/
parent() {
return this.flatMap(n => [n.parents().get(0)]);
}
/**
*
* @param {String|Function} selector
* @returns {ShallowWrapper}
*/
closest(selector) {
return this.is(selector) ? this : this.parents().filter(selector).first();
}
/**
* Shallow renders the current node and returns a shallow wrapper around it.
*
* NOTE: can only be called on wrapper of a single node.
*
* @param options object
* @returns {ShallowWrapper}
*/
shallow(options) {
return this.single((n) => new ShallowWrapper(n, null, options));
}
/**
* Returns the value of prop with the given name of the root node.
*
* @param propName
* @returns {*}
*/
prop(propName) {
return this.props()[propName];
}
/**
* Returns the key assigned to the current node.
*
* @returns {String}
*/
key() {
return this.single((n) => n.key);
}
/**
* Returns the type of the root node of this wrapper. If it's a composite component, this will be
* the component constructor. If it's native DOM node, it will be a string.
*
* @returns {String|Function}
*/
type() {
return this.single(typeOfNode);
}
/**
* Returns the name of the root node of this wrapper.
*
* In order of precedence => type.displayName -> type.name -> type.
*
* @returns {String}
*/
name() {
return this.single(displayNameOfNode);
}
/**
* Returns whether or not the current root node has the given class name or not.
*
* NOTE: can only be called on a wrapper of a single node.
*
* @param className
* @returns {Boolean}
*/
hasClass(className) {
if (className && className.indexOf('.') !== -1) {
console.warn(
'It looks like you\'re calling `ShallowWrapper::hasClass()` with a CSS selector. ' +
'hasClass() expects a class name, not a CSS selector.'
);
}
return this.single(n => hasClassName(n, className));
}
/**
* Iterates through each node of the current wrapper and executes the provided function with a
* wrapper around the corresponding node passed in as the first argument.
*
* @param {Function} fn
* @returns {ShallowWrapper}
*/
forEach(fn) {
this.nodes.forEach((n, i) => fn.call(this, this.wrap(n), i));
return this;
}
/**
* Maps the current array of nodes to another array. Each node is passed in as a `ShallowWrapper`
* to the map function.
*
* @param {Function} fn
* @returns {Array}
*/
map(fn) {
return this.nodes.map((n, i) => fn.call(this, this.wrap(n), i));
}
/**
* Reduces the current array of nodes to a value. Each node is passed in as a `ShallowWrapper`
* to the reducer function.
*
* @param {Function} fn - the reducer function
* @param {*} initialValue - the initial value
* @returns {*}
*/
reduce(fn, initialValue) {
return this.nodes.reduce(
(accum, n, i) => fn.call(this, accum, this.wrap(n), i),
initialValue
);
}
/**
* Reduces the current array of nodes to another array, from right to left. Each node is passed
* in as a `ShallowWrapper` to the reducer function.
*
* @param {Function} fn - the reducer function
* @param {*} initialValue - the initial value
* @returns {*}
*/
reduceRight(fn, initialValue) {
return this.nodes.reduceRight(
(accum, n, i) => fn.call(this, accum, this.wrap(n), i),
initialValue
);
}
/**
* Returns whether or not any of the nodes in the wrapper match the provided selector.
*
* @param {Function|String} selector
* @returns {Boolean}
*/
some(selector) {
const predicate = buildPredicate(selector);
return this.nodes.some(predicate);
}
/**
* Returns whether or not any of the nodes in the wrapper pass the provided predicate function.
*
* @param {Function} predicate
* @returns {Boolean}
*/
someWhere(predicate) {
return this.nodes.some((n, i) => predicate.call(this, this.wrap(n), i));
}
/**
* Returns whether or not all of the nodes in the wrapper match the provided selector.
*
* @param {Function|String} selector
* @returns {Boolean}
*/
every(selector) {
const predicate = buildPredicate(selector);
return this.nodes.every(predicate);
}
/**
* Returns whether or not any of the nodes in the wrapper pass the provided predicate function.
*
* @param {Function} predicate
* @returns {Boolean}
*/
everyWhere(predicate) {
return this.nodes.every((n, i) => predicate.call(this, this.wrap(n), i));
}
/**
* Utility method used to create new wrappers with a mapping function that returns an array of
* nodes in response to a single node wrapper. The returned wrapper is a single wrapper around
* all of the mapped nodes flattened (and de-duplicated).
*
* @param {Function} fn
* @returns {ShallowWrapper}
*/
flatMap(fn) {
const nodes = this.nodes.map((n, i) => fn.call(this, this.wrap(n), i));
const flattened = flatten(nodes, true);
const uniques = unique(flattened);
const compacted = compact(uniques);
return this.wrap(compacted);
}
/**
* Finds all nodes in the current wrapper nodes' render trees that match the provided predicate
* function. The predicate function will receive the nodes inside a ShallowWrapper as its
* first argument.
*
* @param {Function} predicate
* @returns {ShallowWrapper}
*/
findWhere(predicate) {
return findWhereUnwrapped(this, n => predicate(this.wrap(n)));
}
/**
* Returns the node at a given index of the current wrapper.
*
* @param index
* @returns {ReactElement}
*/
get(index) {
return this.nodes[index];
}
/**
* Returns a wrapper around the node at a given index of the current wrapper.
*
* @param index
* @returns {ShallowWrapper}
*/
at(index) {
return this.wrap(this.nodes[index]);
}
/**
* Returns a wrapper around the first node of the current wrapper.
*
* @returns {ShallowWrapper}
*/
first() {
return this.at(0);
}
/**
* Returns a wrapper around the last node of the current wrapper.
*
* @returns {ShallowWrapper}
*/
last() {
return this.at(this.length - 1);
}
/**
* Returns true if the current wrapper has no nodes. False otherwise.
*
* @returns {boolean}
*/
isEmpty() {
return this.length === 0;
}
/**
* Utility method that throws an error if the current instance has a length other than one.
* This is primarily used to enforce that certain methods are only run on a wrapper when it is
* wrapping a single node.
*
* @param fn
* @returns {*}
*/
single(fn) {
if (this.length !== 1) {
throw new Error(
`This method is only meant to be run on single node. ${this.length} found instead.`
);
}
return fn.call(this, this.node);
}
/**
* Helpful utility method to create a new wrapper with the same root as the current wrapper, with
* any nodes passed in as the first parameter automatically wrapped.
*
* @param node
* @returns {ShallowWrapper}
*/
wrap(node) {
if (node instanceof ShallowWrapper) {
return node;
}
return new ShallowWrapper(node, this.root);
}
/**
* Returns an HTML-like string of the shallow render for debugging purposes.
*
* @returns {String}
*/
debug() {
return debugNodes(this.nodes);
}
/**
* Invokes intercepter and returns itself. intercepter is called with itself.
* This is helpful when debugging nodes in method chains.
* @param fn
* @returns {ShallowWrapper}
*/
tap(intercepter) {
intercepter(this);
return this;
}
}
|
ajax/libs/analytics.js/2.3.21/analytics.min.js | pvnr0082t/cdnjs | (function outer(modules,cache,entries){var global=function(){return this}();function require(name,jumped){if(cache[name])return cache[name].exports;if(modules[name])return call(name,require);throw new Error('cannot find module "'+name+'"')}function call(id,require){var m=cache[id]={exports:{}};var mod=modules[id];var name=mod[2];var fn=mod[0];fn.call(m.exports,function(req){var dep=modules[id][1][req];return require(dep?dep:req)},m,m.exports,outer,modules,cache,entries);if(name)cache[name]=cache[id];return cache[id].exports}for(var id in entries){if(entries[id]){global[entries[id]]=require(id)}else{require(id)}}require.duo=true;require.cache=cache;require.modules=modules;return require})({1:[function(require,module,exports){var Integrations=require("analytics.js-integrations");var Analytics=require("./analytics");var each=require("each");var analytics=module.exports=exports=new Analytics;analytics.require=require;exports.VERSION=require("./version");each(Integrations,function(name,Integration){analytics.use(Integration)})},{"analytics.js-integrations":2,"./analytics":3,each:4,"./version":5}],2:[function(require,module,exports){var each=require("each");var plugins=require("./integrations.js");each(plugins,function(plugin){var name=(plugin.Integration||plugin).prototype.name;exports[name]=plugin})},{each:4,"./integrations.js":6}],4:[function(require,module,exports){var type=require("type");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn){switch(type(obj)){case"array":return array(obj,fn);case"object":if("number"==typeof obj.length)return array(obj,fn);return object(obj,fn);case"string":return string(obj,fn)}};function string(obj,fn){for(var i=0;i<obj.length;++i){fn(obj.charAt(i),i)}}function object(obj,fn){for(var key in obj){if(has.call(obj,key)){fn(key,obj[key])}}}function array(obj,fn){for(var i=0;i<obj.length;++i){fn(obj[i],i)}}},{type:7}],7:[function(require,module,exports){var toString=Object.prototype.toString;module.exports=function(val){switch(toString.call(val)){case"[object Function]":return"function";case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object String]":return"string"}if(val===null)return"null";if(val===undefined)return"undefined";if(val&&val.nodeType===1)return"element";if(val===Object(val))return"object";return typeof val}},{}],6:[function(require,module,exports){module.exports=[require("./lib/adroll"),require("./lib/adwords"),require("./lib/alexa"),require("./lib/amplitude"),require("./lib/appcues"),require("./lib/awesm"),require("./lib/awesomatic"),require("./lib/bing-ads"),require("./lib/bronto"),require("./lib/bugherd"),require("./lib/bugsnag"),require("./lib/chartbeat"),require("./lib/churnbee"),require("./lib/clicktale"),require("./lib/clicky"),require("./lib/comscore"),require("./lib/crazy-egg"),require("./lib/curebit"),require("./lib/customerio"),require("./lib/drip"),require("./lib/errorception"),require("./lib/evergage"),require("./lib/facebook-conversion-tracking"),require("./lib/foxmetrics"),require("./lib/frontleaf"),require("./lib/gauges"),require("./lib/get-satisfaction"),require("./lib/google-analytics"),require("./lib/google-tag-manager"),require("./lib/gosquared"),require("./lib/heap"),require("./lib/hellobar"),require("./lib/hittail"),require("./lib/hubspot"),require("./lib/improvely"),require("./lib/insidevault"),require("./lib/inspectlet"),require("./lib/intercom"),require("./lib/keen-io"),require("./lib/kenshoo"),require("./lib/kissmetrics"),require("./lib/klaviyo"),require("./lib/leadlander"),require("./lib/livechat"),require("./lib/lucky-orange"),require("./lib/lytics"),require("./lib/mixpanel"),require("./lib/mojn"),require("./lib/mouseflow"),require("./lib/mousestats"),require("./lib/navilytics"),require("./lib/olark"),require("./lib/optimizely"),require("./lib/perfect-audience"),require("./lib/pingdom"),require("./lib/piwik"),require("./lib/preact"),require("./lib/qualaroo"),require("./lib/quantcast"),require("./lib/rollbar"),require("./lib/saasquatch"),require("./lib/sentry"),require("./lib/snapengage"),require("./lib/spinnakr"),require("./lib/tapstream"),require("./lib/trakio"),require("./lib/twitter-ads"),require("./lib/uservoice"),require("./lib/vero"),require("./lib/visual-website-optimizer"),require("./lib/webengage"),require("./lib/woopra"),require("./lib/yandex-metrica")]},{"./lib/adroll":8,"./lib/adwords":9,"./lib/alexa":10,"./lib/amplitude":11,"./lib/appcues":12,"./lib/awesm":13,"./lib/awesomatic":14,"./lib/bing-ads":15,"./lib/bronto":16,"./lib/bugherd":17,"./lib/bugsnag":18,"./lib/chartbeat":19,"./lib/churnbee":20,"./lib/clicktale":21,"./lib/clicky":22,"./lib/comscore":23,"./lib/crazy-egg":24,"./lib/curebit":25,"./lib/customerio":26,"./lib/drip":27,"./lib/errorception":28,"./lib/evergage":29,"./lib/facebook-conversion-tracking":30,"./lib/foxmetrics":31,"./lib/frontleaf":32,"./lib/gauges":33,"./lib/get-satisfaction":34,"./lib/google-analytics":35,"./lib/google-tag-manager":36,"./lib/gosquared":37,"./lib/heap":38,"./lib/hellobar":39,"./lib/hittail":40,"./lib/hubspot":41,"./lib/improvely":42,"./lib/insidevault":43,"./lib/inspectlet":44,"./lib/intercom":45,"./lib/keen-io":46,"./lib/kenshoo":47,"./lib/kissmetrics":48,"./lib/klaviyo":49,"./lib/leadlander":50,"./lib/livechat":51,"./lib/lucky-orange":52,"./lib/lytics":53,"./lib/mixpanel":54,"./lib/mojn":55,"./lib/mouseflow":56,"./lib/mousestats":57,"./lib/navilytics":58,"./lib/olark":59,"./lib/optimizely":60,"./lib/perfect-audience":61,"./lib/pingdom":62,"./lib/piwik":63,"./lib/preact":64,"./lib/qualaroo":65,"./lib/quantcast":66,"./lib/rollbar":67,"./lib/saasquatch":68,"./lib/sentry":69,"./lib/snapengage":70,"./lib/spinnakr":71,"./lib/tapstream":72,"./lib/trakio":73,"./lib/twitter-ads":74,"./lib/uservoice":75,"./lib/vero":76,"./lib/visual-website-optimizer":77,"./lib/webengage":78,"./lib/woopra":79,"./lib/yandex-metrica":80}],8:[function(require,module,exports){var integration=require("analytics.js-integration");var snake=require("to-snake-case");var useHttps=require("use-https");var each=require("each");var is=require("is");var has=Object.prototype.hasOwnProperty;var AdRoll=module.exports=integration("AdRoll").assumesPageview().global("__adroll_loaded").global("adroll_adv_id").global("adroll_pix_id").global("adroll_custom_data").option("advId","").option("pixId","").tag("http",'<script src="http://a.adroll.com/j/roundtrip.js">').tag("https",'<script src="https://s.adroll.com/j/roundtrip.js">').mapping("events");AdRoll.prototype.initialize=function(page){window.adroll_adv_id=this.options.advId;window.adroll_pix_id=this.options.pixId;window.__adroll_loaded=true;var name=useHttps()?"https":"http";this.load(name,this.ready)};AdRoll.prototype.loaded=function(){return window.__adroll};AdRoll.prototype.page=function(page){var name=page.fullName();this.track(page.track(name))};AdRoll.prototype.track=function(track){var event=track.event();var user=this.analytics.user();var events=this.events(event);var total=track.revenue()||track.total()||0;var orderId=track.orderId()||0;each(events,function(event){var data={};if(user.id())data.user_id=user.id();data.adroll_conversion_value_in_dollars=total;data.order_id=orderId;data.adroll_segments=snake(event);window.__adroll.record_user(data)});if(!events.length){var data={};if(user.id())data.user_id=user.id();data.adroll_segments=snake(event);window.__adroll.record_user(data)}}},{"analytics.js-integration":81,"to-snake-case":82,"use-https":83,each:4,is:84}],81:[function(require,module,exports){var bind=require("bind");var callback=require("callback");var clone=require("clone");var debug=require("debug");var defaults=require("defaults");var protos=require("./protos");var slug=require("slug");var statics=require("./statics");module.exports=createIntegration;function createIntegration(name){function Integration(options){if(options&&options.addIntegration){return options.addIntegration(Integration)}this.debug=debug("analytics:integration:"+slug(name));this.options=defaults(clone(options)||{},this.defaults);this._queue=[];this.once("ready",bind(this,this.flush));Integration.emit("construct",this);this.ready=bind(this,this.ready);this._wrapInitialize();this._wrapPage();this._wrapTrack()}Integration.prototype.defaults={};Integration.prototype.globals=[];Integration.prototype.templates={};Integration.prototype.name=name;for(var key in statics)Integration[key]=statics[key];for(var key in protos)Integration.prototype[key]=protos[key];return Integration}},{bind:85,callback:86,clone:87,debug:88,defaults:89,"./protos":90,slug:91,"./statics":92}],85:[function(require,module,exports){var bind=require("bind"),bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;function bindMethods(obj,methods){methods=[].slice.call(arguments,1);for(var i=0,method;method=methods[i];i++){obj[method]=bind(obj,obj[method])}return obj}},{bind:93,"bind-all":94}],93:[function(require,module,exports){var slice=[].slice;module.exports=function(obj,fn){if("string"==typeof fn)fn=obj[fn];if("function"!=typeof fn)throw new Error("bind() requires a function");var args=slice.call(arguments,2);return function(){return fn.apply(obj,args.concat(slice.call(arguments)))}}},{}],94:[function(require,module,exports){try{var bind=require("bind");var type=require("type")}catch(e){var bind=require("bind-component");var type=require("type-component")}module.exports=function(obj){for(var key in obj){var val=obj[key];if(type(val)==="function")obj[key]=bind(obj,obj[key])}return obj}},{bind:93,type:7}],86:[function(require,module,exports){var next=require("next-tick");module.exports=callback;function callback(fn){if("function"===typeof fn)fn()}callback.async=function(fn,wait){if("function"!==typeof fn)return;if(!wait)return next(fn);setTimeout(fn,wait)};callback.sync=callback},{"next-tick":95}],95:[function(require,module,exports){"use strict";if(typeof setImmediate=="function"){module.exports=function(f){setImmediate(f)}}else if(typeof process!="undefined"&&typeof process.nextTick=="function"){module.exports=process.nextTick}else if(typeof window=="undefined"||window.ActiveXObject||!window.postMessage){module.exports=function(f){setTimeout(f)}}else{var q=[];window.addEventListener("message",function(){var i=0;while(i<q.length){try{q[i++]()}catch(e){q=q.slice(i);window.postMessage("tic!","*");throw e}}q.length=0},true);module.exports=function(fn){if(!q.length)window.postMessage("tic!","*");q.push(fn)}}},{}],87:[function(require,module,exports){var type;try{type=require("type")}catch(e){type=require("type-component")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{type:7}],88:[function(require,module,exports){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}},{"./lib/debug":96,"./debug":97}],96:[function(require,module,exports){var tty=require("tty");module.exports=debug;var names=[],skips=[];(process.env.DEBUG||"").split(/[\s,]+/).forEach(function(name){name=name.replace("*",".*?");if(name[0]==="-"){skips.push(new RegExp("^"+name.substr(1)+"$"))}else{names.push(new RegExp("^"+name+"$"))}});var colors=[6,2,3,4,5,1];var prev={};var prevColor=0;var isatty=tty.isatty(2);function color(){return colors[prevColor++%colors.length]}function humanize(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"}function debug(name){function disabled(){}disabled.enabled=false;var match=skips.some(function(re){return re.test(name)});if(match)return disabled;match=names.some(function(re){return re.test(name)});if(!match)return disabled;var c=color();function colored(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(prev[name]||curr);prev[name]=curr;fmt=" [9"+c+"m"+name+" "+"[3"+c+"m[90m"+fmt+"[3"+c+"m"+" +"+humanize(ms)+"[0m";console.error.apply(this,arguments)}function plain(fmt){fmt=coerce(fmt);fmt=(new Date).toUTCString()+" "+name+" "+fmt;console.error.apply(this,arguments)}colored.enabled=plain.enabled=true;return isatty||process.env.DEBUG_COLORS?colored:plain}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{}],97:[function(require,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],89:[function(require,module,exports){"use strict";var defaults=function(dest,src,recursive){for(var prop in src){if(recursive&&dest[prop]instanceof Object&&src[prop]instanceof Object){dest[prop]=defaults(dest[prop],src[prop],true)}else if(!(prop in dest)){dest[prop]=src[prop]}}return dest};module.exports=defaults},{}],90:[function(require,module,exports){var loadScript=require("segmentio/load-script");var normalize=require("to-no-case");var callback=require("callback");var Emitter=require("emitter");var events=require("./events");var tick=require("next-tick");var assert=require("assert");var after=require("after");var each=require("component/each");var type=require("type");var fmt=require("yields/fmt");var setTimeout=window.setTimeout;var setInterval=window.setInterval;var onerror=null;var onload=null;Emitter(exports);exports.initialize=function(){var ready=this.ready;tick(ready)};exports.loaded=function(){return false};exports.load=function(cb){callback.async(cb)};exports.page=function(page){};exports.track=function(track){};exports.map=function(obj,str){var a=normalize(str);var ret=[];if(!obj)return ret;if("object"==type(obj)){for(var k in obj){var item=obj[k];var b=normalize(k);if(b==a)ret.push(item)}}if("array"==type(obj)){if(!obj.length)return ret;if(!obj[0].key)return ret;for(var i=0;i<obj.length;++i){var item=obj[i];var b=normalize(item.key);if(b==a)ret.push(item.value)}}return ret};exports.invoke=function(method){if(!this[method])return;var args=[].slice.call(arguments,1);if(!this._ready)return this.queue(method,args);var ret;try{this.debug("%s with %o",method,args);ret=this[method].apply(this,args)}catch(e){this.debug("error %o calling %s with %o",e,method,args)}return ret};exports.queue=function(method,args){if("page"==method&&this._assumesPageview&&!this._initialized){return this.page.apply(this,args)}this._queue.push({method:method,args:args})};exports.flush=function(){this._ready=true;var call;while(call=this._queue.shift())this[call.method].apply(this,call.args)};exports.reset=function(){for(var i=0,key;key=this.globals[i];i++)window[key]=undefined;window.setTimeout=setTimeout;window.setInterval=setInterval;window.onerror=onerror;window.onload=onload};exports.load=function(name,locals,fn){if("function"==typeof name)fn=name,locals=null,name=null;if(name&&"object"==typeof name)fn=locals,locals=name,name=null;if("function"==typeof locals)fn=locals,locals=null;name=name||"library";locals=locals||{};locals=this.locals(locals);var template=this.templates[name];assert(template,fmt('Template "%s" not defined.',name));var attrs=render(template,locals);var el;switch(template.type){case"img":attrs.width=1;attrs.height=1;el=loadImage(attrs,fn);break;case"script":el=loadScript(attrs,fn);delete attrs.src;each(attrs,function(key,val){el.setAttribute(key,val)});break;case"iframe":el=loadIframe(attrs,fn);break}return el};exports.locals=function(locals){locals=locals||{};var cache=Math.floor((new Date).getTime()/36e5);if(!locals.hasOwnProperty("cache"))locals.cache=cache;each(this.options,function(key,val){if(!locals.hasOwnProperty(key))locals[key]=val});return locals};exports.ready=function(){this.emit("ready")};exports._wrapInitialize=function(){var initialize=this.initialize;this.initialize=function(){this.debug("initialize");this._initialized=true;var ret=initialize.apply(this,arguments);this.emit("initialize");return ret};if(this._assumesPageview)this.initialize=after(2,this.initialize)};exports._wrapPage=function(){var page=this.page;this.page=function(){if(this._assumesPageview&&!this._initialized){return this.initialize.apply(this,arguments)}return page.apply(this,arguments)}};exports._wrapTrack=function(){var t=this.track;this.track=function(track){var event=track.event();var called;var ret;for(var method in events){var regexp=events[method];if(!this[method])continue;if(!regexp.test(event))continue;ret=this[method].apply(this,arguments);called=true;break}if(!called)ret=t.apply(this,arguments);return ret}};function loadImage(attrs,fn){fn=fn||function(){};var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};img.src=attrs.src;img.width=1;img.height=1;return img}function error(fn,message,img){return function(e){e=e||window.event;var err=new Error(message);err.event=e;err.source=img;fn(err)}}function render(template,locals){var attrs={};each(template.attrs,function(key,val){attrs[key]=val.replace(/\{\{\ *(\w+)\ *\}\}/g,function(_,$1){return locals[$1]})});return attrs}},{"segmentio/load-script":98,"to-no-case":99,callback:86,emitter:100,"./events":101,"next-tick":95,assert:102,after:103,"component/each":104,type:7,"yields/fmt":105}],98:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadScript(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;if("function"==type(fn)){onload(script,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript)});return script}},{"script-onload":106,"next-tick":95,type:7}],106:[function(require,module,exports){module.exports=function(el,fn){return el.addEventListener?add(el,fn):attach(el,fn)};function add(el,fn){el.addEventListener("load",function(_,e){fn(null,e)},false);el.addEventListener("error",function(e){var err=new Error('failed to load the script "'+el.src+'"');err.event=e;fn(err)},false)}function attach(el,fn){el.attachEvent("onreadystatechange",function(e){if(!/complete|loaded/.test(el.readyState))return;fn(null,e)})}},{}],99:[function(require,module,exports){module.exports=toNoCase;var hasSpace=/\s/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))return unseparate(string).toLowerCase();return uncamelize(string).toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}},{}],100:[function(require,module,exports){var index=require("indexof");module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}fn._off=on;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var i=index(callbacks,fn._off||fn);if(~i)callbacks.splice(i,1);return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{indexof:107}],107:[function(require,module,exports){module.exports=function(arr,obj){if(arr.indexOf)return arr.indexOf(obj);for(var i=0;i<arr.length;++i){if(arr[i]===obj)return i}return-1}},{}],101:[function(require,module,exports){module.exports={removedProduct:/removed[ _]?product/i,viewedProduct:/viewed[ _]?product/i,addedProduct:/added[ _]?product/i,completedOrder:/completed[ _]?order/i}},{}],102:[function(require,module,exports){var equals=require("equals");var fmt=require("fmt");var stack=require("stack");module.exports=exports=function(expr,msg){if(expr)return;throw new Error(msg||message())};exports.equal=function(actual,expected,msg){if(actual==expected)return;throw new Error(msg||fmt("Expected %o to equal %o.",actual,expected))};exports.notEqual=function(actual,expected,msg){if(actual!=expected)return;throw new Error(msg||fmt("Expected %o not to equal %o.",actual,expected))};exports.deepEqual=function(actual,expected,msg){if(equals(actual,expected))return;throw new Error(msg||fmt("Expected %o to deeply equal %o.",actual,expected))};exports.notDeepEqual=function(actual,expected,msg){if(!equals(actual,expected))return;throw new Error(msg||fmt("Expected %o not to deeply equal %o.",actual,expected))};exports.strictEqual=function(actual,expected,msg){if(actual===expected)return;throw new Error(msg||fmt("Expected %o to strictly equal %o.",actual,expected))};exports.notStrictEqual=function(actual,expected,msg){if(actual!==expected)return;throw new Error(msg||fmt("Expected %o not to strictly equal %o.",actual,expected))};exports.throws=function(block,error,msg){var err;try{block()}catch(e){err=e}if(!err)throw new Error(msg||fmt("Expected %s to throw an error.",block.toString()));if(error&&!(err instanceof error)){throw new Error(msg||fmt("Expected %s to throw an %o.",block.toString(),error))}};exports.doesNotThrow=function(block,error,msg){var err;try{block()}catch(e){err=e}if(err)throw new Error(msg||fmt("Expected %s not to throw an error.",block.toString()));if(error&&err instanceof error){throw new Error(msg||fmt("Expected %s not to throw an %o.",block.toString(),error))}};function message(){if(!Error.captureStackTrace)return"assertion failed";var callsite=stack()[2];var fn=callsite.getFunctionName();var file=callsite.getFileName();var line=callsite.getLineNumber()-1;var col=callsite.getColumnNumber()-1;var src=get(file);line=src.split("\n")[line].slice(col);var m=line.match(/assert\((.*)\)/);return m&&m[1].trim()}function get(script){var xhr=new XMLHttpRequest;xhr.open("GET",script,false);xhr.send(null);return xhr.responseText}},{equals:108,fmt:105,stack:109}],108:[function(require,module,exports){var type=require("type");module.exports=equals;equals.compare=compare;function equals(){var i=arguments.length-1;while(i>0){if(!compare(arguments[i],arguments[--i]))return false}return true}function compare(a,b,memos){if(a===b)return true;var fnA=types[type(a)];var fnB=types[type(b)];return fnA&&fnA===fnB?fnA(a,b,memos):false}var types={};types.number=function(a){return a!==a};types["function"]=function(a,b,memos){return a.toString()===b.toString()&&types.object(a,b,memos)&&compare(a.prototype,b.prototype)};types.date=function(a,b){return+a===+b};types.regexp=function(a,b){return a.toString()===b.toString()};types.element=function(a,b){return a.outerHTML===b.outerHTML};types.textnode=function(a,b){return a.textContent===b.textContent};function memoGaurd(fn){return function(a,b,memos){if(!memos)return fn(a,b,[]);var i=memos.length,memo;while(memo=memos[--i]){if(memo[0]===a&&memo[1]===b)return true}return fn(a,b,memos)}}types["arguments"]=types.array=memoGaurd(compareArrays);function compareArrays(a,b,memos){var i=a.length;if(i!==b.length)return false;memos.push([a,b]);while(i--){if(!compare(a[i],b[i],memos))return false}return true}types.object=memoGaurd(compareObjects);function compareObjects(a,b,memos){var ka=getEnumerableProperties(a);var kb=getEnumerableProperties(b);var i=ka.length;if(i!==kb.length)return false;ka.sort();kb.sort();while(i--)if(ka[i]!==kb[i])return false;memos.push([a,b]);i=ka.length;while(i--){var key=ka[i];if(!compare(a[key],b[key],memos))return false}return true}function getEnumerableProperties(object){var result=[];for(var k in object)if(k!=="constructor"){result.push(k)}return result}},{type:110}],110:[function(require,module,exports){var toString={}.toString;var DomNode=typeof window!="undefined"?window.Node:Function;module.exports=exports=function(x){var type=typeof x;if(type!="object")return type;type=types[toString.call(x)];if(type)return type;if(x instanceof DomNode)switch(x.nodeType){case 1:return"element";case 3:return"text-node";case 9:return"document";case 11:return"document-fragment";default:return"dom-node"}};var types=exports.types={"[object Function]":"function","[object Date]":"date","[object RegExp]":"regexp","[object Arguments]":"arguments","[object Array]":"array","[object String]":"string","[object Null]":"null","[object Undefined]":"undefined","[object Number]":"number","[object Boolean]":"boolean","[object Object]":"object","[object Text]":"text-node","[object Uint8Array]":"bit-array","[object Uint16Array]":"bit-array","[object Uint32Array]":"bit-array","[object Uint8ClampedArray]":"bit-array","[object Error]":"error","[object FormData]":"form-data","[object File]":"file","[object Blob]":"blob"}},{}],105:[function(require,module,exports){module.exports=fmt;fmt.o=JSON.stringify;fmt.s=String;fmt.d=parseInt;function fmt(str){var args=[].slice.call(arguments,1);var j=0;return str.replace(/%([a-z])/gi,function(_,f){return fmt[f]?fmt[f](args[j++]):_+f})}},{}],109:[function(require,module,exports){module.exports=stack;function stack(){var orig=Error.prepareStackTrace;Error.prepareStackTrace=function(_,stack){return stack};var err=new Error;Error.captureStackTrace(err,arguments.callee);var stack=err.stack;Error.prepareStackTrace=orig;return stack}},{}],103:[function(require,module,exports){module.exports=function after(times,func){if(times<=0)return func();return function(){if(--times<1){return func.apply(this,arguments)}}}},{}],104:[function(require,module,exports){try{var type=require("type")}catch(err){var type=require("component-type")}var toFunction=require("to-function");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn,ctx){fn=toFunction(fn);ctx=ctx||this;switch(type(obj)){case"array":return array(obj,fn,ctx);case"object":if("number"==typeof obj.length)return array(obj,fn,ctx);return object(obj,fn,ctx);case"string":return string(obj,fn,ctx)}};function string(obj,fn,ctx){for(var i=0;i<obj.length;++i){fn.call(ctx,obj.charAt(i),i)}}function object(obj,fn,ctx){for(var key in obj){if(has.call(obj,key)){fn.call(ctx,key,obj[key])}}}function array(obj,fn,ctx){for(var i=0;i<obj.length;++i){fn.call(ctx,obj[i],i)}}},{type:7,"component-type":7,"to-function":111}],111:[function(require,module,exports){var expr;try{expr=require("props")}catch(e){expr=require("component-props")}module.exports=toFunction;function toFunction(obj){switch({}.toString.call(obj)){case"[object Object]":return objectToFunction(obj);case"[object Function]":return obj;case"[object String]":return stringToFunction(obj);case"[object RegExp]":return regexpToFunction(obj);default:return defaultToFunction(obj)}}function defaultToFunction(val){return function(obj){return val===obj}}function regexpToFunction(re){return function(obj){return re.test(obj)}}function stringToFunction(str){if(/^ *\W+/.test(str))return new Function("_","return _ "+str);return new Function("_","return "+get(str))}function objectToFunction(obj){var match={};for(var key in obj){match[key]=typeof obj[key]==="string"?defaultToFunction(obj[key]):toFunction(obj[key])}return function(val){if(typeof val!=="object")return false;for(var key in match){if(!(key in val))return false;if(!match[key](val[key]))return false}return true}}function get(str){var props=expr(str);if(!props.length)return"_."+str;var val,i,prop;for(i=0;i<props.length;i++){prop=props[i];val="_."+prop;val="('function' == typeof "+val+" ? "+val+"() : "+val+")";str=stripNested(prop,str,val)}return str}function stripNested(prop,str,val){return str.replace(new RegExp("(\\.)?"+prop,"g"),function($0,$1){return $1?$0:val})}},{props:112,"component-props":112}],112:[function(require,module,exports){var globals=/\b(this|Array|Date|Object|Math|JSON)\b/g;module.exports=function(str,fn){var p=unique(props(str));if(fn&&"string"==typeof fn)fn=prefixed(fn);if(fn)return map(str,p,fn);return p};function props(str){return str.replace(/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\//g,"").replace(globals,"").match(/[$a-zA-Z_]\w*/g)||[]}function map(str,props,fn){var re=/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g;return str.replace(re,function(_){if("("==_[_.length-1])return fn(_);if(!~props.indexOf(_))return _;return fn(_)})}function unique(arr){var ret=[];for(var i=0;i<arr.length;i++){if(~ret.indexOf(arr[i]))continue;ret.push(arr[i])}return ret}function prefixed(str){return function(_){return str+_}}},{}],91:[function(require,module,exports){module.exports=function(str,options){options||(options={});return str.toLowerCase().replace(options.replace||/[^a-z0-9]/g," ").replace(/^ +| +$/g,"").replace(/ +/g,options.separator||"-")}},{}],92:[function(require,module,exports){var after=require("after");var domify=require("component/domify");var each=require("component/each");var Emitter=require("emitter");Emitter(exports);exports.option=function(key,value){this.prototype.defaults[key]=value;return this};exports.mapping=function(name){this.option(name,[]);this.prototype[name]=function(str){return this.map(this.options[name],str)};return this};exports.global=function(key){this.prototype.globals.push(key);return this
};exports.assumesPageview=function(){this.prototype._assumesPageview=true;return this};exports.readyOnLoad=function(){this.prototype._readyOnLoad=true;return this};exports.readyOnInitialize=function(){this.prototype._readyOnInitialize=true;return this};exports.tag=function(name,str){if(null==str){str=name;name="library"}this.prototype.templates[name]=objectify(str);return this};function objectify(str){str=str.replace(' src="',' data-src="');var el=domify(str);var attrs={};each(el.attributes,function(attr){var name="data-src"==attr.name?"src":attr.name;attrs[name]=attr.value});return{type:el.tagName.toLowerCase(),attrs:attrs}}},{after:103,"component/domify":113,"component/each":104,emitter:100}],113:[function(require,module,exports){module.exports=parse;var div=document.createElement("div");div.innerHTML=' <link/><table></table><a href="/a">a</a><input type="checkbox"/>';var innerHTMLBug=!div.getElementsByTagName("link").length;div=undefined;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:innerHTMLBug?[1,"X<div>","</div>"]:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"];map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"];map.text=map.circle=map.ellipse=map.line=map.path=map.polygon=map.polyline=map.rect=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"];function parse(html,doc){if("string"!=typeof html)throw new TypeError("String expected");if(!doc)doc=document;var m=/<([\w:]+)/.exec(html);if(!m)return doc.createTextNode(html);html=html.replace(/^\s+|\s+$/g,"");var tag=m[1];if(tag=="body"){var el=doc.createElement("html");el.innerHTML=html;return el.removeChild(el.lastChild)}var wrap=map[tag]||map._default;var depth=wrap[0];var prefix=wrap[1];var suffix=wrap[2];var el=doc.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=doc.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}},{}],82:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}},{"to-space-case":114}],114:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}},{"to-no-case":115}],115:[function(require,module,exports){module.exports=toNoCase;var hasSpace=/\s/;var hasCamel=/[a-z][A-Z]/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))string=unseparate(string);if(hasCamel.test(string))string=uncamelize(string);return string.toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}},{}],83:[function(require,module,exports){module.exports=function(url){switch(arguments.length){case 0:return check();case 1:return transform(url)}};function transform(url){return check()?"https:"+url:"http:"+url}function check(){return location.protocol=="https:"||location.protocol=="chrome-extension:"}},{}],84:[function(require,module,exports){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":116,type:7,"component-type":7}],116:[function(require,module,exports){module.exports=isEmpty;var has=Object.prototype.hasOwnProperty;function isEmpty(val){if(null==val)return true;if("number"==typeof val)return 0===val;if(undefined!==val.length)return 0===val.length;for(var key in val)if(has.call(val,key))return false;return true}},{}],9:[function(require,module,exports){var integration=require("analytics.js-integration");var domify=require("domify");var each=require("each");var has=Object.prototype.hasOwnProperty;var AdWords=module.exports=integration("AdWords").option("conversionId","").option("remarketing",false).tag('<script src="//www.googleadservices.com/pagead/conversion_async.js">').mapping("events");AdWords.prototype.initialize=function(){this.load(this.ready)};AdWords.prototype.loaded=function(){return!!document.body};AdWords.prototype.page=function(page){var remarketing=!!this.options.remarketing;var id=this.options.conversionId;var props={};window.google_trackConversion({google_conversion_id:id,google_custom_params:props,google_remarketing_only:remarketing})};AdWords.prototype.track=function(track){var id=this.options.conversionId;var events=this.events(track.event());var revenue=track.revenue()||0;each(events,function(label){var props=track.properties();window.google_trackConversion({google_conversion_id:id,google_conversion_language:"en",google_conversion_format:"3",google_conversion_color:"ffffff",google_conversion_label:label,google_conversion_value:revenue,google_remarketing_only:false})})}},{"analytics.js-integration":81,domify:117,each:4}],117:[function(require,module,exports){module.exports=parse;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"];map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"];map.text=map.circle=map.ellipse=map.line=map.path=map.polygon=map.polyline=map.rect=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"];function parse(html){if("string"!=typeof html)throw new TypeError("String expected");html=html.replace(/^\s+|\s+$/g,"");var m=/<([\w:]+)/.exec(html);if(!m)return document.createTextNode(html);var tag=m[1];if(tag=="body"){var el=document.createElement("html");el.innerHTML=html;return el.removeChild(el.lastChild)}var wrap=map[tag]||map._default;var depth=wrap[0];var prefix=wrap[1];var suffix=wrap[2];var el=document.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=document.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}},{}],10:[function(require,module,exports){var integration=require("analytics.js-integration");var Alexa=module.exports=integration("Alexa").assumesPageview().global("_atrk_opts").option("account",null).option("domain","").option("dynamic",true).tag('<script src="//d31qbv1cthcecs.cloudfront.net/atrk.js">');Alexa.prototype.initialize=function(page){var self=this;window._atrk_opts={atrk_acct:this.options.account,domain:this.options.domain,dynamic:this.options.dynamic};this.load(function(){window.atrk();self.ready()})};Alexa.prototype.loaded=function(){return!!window.atrk}},{"analytics.js-integration":81}],11:[function(require,module,exports){var integration=require("analytics.js-integration");var Amplitude=module.exports=integration("Amplitude").global("amplitude").option("apiKey","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.1-min.js">');Amplitude.prototype.initialize=function(page){(function(e,t){var r=e.amplitude||{};r._q=[];function i(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}var s=["init","logEvent","setUserId","setGlobalUserProperties","setVersionName","setDomain"];for(var c=0;c<s.length;c++){i(s[c])}e.amplitude=r})(window,document);window.amplitude.init(this.options.apiKey);this.load(this.ready)};Amplitude.prototype.loaded=function(){return!!(window.amplitude&&window.amplitude.options)};Amplitude.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Amplitude.prototype.identify=function(identify){var id=identify.userId();var traits=identify.traits();if(id)window.amplitude.setUserId(id);if(traits)window.amplitude.setGlobalUserProperties(traits)};Amplitude.prototype.track=function(track){var props=track.properties();var event=track.event();window.amplitude.logEvent(event,props)}},{"analytics.js-integration":81}],12:[function(require,module,exports){var integration=require("analytics.js-integration");var load=require("load-script");var is=require("is");module.exports=exports=function(analytics){analytics.addIntegration(Appcues)};var Appcues=exports.Integration=integration("Appcues").assumesPageview().global("Appcues").global("AppcuesIdentity").option("appcuesId","").option("userId","").option("userEmail","");Appcues.prototype.initialize=function(){this.load(function(){window.Appcues.init()})};Appcues.prototype.loaded=function(){return is.object(window.Appcues)};Appcues.prototype.load=function(callback){var script=load("//d2dubfq97s02eu.cloudfront.net/appcues-bundle.min.js",callback);script.setAttribute("data-appcues-id",this.options.appcuesId);script.setAttribute("data-user-id",this.options.userId);script.setAttribute("data-user-email",this.options.userEmail)};Appcues.prototype.identify=function(identify){window.Appcues.identify(identify.traits())}},{"analytics.js-integration":81,"load-script":118,is:84}],118:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadScript(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;if("function"==type(fn)){onload(script,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript)});return script}},{"script-onload":106,"next-tick":95,type:7}],13:[function(require,module,exports){var integration=require("analytics.js-integration");var each=require("each");var Awesm=module.exports=integration("awe.sm").assumesPageview().global("AWESM").option("apiKey","").tag('<script src="//widgets.awe.sm/v3/widgets.js?key={{ apiKey }}&async=true">').mapping("events");Awesm.prototype.initialize=function(page){window.AWESM={api_key:this.options.apiKey};this.load(this.ready)};Awesm.prototype.loaded=function(){return!!(window.AWESM&&window.AWESM._exists)};Awesm.prototype.track=function(track){var user=this.analytics.user();var goals=this.events(track.event());each(goals,function(goal){window.AWESM.convert(goal,track.cents(),null,user.id())})}},{"analytics.js-integration":81,each:4}],14:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var noop=function(){};var onBody=require("on-body");var Awesomatic=module.exports=integration("Awesomatic").assumesPageview().global("Awesomatic").global("AwesomaticSettings").global("AwsmSetup").global("AwsmTmp").option("appId","").tag('<script src="https://1c817b7a15b6941337c0-dff9b5f4adb7ba28259631e99c3f3691.ssl.cf2.rackcdn.com/gen/embed.js">');Awesomatic.prototype.initialize=function(page){var self=this;var user=this.analytics.user();var id=user.id();var options=user.traits();options.appId=this.options.appId;if(id)options.user_id=id;this.load(function(){window.Awesomatic.initialize(options,function(){self.ready()})})};Awesomatic.prototype.loaded=function(){return is.object(window.Awesomatic)}},{"analytics.js-integration":81,is:84,"on-body":119}],119:[function(require,module,exports){var each=require("each");var body=false;var callbacks=[];module.exports=function onBody(callback){if(body){call(callback)}else{callbacks.push(callback)}};var interval=setInterval(function(){if(!document.body)return;body=true;each(callbacks,call);clearInterval(interval)},5);function call(callback){callback(document.body)}},{each:104}],15:[function(require,module,exports){var integration=require("analytics.js-integration");var onbody=require("on-body");var domify=require("domify");var extend=require("extend");var bind=require("bind");var when=require("when");var each=require("each");var has=Object.prototype.hasOwnProperty;var noop=function(){};var Bing=module.exports=integration("Bing Ads").option("siteId","").option("domainId","").tag('<script id="mstag_tops" src="//flex.msn.com/mstag/site/{{ siteId }}/mstag.js">').mapping("events");Bing.prototype.initialize=function(page){if(!window.mstag){window.mstag={loadTag:noop,time:(new Date).getTime(),_write:writeToAppend}}var self=this;onbody(function(){self.load(function(){var loaded=bind(self,self.loaded);when(loaded,self.ready)})})};Bing.prototype.loaded=function(){return!!(window.mstag&&window.mstag.loadTag!==noop)};Bing.prototype.track=function(track){var events=this.events(track.event());var revenue=track.revenue()||0;var self=this;each(events,function(goal){window.mstag.loadTag("analytics",{domainId:self.options.domainId,revenue:revenue,dedup:"1",type:"1",actionid:goal})})};function writeToAppend(str){var first=document.getElementsByTagName("script")[0];var el=domify(str);if("script"==el.tagName.toLowerCase()&&el.getAttribute("src")){var tmp=document.createElement("script");tmp.src=el.getAttribute("src");tmp.async=true;el=tmp}document.body.appendChild(el)}},{"analytics.js-integration":81,"on-body":119,domify:117,extend:120,bind:93,when:121,each:4}],120:[function(require,module,exports){module.exports=function extend(object){var args=Array.prototype.slice.call(arguments,1);for(var i=0,source;source=args[i];i++){if(!source)continue;for(var property in source){object[property]=source[property]}}return object}},{}],121:[function(require,module,exports){var callback=require("callback");module.exports=when;function when(condition,fn,interval){if(condition())return callback.async(fn);var ref=setInterval(function(){if(!condition())return;callback(fn);clearInterval(ref)},interval||10)}},{callback:86}],16:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var Track=require("facade").Track;var pixel=require("load-pixel")("http://app.bronto.com/public/");var qs=require("querystring");var each=require("each");var Bronto=module.exports=integration("Bronto").global("__bta").option("siteId","").option("host","").tag('<script src="//p.bm23.com/bta.js">');Bronto.prototype.initialize=function(page){var self=this;var params=qs.parse(window.location.search);if(!params._bta_tid&&!params._bta_c){this.debug("missing tracking URL parameters `_bta_tid` and `_bta_c`.")}this.load(function(){var opts=self.options;self.bta=new window.__bta(opts.siteId);if(opts.host)self.bta.setHost(opts.host);self.ready()})};Bronto.prototype.loaded=function(){return this.bta};Bronto.prototype.completedOrder=function(track){var user=this.analytics.user();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({userId:user.id(),traits:user.traits()});var email=identify.email();each(products,function(product){var track=new Track({properties:product});items.push({item_id:track.id()||track.sku(),desc:product.description||track.name(),quantity:track.quantity(),amount:track.price()})});this.bta.addOrder({order_id:track.orderId(),email:email,items:items})}},{"analytics.js-integration":81,facade:122,"load-pixel":123,querystring:124,each:4}],122:[function(require,module,exports){var Facade=require("./facade");module.exports=Facade;Facade.Alias=require("./alias");Facade.Group=require("./group");Facade.Identify=require("./identify");Facade.Track=require("./track");Facade.Page=require("./page");Facade.Screen=require("./screen")},{"./facade":125,"./alias":126,"./group":127,"./identify":128,"./track":129,"./page":130,"./screen":131}],125:[function(require,module,exports){var traverse=require("isodate-traverse");var isEnabled=require("./is-enabled");var clone=require("./utils").clone;var type=require("./utils").type;var address=require("./address");var objCase=require("obj-case");var newDate=require("new-date");module.exports=Facade;function Facade(obj){if(!obj.hasOwnProperty("timestamp"))obj.timestamp=new Date;else obj.timestamp=newDate(obj.timestamp);traverse(obj);this.obj=obj}address(Facade.prototype);Facade.prototype.proxy=function(field){var fields=field.split(".");field=fields.shift();var obj=this[field]||this.field(field);if(!obj)return obj;if(typeof obj==="function")obj=obj.call(this)||{};if(fields.length===0)return transform(obj);obj=objCase(obj,fields.join("."));return transform(obj)};Facade.prototype.field=function(field){var obj=this.obj[field];return transform(obj)};Facade.proxy=function(field){return function(){return this.proxy(field)}};Facade.field=function(field){return function(){return this.field(field)}};Facade.multi=function(path){return function(){var multi=this.proxy(path+"s");if("array"==type(multi))return multi;var one=this.proxy(path);if(one)one=[clone(one)];return one||[]}};Facade.one=function(path){return function(){var one=this.proxy(path);if(one)return one;var multi=this.proxy(path+"s");if("array"==type(multi))return multi[0]}};Facade.prototype.json=function(){var ret=clone(this.obj);if(this.type)ret.type=this.type();return ret};Facade.prototype.context=Facade.prototype.options=function(integration){var options=clone(this.obj.options||this.obj.context)||{};if(!integration)return clone(options);if(!this.enabled(integration))return;var integrations=this.integrations();var value=integrations[integration]||objCase(integrations,integration);if("boolean"==typeof value)value={};return value||{}};Facade.prototype.enabled=function(integration){var allEnabled=this.proxy("options.providers.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("options.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("integrations.all");if(typeof allEnabled!=="boolean")allEnabled=true;var enabled=allEnabled&&isEnabled(integration);var options=this.integrations();if(options.providers&&options.providers.hasOwnProperty(integration)){enabled=options.providers[integration]}if(options.hasOwnProperty(integration)){var settings=options[integration];if(typeof settings==="boolean"){enabled=settings}else{enabled=true}}return enabled?true:false};Facade.prototype.integrations=function(){return this.obj.integrations||this.proxy("options.providers")||this.options()};Facade.prototype.active=function(){var active=this.proxy("options.active");if(active===null||active===undefined)active=true;return active};Facade.prototype.sessionId=Facade.prototype.anonymousId=function(){return this.field("anonymousId")||this.field("sessionId")};Facade.prototype.groupId=Facade.proxy("options.groupId");Facade.prototype.traits=function(aliases){var ret=this.proxy("options.traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("options.traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Facade.prototype.library=function(){var library=this.proxy("options.library");if(!library)return{name:"unknown",version:null};if(typeof library==="string")return{name:library,version:null};return library};Facade.prototype.userId=Facade.field("userId");Facade.prototype.channel=Facade.field("channel");Facade.prototype.timestamp=Facade.field("timestamp");Facade.prototype.userAgent=Facade.proxy("options.userAgent");Facade.prototype.ip=Facade.proxy("options.ip");function transform(obj){var cloned=clone(obj);return cloned}},{"isodate-traverse":132,"./is-enabled":133,"./utils":134,"./address":135,"obj-case":136,"new-date":137}],132:[function(require,module,exports){var is=require("is");var isodate=require("isodate");var each;try{each=require("each")}catch(err){each=require("each-component")}module.exports=traverse;function traverse(input,strict){if(strict===undefined)strict=true;if(is.object(input))return object(input,strict);if(is.array(input))return array(input,strict);return input}function object(obj,strict){each(obj,function(key,val){if(isodate.is(val,strict)){obj[key]=isodate.parse(val)}else if(is.object(val)||is.array(val)){traverse(val,strict)}});return obj}function array(arr,strict){each(arr,function(val,x){if(is.object(val)){traverse(val,strict)}else if(isodate.is(val,strict)){arr[x]=isodate.parse(val)}});return arr}},{is:138,isodate:139,each:4}],138:[function(require,module,exports){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":116,type:7,"component-type":7}],139:[function(require,module,exports){var matcher=/^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;exports.parse=function(iso){var numericKeys=[1,5,6,7,11,12];var arr=matcher.exec(iso);var offset=0;if(!arr)return new Date(iso);for(var i=0,val;val=numericKeys[i];i++){arr[val]=parseInt(arr[val],10)||0}arr[2]=parseInt(arr[2],10)||1;arr[3]=parseInt(arr[3],10)||1;arr[2]--;arr[8]=arr[8]?(arr[8]+"00").substring(0,3):0;if(arr[4]==" "){offset=(new Date).getTimezoneOffset()}else if(arr[9]!=="Z"&&arr[10]){offset=arr[11]*60+arr[12];if("+"==arr[10])offset=0-offset}var millis=Date.UTC(arr[1],arr[2],arr[3],arr[5],arr[6]+offset,arr[7],arr[8]);return new Date(millis)};exports.is=function(string,strict){if(strict&&false===/^\d{4}-\d{2}-\d{2}/.test(string))return false;return matcher.test(string)}},{}],133:[function(require,module,exports){var disabled={Salesforce:true};module.exports=function(integration){return!disabled[integration]}},{}],134:[function(require,module,exports){try{exports.inherit=require("inherit");exports.clone=require("clone");exports.type=require("type")}catch(e){exports.inherit=require("inherit-component");exports.clone=require("clone-component");exports.type=require("type-component")}},{inherit:140,clone:141,type:7}],140:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],141:[function(require,module,exports){var type;try{type=require("component-type")}catch(_){type=require("type")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{"component-type":7,type:7}],135:[function(require,module,exports){var get=require("obj-case");module.exports=function(proto){proto.zip=trait("postalCode","zip");proto.country=trait("country");proto.street=trait("street");proto.state=trait("state");proto.city=trait("city");function trait(a,b){return function(){var traits=this.traits();var props=this.properties?this.properties():{};return get(traits,"address."+a)||get(traits,a)||(b?get(traits,"address."+b):null)||(b?get(traits,b):null)||get(props,"address."+a)||get(props,a)||(b?get(props,"address."+b):null)||(b?get(props,b):null)}}}},{"obj-case":136}],136:[function(require,module,exports){var identity=function(_){return _};module.exports=module.exports.find=multiple(find);module.exports.replace=function(obj,key,val){multiple(replace).apply(this,arguments);return obj};module.exports.del=function(obj,key){multiple(del).apply(this,arguments);return obj};function multiple(fn){return function(obj,path,val){path=normalize(path);var key;var finished=false;while(!finished)loop();function loop(){for(key in obj){var normalizedKey=normalize(key);if(0===path.indexOf(normalizedKey)){var temp=path.substr(normalizedKey.length);if(temp.charAt(0)==="."||temp.length===0){path=temp.substr(1);var child=obj[key];if(null==child){finished=true;obj=null;return}if(!path.length){finished=true;return}obj=child;return}}}key=undefined;finished=true}if(!key)return;return fn(obj,key,val)}}function find(obj,key){if(obj.hasOwnProperty(key))return obj[key]}function del(obj,key){if(obj.hasOwnProperty(key))delete obj[key];return obj}function replace(obj,key,val){if(obj.hasOwnProperty(key))obj[key]=val;return obj}function normalize(path){return path.replace(/[^a-zA-Z0-9\.]+/g,"").toLowerCase()}},{}],137:[function(require,module,exports){var is=require("is");var isodate=require("isodate");var milliseconds=require("./milliseconds");var seconds=require("./seconds");module.exports=function newDate(val){if(is.date(val))return val;if(is.number(val))return new Date(toMs(val));if(isodate.is(val))return isodate.parse(val);if(milliseconds.is(val))return milliseconds.parse(val);if(seconds.is(val))return seconds.parse(val);return new Date(val)};function toMs(num){if(num<315576e5)return num*1e3;return num}},{is:142,isodate:139,"./milliseconds":143,"./seconds":144}],142:[function(require,module,exports){var isEmpty=require("is-empty"),typeOf=require("type");var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":116,type:7}],143:[function(require,module,exports){var matcher=/\d{13}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(millis){millis=parseInt(millis,10);return new Date(millis)}},{}],144:[function(require,module,exports){var matcher=/\d{10}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(seconds){var millis=parseInt(seconds,10)*1e3;return new Date(millis)}},{}],126:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");module.exports=Alias;function Alias(dictionary){Facade.call(this,dictionary)}inherit(Alias,Facade);Alias.prototype.type=Alias.prototype.action=function(){return"alias"};Alias.prototype.from=Alias.prototype.previousId=function(){return this.field("previousId")||this.field("from")};Alias.prototype.to=Alias.prototype.userId=function(){return this.field("userId")||this.field("to")}},{"./utils":134,"./facade":125}],127:[function(require,module,exports){var inherit=require("./utils").inherit;var address=require("./address");var isEmail=require("is-email");var newDate=require("new-date");var Facade=require("./facade");module.exports=Group;function Group(dictionary){Facade.call(this,dictionary)}inherit(Group,Facade);Group.prototype.type=Group.prototype.action=function(){return"group"};Group.prototype.groupId=Facade.field("groupId");Group.prototype.created=function(){var created=this.proxy("traits.createdAt")||this.proxy("traits.created")||this.proxy("properties.createdAt")||this.proxy("properties.created");if(created)return newDate(created)};Group.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var groupId=this.groupId();if(isEmail(groupId))return groupId};Group.prototype.traits=function(aliases){var ret=this.properties();var id=this.groupId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Group.prototype.name=Facade.proxy("traits.name");Group.prototype.industry=Facade.proxy("traits.industry");Group.prototype.employees=Facade.proxy("traits.employees");Group.prototype.properties=function(){return this.field("traits")||this.field("properties")||{}}},{"./utils":134,"./address":135,"is-email":145,"new-date":137,"./facade":125}],145:[function(require,module,exports){module.exports=isEmail;var matcher=/.+\@.+\..+/;function isEmail(string){return matcher.test(string)}},{}],128:[function(require,module,exports){var address=require("./address");var Facade=require("./facade");var isEmail=require("is-email");var newDate=require("new-date");var utils=require("./utils");var get=require("obj-case");var trim=require("trim");var inherit=utils.inherit;var clone=utils.clone;var type=utils.type;module.exports=Identify;function Identify(dictionary){Facade.call(this,dictionary)}inherit(Identify,Facade);Identify.prototype.type=Identify.prototype.action=function(){return"identify"};Identify.prototype.traits=function(aliases){var ret=this.field("traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;if(alias!==aliases[alias])delete ret[alias]}return ret};Identify.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Identify.prototype.created=function(){var created=this.proxy("traits.created")||this.proxy("traits.createdAt");if(created)return newDate(created)};Identify.prototype.companyCreated=function(){var created=this.proxy("traits.company.created")||this.proxy("traits.company.createdAt");if(created)return newDate(created)};Identify.prototype.name=function(){var name=this.proxy("traits.name");if(typeof name==="string")return trim(name);var firstName=this.firstName();var lastName=this.lastName();if(firstName&&lastName)return trim(firstName+" "+lastName)};Identify.prototype.firstName=function(){var firstName=this.proxy("traits.firstName");if(typeof firstName==="string")return trim(firstName);var name=this.proxy("traits.name");if(typeof name==="string")return trim(name).split(" ")[0]};Identify.prototype.lastName=function(){var lastName=this.proxy("traits.lastName");if(typeof lastName==="string")return trim(lastName);var name=this.proxy("traits.name");if(typeof name!=="string")return;var space=trim(name).indexOf(" ");if(space===-1)return;return trim(name.substr(space+1))};Identify.prototype.uid=function(){return this.userId()||this.username()||this.email()};Identify.prototype.description=function(){return this.proxy("traits.description")||this.proxy("traits.background")};Identify.prototype.age=function(){var date=this.birthday();
var age=get(this.traits(),"age");if(null!=age)return age;if("date"!=type(date))return;var now=new Date;return now.getFullYear()-date.getFullYear()};Identify.prototype.avatar=function(){var traits=this.traits();return get(traits,"avatar")||get(traits,"photoUrl")||get(traits,"avatarUrl")};Identify.prototype.position=function(){var traits=this.traits();return get(traits,"position")||get(traits,"jobTitle")};Identify.prototype.username=Facade.proxy("traits.username");Identify.prototype.website=Facade.one("traits.website");Identify.prototype.websites=Facade.multi("traits.website");Identify.prototype.phone=Facade.one("traits.phone");Identify.prototype.phones=Facade.multi("traits.phone");Identify.prototype.address=Facade.proxy("traits.address");Identify.prototype.gender=Facade.proxy("traits.gender");Identify.prototype.birthday=Facade.proxy("traits.birthday")},{"./address":135,"./facade":125,"is-email":145,"new-date":137,"./utils":134,"obj-case":136,trim:146}],146:[function(require,module,exports){exports=module.exports=trim;function trim(str){if(str.trim)return str.trim();return str.replace(/^\s*|\s*$/g,"")}exports.left=function(str){if(str.trimLeft)return str.trimLeft();return str.replace(/^\s*/,"")};exports.right=function(str){if(str.trimRight)return str.trimRight();return str.replace(/\s*$/,"")}},{}],129:[function(require,module,exports){var inherit=require("./utils").inherit;var clone=require("./utils").clone;var type=require("./utils").type;var Facade=require("./facade");var Identify=require("./identify");var isEmail=require("is-email");var get=require("obj-case");module.exports=Track;function Track(dictionary){Facade.call(this,dictionary)}inherit(Track,Facade);Track.prototype.type=Track.prototype.action=function(){return"track"};Track.prototype.event=Facade.field("event");Track.prototype.value=Facade.proxy("properties.value");Track.prototype.category=Facade.proxy("properties.category");Track.prototype.id=Facade.proxy("properties.id");Track.prototype.sku=Facade.proxy("properties.sku");Track.prototype.tax=Facade.proxy("properties.tax");Track.prototype.name=Facade.proxy("properties.name");Track.prototype.price=Facade.proxy("properties.price");Track.prototype.total=Facade.proxy("properties.total");Track.prototype.coupon=Facade.proxy("properties.coupon");Track.prototype.shipping=Facade.proxy("properties.shipping");Track.prototype.discount=Facade.proxy("properties.discount");Track.prototype.description=Facade.proxy("properties.description");Track.prototype.plan=Facade.proxy("properties.plan");Track.prototype.orderId=function(){return this.proxy("properties.id")||this.proxy("properties.orderId")};Track.prototype.subtotal=function(){var subtotal=get(this.properties(),"subtotal");var total=this.total();var n;if(subtotal)return subtotal;if(!total)return 0;if(n=this.tax())total-=n;if(n=this.shipping())total-=n;if(n=this.discount())total+=n;return total};Track.prototype.products=function(){var props=this.properties();var products=get(props,"products");return"array"==type(products)?products:[]};Track.prototype.quantity=function(){var props=this.obj.properties||{};return props.quantity||1};Track.prototype.currency=function(){var props=this.obj.properties||{};return props.currency||"USD"};Track.prototype.referrer=Facade.proxy("properties.referrer");Track.prototype.query=Facade.proxy("options.query");Track.prototype.properties=function(aliases){var ret=this.field("properties")||{};aliases=aliases||{};for(var alias in aliases){var value=null==this[alias]?this.proxy("properties."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Track.prototype.username=function(){return this.proxy("traits.username")||this.proxy("properties.username")||this.userId()||this.sessionId()};Track.prototype.email=function(){var email=this.proxy("traits.email");email=email||this.proxy("properties.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Track.prototype.revenue=function(){var revenue=this.proxy("properties.revenue");var event=this.event();if(!revenue&&event&&event.match(/completed ?order/i)){revenue=this.proxy("properties.total")}return currency(revenue)};Track.prototype.cents=function(){var revenue=this.revenue();return"number"!=typeof revenue?this.value()||0:revenue*100};Track.prototype.identify=function(){var json=this.json();json.traits=this.traits();return new Identify(json)};function currency(val){if(!val)return;if(typeof val==="number")return val;if(typeof val!=="string")return;val=val.replace(/\$/g,"");val=parseFloat(val);if(!isNaN(val))return val}},{"./utils":134,"./facade":125,"./identify":128,"is-email":145,"obj-case":136}],130:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");var Track=require("./track");module.exports=Page;function Page(dictionary){Facade.call(this,dictionary)}inherit(Page,Facade);Page.prototype.type=Page.prototype.action=function(){return"page"};Page.prototype.category=Facade.field("category");Page.prototype.name=Facade.field("name");Page.prototype.title=Facade.proxy("properties.title");Page.prototype.path=Facade.proxy("properties.path");Page.prototype.url=Facade.proxy("properties.url");Page.prototype.properties=function(){var props=this.field("properties")||{};var category=this.category();var name=this.name();if(category)props.category=category;if(name)props.name=name;return props};Page.prototype.fullName=function(){var category=this.category();var name=this.name();return name&&category?category+" "+name:name};Page.prototype.event=function(name){return name?"Viewed "+name+" Page":"Loaded a Page"};Page.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),timestamp:this.timestamp(),context:this.context(),properties:props})}},{"./utils":134,"./facade":125,"./track":129}],131:[function(require,module,exports){var inherit=require("./utils").inherit;var Page=require("./page");var Track=require("./track");module.exports=Screen;function Screen(dictionary){Page.call(this,dictionary)}inherit(Screen,Page);Screen.prototype.type=Screen.prototype.action=function(){return"screen"};Screen.prototype.event=function(name){return name?"Viewed "+name+" Screen":"Loaded a Screen"};Screen.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),timestamp:this.timestamp(),context:this.context(),properties:props})}},{"./utils":134,"./page":130,"./track":129}],123:[function(require,module,exports){var stringify=require("querystring").stringify;var sub=require("substitute");module.exports=function(path){return function(query,obj,fn){if("function"==typeof obj)fn=obj,obj={};obj=obj||{};fn=fn||function(){};var url=sub(path,obj);var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};query=stringify(query);if(query)query="?"+query;img.src=url+query;img.width=1;img.height=1;return img}};function error(fn,message,img){return function(e){e=e||window.event;var err=new Error(message);err.event=e;err.source=img;fn(err)}}},{querystring:124,substitute:147}],124:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=/(\w+)\[(\d+)\]/.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:146,type:7}],147:[function(require,module,exports){module.exports=substitute;var type=Object.prototype.toString;function substitute(str,obj,expr){if(!obj)throw new TypeError("expected an object");expr=expr||/:(\w+)/g;return str.replace(expr,function(_,prop){switch(type.call(obj)){case"[object Object]":return null!=obj[prop]?obj[prop]:_;case"[object Array]":var val=obj.shift();return null!=val?val:_}})}},{}],17:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var BugHerd=module.exports=integration("BugHerd").assumesPageview().global("BugHerdConfig").global("_bugHerd").option("apiKey","").option("showFeedbackTab",true).tag('<script src="//www.bugherd.com/sidebarv2.js?apikey={{ apiKey }}">');BugHerd.prototype.initialize=function(page){window.BugHerdConfig={feedback:{hide:!this.options.showFeedbackTab}};var ready=this.ready;this.load(function(){tick(ready)})};BugHerd.prototype.loaded=function(){return!!window._bugHerd}},{"analytics.js-integration":81,"next-tick":95}],18:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var extend=require("extend");var onError=require("on-error");var Bugsnag=module.exports=integration("Bugsnag").global("Bugsnag").option("apiKey","").tag('<script src="//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js">');Bugsnag.prototype.initialize=function(page){var self=this;this.load(function(){window.Bugsnag.apiKey=self.options.apiKey;self.ready()})};Bugsnag.prototype.loaded=function(){return is.object(window.Bugsnag)};Bugsnag.prototype.identify=function(identify){window.Bugsnag.metaData=window.Bugsnag.metaData||{};extend(window.Bugsnag.metaData,identify.traits())}},{"analytics.js-integration":81,is:84,extend:120,"on-error":148}],148:[function(require,module,exports){module.exports=onError;var callbacks=[];if("function"==typeof window.onerror)callbacks.push(window.onerror);window.onerror=handler;function handler(){for(var i=0,fn;fn=callbacks[i];i++)fn.apply(this,arguments)}function onError(fn){callbacks.push(fn);if(window.onerror!=handler){callbacks.push(window.onerror);window.onerror=handler}}},{}],19:[function(require,module,exports){var integration=require("analytics.js-integration");var defaults=require("defaults");var onBody=require("on-body");var Chartbeat=module.exports=integration("Chartbeat").assumesPageview().global("_sf_async_config").global("_sf_endpt").global("pSUPERFLY").option("domain","").option("uid",null).tag('<script src="//static.chartbeat.com/js/chartbeat.js">');Chartbeat.prototype.initialize=function(page){var self=this;window._sf_async_config=window._sf_async_config||{};window._sf_async_config.useCanonical=true;defaults(window._sf_async_config,this.options);onBody(function(){window._sf_endpt=(new Date).getTime();self.load(self.ready)})};Chartbeat.prototype.loaded=function(){return!!window.pSUPERFLY};Chartbeat.prototype.page=function(page){var props=page.properties();var name=page.fullName();window.pSUPERFLY.virtualPage(props.path,name||props.title)}},{"analytics.js-integration":81,defaults:149,"on-body":119}],149:[function(require,module,exports){module.exports=defaults;function defaults(dest,defaults){for(var prop in defaults){if(!(prop in dest)){dest[prop]=defaults[prop]}}return dest}},{}],20:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_cbq");var each=require("each");var has=Object.prototype.hasOwnProperty;var supported={activation:true,changePlan:true,register:true,refund:true,charge:true,cancel:true,login:true};var ChurnBee=module.exports=integration("ChurnBee").global("_cbq").global("ChurnBee").option("apiKey","").tag('<script src="//api.churnbee.com/cb.js">').mapping("events");ChurnBee.prototype.initialize=function(page){push("_setApiKey",this.options.apiKey);this.load(this.ready)};ChurnBee.prototype.loaded=function(){return!!window.ChurnBee};ChurnBee.prototype.track=function(track){var event=track.event();var events=this.events(event);events.push(event);each(events,function(event){if(true!=supported[event])return;push(event,track.properties({revenue:"amount"}))})}},{"analytics.js-integration":81,"global-queue":150,each:4}],150:[function(require,module,exports){module.exports=generate;function generate(name,options){options=options||{};return function(args){args=[].slice.call(arguments);window[name]||(window[name]=[]);options.wrap===false?window[name].push.apply(window[name],args):window[name].push(args)}}},{}],21:[function(require,module,exports){var date=require("load-date");var domify=require("domify");var each=require("each");var integration=require("analytics.js-integration");var is=require("is");var useHttps=require("use-https");var onBody=require("on-body");var ClickTale=module.exports=integration("ClickTale").assumesPageview().global("WRInitTime").global("ClickTale").global("ClickTaleSetUID").global("ClickTaleField").global("ClickTaleEvent").option("httpCdnUrl","http://s.clicktale.net/WRe0.js").option("httpsCdnUrl","").option("projectId","").option("recordingRatio",.01).option("partitionId","").tag('<script src="{{src}}">');ClickTale.prototype.initialize=function(page){var self=this;window.WRInitTime=date.getTime();onBody(function(body){body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">'))});var http=this.options.httpCdnUrl;var https=this.options.httpsCdnUrl;if(useHttps()&&!https)return this.debug("https option required");var src=useHttps()?https:http;this.load({src:src},function(){window.ClickTale(self.options.projectId,self.options.recordingRatio,self.options.partitionId);self.ready()})};ClickTale.prototype.loaded=function(){return is.fn(window.ClickTale)};ClickTale.prototype.identify=function(identify){var id=identify.userId();window.ClickTaleSetUID(id);each(identify.traits(),function(key,value){window.ClickTaleField(key,value)})};ClickTale.prototype.track=function(track){window.ClickTaleEvent(track.event())}},{"load-date":151,domify:117,each:4,"analytics.js-integration":81,is:84,"use-https":83,"on-body":119}],151:[function(require,module,exports){var time=new Date,perf=window.performance;if(perf&&perf.timing&&perf.timing.responseEnd){time=new Date(perf.timing.responseEnd)}module.exports=time},{}],22:[function(require,module,exports){var Identify=require("facade").Identify;var extend=require("extend");var integration=require("analytics.js-integration");var is=require("is");var Clicky=module.exports=integration("Clicky").assumesPageview().global("clicky").global("clicky_site_ids").global("clicky_custom").option("siteId",null).tag('<script src="//static.getclicky.com/js"></script>');Clicky.prototype.initialize=function(page){var user=this.analytics.user();window.clicky_site_ids=window.clicky_site_ids||[this.options.siteId];this.identify(new Identify({userId:user.id(),traits:user.traits()}));this.load(this.ready)};Clicky.prototype.loaded=function(){return is.object(window.clicky)};Clicky.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();window.clicky.log(properties.path,name||properties.title)};Clicky.prototype.identify=function(identify){window.clicky_custom=window.clicky_custom||{};window.clicky_custom.session=window.clicky_custom.session||{};extend(window.clicky_custom.session,identify.traits())};Clicky.prototype.track=function(track){window.clicky.goal(track.event(),track.revenue())}},{facade:122,extend:120,"analytics.js-integration":81,is:84}],23:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var Comscore=module.exports=integration("comScore").assumesPageview().global("_comscore").global("COMSCORE").option("c1","2").option("c2","").tag("http",'<script src="http://b.scorecardresearch.com/beacon.js">').tag("https",'<script src="https://sb.scorecardresearch.com/beacon.js">');Comscore.prototype.initialize=function(page){window._comscore=window._comscore||[this.options];var name=useHttps()?"https":"http";this.load(name,this.ready)};Comscore.prototype.loaded=function(){return!!window.COMSCORE}},{"analytics.js-integration":81,"use-https":83}],24:[function(require,module,exports){var integration=require("analytics.js-integration");var CrazyEgg=module.exports=integration("Crazy Egg").assumesPageview().global("CE2").option("accountNumber","").tag('<script src="//dnn506yrbagrg.cloudfront.net/pages/scripts/{{ path }}.js?{{ cache }}">');CrazyEgg.prototype.initialize=function(page){var number=this.options.accountNumber;var path=number.slice(0,4)+"/"+number.slice(4);var cache=Math.floor((new Date).getTime()/36e5);this.load({path:path,cache:cache},this.ready)};CrazyEgg.prototype.loaded=function(){return!!window.CE2}},{"analytics.js-integration":81}],25:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_curebitq");var Identify=require("facade").Identify;var throttle=require("throttle");var Track=require("facade").Track;var iso=require("to-iso-string");var clone=require("clone");var each=require("each");var bind=require("bind");var Curebit=module.exports=integration("Curebit").global("_curebitq").global("curebit").option("siteId","").option("iframeWidth","100%").option("iframeHeight","480").option("iframeBorder",0).option("iframeId","curebit_integration").option("responsive",true).option("device","").option("insertIntoId","").option("campaigns",{}).option("server","https://www.curebit.com").tag('<script src="//d2jjzw81hqbuqv.cloudfront.net/integration/curebit-1.0.min.js">');Curebit.prototype.initialize=function(page){push("init",{site_id:this.options.siteId,server:this.options.server});this.load(this.ready);this.page=throttle(bind(this,this.page),250)};Curebit.prototype.loaded=function(){return!!window.curebit};Curebit.prototype.injectIntoId=function(url,id,fn){var server=this.options.server;when(function(){return document.getElementById(id)},function(){var script=document.createElement("script");script.src=url;var parent=document.getElementById(id);parent.appendChild(script);onload(script,fn)})};Curebit.prototype.page=function(page){var user=this.analytics.user();var campaigns=this.options.campaigns;var path=window.location.pathname;if(!campaigns[path])return;var tags=(campaigns[path]||"").split(",");if(!tags.length)return;var settings={responsive:this.options.responsive,device:this.options.device,campaign_tags:tags,iframe:{width:this.options.iframeWidth,height:this.options.iframeHeight,id:this.options.iframeId,frameborder:this.options.iframeBorder,container:this.options.insertIntoId}};var identify=new Identify({userId:user.id(),traits:user.traits()});if(identify.email()){settings.affiliate_member={email:identify.email(),first_name:identify.firstName(),last_name:identify.lastName(),customer_id:identify.userId()}}push("register_affiliate",settings)};Curebit.prototype.completedOrder=function(track){var user=this.analytics.user();var orderId=track.orderId();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({traits:user.traits(),userId:user.id()});each(products,function(product){var track=new Track({properties:product});items.push({product_id:track.id()||track.sku(),quantity:track.quantity(),image_url:product.image,price:track.price(),title:track.name(),url:product.url})});push("register_purchase",{order_date:iso(props.date||new Date),order_number:orderId,coupon_code:track.coupon(),subtotal:track.total(),customer_id:identify.userId(),first_name:identify.firstName(),last_name:identify.lastName(),email:identify.email(),items:items})}},{"analytics.js-integration":81,"global-queue":150,facade:122,throttle:152,"to-iso-string":153,clone:154,each:4,bind:93}],152:[function(require,module,exports){module.exports=throttle;function throttle(func,wait){var rtn;var last=0;return function throttled(){var now=(new Date).getTime();var delta=now-last;if(delta>=wait){rtn=func.apply(this,arguments);last=now}return rtn}}},{}],153:[function(require,module,exports){module.exports=toIsoString;function toIsoString(date){return date.getUTCFullYear()+"-"+pad(date.getUTCMonth()+1)+"-"+pad(date.getUTCDate())+"T"+pad(date.getUTCHours())+":"+pad(date.getUTCMinutes())+":"+pad(date.getUTCSeconds())+"."+String((date.getUTCMilliseconds()/1e3).toFixed(3)).slice(2,5)+"Z"}function pad(number){var n=number.toString();return n.length===1?"0"+n:n}},{}],154:[function(require,module,exports){var type;try{type=require("type")}catch(e){type=require("type-component")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{type:7}],26:[function(require,module,exports){var alias=require("alias");var convertDates=require("convert-dates");var Identify=require("facade").Identify;var integration=require("analytics.js-integration");var Customerio=module.exports=integration("Customer.io").assumesPageview().global("_cio").option("siteId","").tag('<script id="cio-tracker" src="https://assets.customer.io/assets/track.js" data-site-id="{{ siteId }}">');Customerio.prototype.initialize=function(page){window._cio=window._cio||[];(function(){var a,b,c;a=function(f){return function(){window._cio.push([f].concat(Array.prototype.slice.call(arguments,0)))}};b=["identify","track"];for(c=0;c<b.length;c++){window._cio[b[c]]=a(b[c])}})();this.load(this.ready)};Customerio.prototype.loaded=function(){return!!window._cio&&window._cio.push!==Array.prototype.push};Customerio.prototype.identify=function(identify){if(!identify.userId())return this.debug("user id required");var traits=identify.traits({created:"created_at"});traits=convertDates(traits,convertDate);window._cio.identify(traits)};Customerio.prototype.group=function(group){var traits=group.traits();var user=this.analytics.user();traits=alias(traits,function(trait){return"Group "+trait});this.identify(new Identify({userId:user.id(),traits:traits}))};Customerio.prototype.track=function(track){var properties=track.properties();properties=convertDates(properties,convertDate);window._cio.track(track.event(),properties)};function convertDate(date){return Math.floor(date.getTime()/1e3)}},{alias:155,"convert-dates":156,facade:122,"analytics.js-integration":81}],155:[function(require,module,exports){var type=require("type");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=alias;function alias(obj,method){switch(type(method)){case"object":return aliasByDictionary(clone(obj),method);case"function":return aliasByFunction(clone(obj),method)}}function aliasByDictionary(obj,aliases){for(var key in aliases){if(undefined===obj[key])continue;obj[aliases[key]]=obj[key];delete obj[key]}return obj}function aliasByFunction(obj,convert){var output={};for(var key in obj)output[convert(key)]=obj[key];return output}},{type:7,clone:141}],156:[function(require,module,exports){var is=require("is");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=convertDates;function convertDates(obj,convert){obj=clone(obj);for(var key in obj){var val=obj[key];if(is.date(val))obj[key]=convert(val);if(is.object(val))obj[key]=convertDates(val,convert)}return obj}},{is:84,clone:87}],27:[function(require,module,exports){var alias=require("alias");var integration=require("analytics.js-integration");var is=require("is");var load=require("load-script");var push=require("global-queue")("_dcq");var Drip=module.exports=integration("Drip").assumesPageview().global("dc").global("_dcq").global("_dcs").option("account","").tag('<script src="//tag.getdrip.com/{{ account }}.js">');Drip.prototype.initialize=function(page){window._dcq=window._dcq||[];window._dcs=window._dcs||{};window._dcs.account=this.options.account;this.load(this.ready)};Drip.prototype.loaded=function(){return is.object(window.dc)};Drip.prototype.track=function(track){var props=track.properties();var cents=track.cents();if(cents)props.value=cents;delete props.revenue;push("track",track.event(),props)};Drip.prototype.identify=function(identify){push("identify",identify.traits())}},{alias:155,"analytics.js-integration":81,is:84,"load-script":118,"global-queue":150}],28:[function(require,module,exports){var extend=require("extend");var integration=require("analytics.js-integration");var onError=require("on-error");var push=require("global-queue")("_errs");var Errorception=module.exports=integration("Errorception").assumesPageview().global("_errs").option("projectId","").option("meta",true).tag('<script src="//beacon.errorception.com/{{ projectId }}.js">');Errorception.prototype.initialize=function(page){window._errs=window._errs||[this.options.projectId];onError(push);this.load(this.ready)};Errorception.prototype.loaded=function(){return!!(window._errs&&window._errs.push!==Array.prototype.push)};Errorception.prototype.identify=function(identify){if(!this.options.meta)return;var traits=identify.traits();window._errs=window._errs||[];window._errs.meta=window._errs.meta||{};extend(window._errs.meta,traits)}},{extend:120,"analytics.js-integration":81,"on-error":148,"global-queue":150}],29:[function(require,module,exports){var each=require("each");var integration=require("analytics.js-integration");var push=require("global-queue")("_aaq");var Evergage=module.exports=integration("Evergage").assumesPageview().global("_aaq").option("account","").option("dataset","").tag('<script src="//cdn.evergage.com/beacon/{{ account }}/{{ dataset }}/scripts/evergage.min.js">');Evergage.prototype.initialize=function(page){var account=this.options.account;var dataset=this.options.dataset;window._aaq=window._aaq||[];push("setEvergageAccount",account);push("setDataset",dataset);push("setUseSiteConfig",true);this.load(this.ready)};Evergage.prototype.loaded=function(){return!!(window._aaq&&window._aaq.push!==Array.prototype.push)};Evergage.prototype.page=function(page){var props=page.properties();var name=page.name();if(name)push("namePage",name);each(props,function(key,value){push("setCustomField",key,value,"page")});window.Evergage.init(true)};Evergage.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("setUser",id);var traits=identify.traits({email:"userEmail",name:"userName"});each(traits,function(key,value){push("setUserField",key,value,"page")})};Evergage.prototype.group=function(group){var props=group.traits();var id=group.groupId();if(!id)return;push("setCompany",id);each(props,function(key,value){push("setAccountField",key,value,"page")})};Evergage.prototype.track=function(track){push("trackAction",track.event(),track.properties())}},{each:4,"analytics.js-integration":81,"global-queue":150}],30:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_fbq");var each=require("each");var has=Object.prototype.hasOwnProperty;var Facebook=module.exports=integration("Facebook Conversion Tracking").global("_fbq").option("currency","USD").tag('<script src="//connect.facebook.net/en_US/fbds.js">').mapping("events");Facebook.prototype.initialize=function(page){window._fbq=window._fbq||[];this.load(this.ready);window._fbq.loaded=true};Facebook.prototype.loaded=function(){return!!(window._fbq&&window._fbq.loaded)};Facebook.prototype.track=function(track){var event=track.event();var events=this.events(event);var revenue=track.revenue()||0;var self=this;each(events,function(event){push("track",event,{value:String(revenue.toFixed(2)),currency:self.options.currency})});if(!events.length){var data=track.properties();push("track",event,data)}}},{"analytics.js-integration":81,"global-queue":150,each:4}],31:[function(require,module,exports){var push=require("global-queue")("_fxm");var integration=require("analytics.js-integration");var Track=require("facade").Track;var each=require("each");var FoxMetrics=module.exports=integration("FoxMetrics").assumesPageview().global("_fxm").option("appId","").tag('<script src="//d35tca7vmefkrc.cloudfront.net/scripts/{{ appId }}.js">');FoxMetrics.prototype.initialize=function(page){window._fxm=window._fxm||[];this.load(this.ready)};FoxMetrics.prototype.loaded=function(){return!!(window._fxm&&window._fxm.appId)};FoxMetrics.prototype.page=function(page){var properties=page.proxy("properties");var category=page.category();var name=page.name();this._category=category;push("_fxm.pages.view",properties.title,name,category,properties.url,properties.referrer)};FoxMetrics.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("_fxm.visitor.profile",id,identify.firstName(),identify.lastName(),identify.email(),identify.address(),undefined,undefined,identify.traits())};FoxMetrics.prototype.track=function(track){var props=track.properties();var category=this._category||props.category;push(track.event(),category,props)};FoxMetrics.prototype.viewedProduct=function(track){ecommerce("productview",track)};FoxMetrics.prototype.removedProduct=function(track){ecommerce("removecartitem",track)};FoxMetrics.prototype.addedProduct=function(track){ecommerce("cartitem",track)};FoxMetrics.prototype.completedOrder=function(track){var orderId=track.orderId();push("_fxm.ecommerce.order",orderId,track.subtotal(),track.shipping(),track.tax(),track.city(),track.state(),track.zip(),track.quantity());each(track.products(),function(product){var track=new Track({properties:product});ecommerce("purchaseitem",track,[track.quantity(),track.price(),orderId])})};function ecommerce(event,track,arr){push.apply(null,["_fxm.ecommerce."+event,track.id()||track.sku(),track.name(),track.category()].concat(arr||[]))}},{"global-queue":150,"analytics.js-integration":81,facade:122,each:4}],32:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var is=require("is");var Frontleaf=module.exports=integration("Frontleaf").assumesPageview().global("_fl").global("_flBaseUrl").option("baseUrl","https://api.frontleaf.com").option("token","").option("stream","").option("trackNamedPages",false).option("trackCategorizedPages",false).tag('<script id="_fl" src="{{ baseUrl }}/lib/tracker.js">');Frontleaf.prototype.initialize=function(page){window._fl=window._fl||[];window._flBaseUrl=window._flBaseUrl||this.options.baseUrl;this._push("setApiToken",this.options.token);this._push("setStream",this.options.stream);var loaded=bind(this,this.loaded);var ready=this.ready;this.load({baseUrl:window._flBaseUrl},this.ready)};Frontleaf.prototype.loaded=function(){return is.array(window._fl)&&window._fl.ready===true};Frontleaf.prototype.identify=function(identify){var userId=identify.userId();if(userId){this._push("setUser",{id:userId,name:identify.name()||identify.username(),data:clean(identify.traits())})}};Frontleaf.prototype.group=function(group){var groupId=group.groupId();if(groupId){this._push("setAccount",{id:groupId,name:group.proxy("traits.name"),data:clean(group.traits())})}};Frontleaf.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Frontleaf.prototype.track=function(track){var event=track.event();this._push("event",event,clean(track.properties()))};Frontleaf.prototype._push=function(command){var args=[].slice.call(arguments,1);window._fl.push(function(t){t[command].apply(command,args)})};function clean(obj){var ret={};var excludeKeys=["id","name","firstName","lastName"];var len=excludeKeys.length;for(var i=0;i<len;i++){clear(obj,excludeKeys[i])
}obj=flatten(obj);for(var key in obj){var val=obj[key];if(null==val){continue}if(is.array(val)){ret[key]=val.toString();continue}ret[key]=val}return ret}function clear(obj,key){if(obj.hasOwnProperty(key)){delete obj[key]}}function flatten(source){var output={};function step(object,prev){for(var key in object){var value=object[key];var newKey=prev?prev+" "+key:key;if(!is.array(value)&&is.object(value)){return step(value,newKey)}output[newKey]=value}}step(source);return output}},{"analytics.js-integration":81,bind:93,when:121,is:84}],33:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_gauges");var Gauges=module.exports=integration("Gauges").assumesPageview().global("_gauges").option("siteId","").tag('<script id="gauges-tracker" src="//secure.gaug.es/track.js" data-site-id="{{ siteId }}">');Gauges.prototype.initialize=function(page){window._gauges=window._gauges||[];this.load(this.ready)};Gauges.prototype.loaded=function(){return!!(window._gauges&&window._gauges.push!==Array.prototype.push)};Gauges.prototype.page=function(page){push("track")}},{"analytics.js-integration":81,"global-queue":150}],34:[function(require,module,exports){var integration=require("analytics.js-integration");var onBody=require("on-body");var GetSatisfaction=module.exports=integration("Get Satisfaction").assumesPageview().global("GSFN").option("widgetId","").tag('<script src="https://loader.engage.gsfn.us/loader.js">');GetSatisfaction.prototype.initialize=function(page){var self=this;var widget=this.options.widgetId;var div=document.createElement("div");var id=div.id="getsat-widget-"+widget;onBody(function(body){body.appendChild(div)});this.load(function(){window.GSFN.loadWidget(widget,{containerId:id});self.ready()})};GetSatisfaction.prototype.loaded=function(){return!!window.GSFN}},{"analytics.js-integration":81,"on-body":119}],35:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_gaq");var length=require("object").length;var canonical=require("canonical");var useHttps=require("use-https");var Track=require("facade").Track;var callback=require("callback");var load=require("load-script");var keys=require("object").keys;var dot=require("obj-case");var each=require("each");var type=require("type");var url=require("url");var is=require("is");var group;var user;module.exports=exports=function(analytics){analytics.addIntegration(GA);group=analytics.group();user=analytics.user()};var GA=exports.Integration=integration("Google Analytics").readyOnLoad().global("ga").global("gaplugins").global("_gaq").global("GoogleAnalyticsObject").option("anonymizeIp",false).option("classic",false).option("domain","none").option("doubleClick",false).option("enhancedLinkAttribution",false).option("ignoredReferrers",null).option("includeSearch",false).option("siteSpeedSampleRate",1).option("trackingId","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("sendUserId",false).option("metrics",{}).option("dimensions",{}).tag("library",'<script src="//www.google-analytics.com/analytics.js">').tag("double click",'<script src="//stats.g.doubleclick.net/dc.js">').tag("http",'<script src="http://www.google-analytics.com/ga.js">').tag("https",'<script src="https://ssl.google-analytics.com/ga.js">');GA.on("construct",function(integration){if(!integration.options.classic)return;integration.initialize=integration.initializeClassic;integration.loaded=integration.loadedClassic;integration.page=integration.pageClassic;integration.track=integration.trackClassic;integration.completedOrder=integration.completedOrderClassic});GA.prototype.initialize=function(){var opts=this.options;window.GoogleAnalyticsObject="ga";window.ga=window.ga||function(){window.ga.q=window.ga.q||[];window.ga.q.push(arguments)};window.ga.l=(new Date).getTime();window.ga("create",opts.trackingId,{cookieDomain:opts.domain||GA.prototype.defaults.domain,siteSpeedSampleRate:opts.siteSpeedSampleRate,allowLinker:true});if(opts.doubleClick){window.ga("require","displayfeatures")}if(opts.sendUserId&&user.id()){window.ga("set","userId",user.id())}if(opts.anonymizeIp)window.ga("set","anonymizeIp",true);var custom=metrics(user.traits(),opts);if(length(custom))window.ga("set",custom);this.load("library",this.ready)};GA.prototype.loaded=function(){return!!window.gaplugins};GA.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var pageview={};var track;this._category=category;window.ga("send","pageview",{page:path(props,this.options),title:name||props.title,location:props.url});if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{noninteraction:true})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{noninteraction:true})}};GA.prototype.track=function(track,options){var opts=options||track.options(this.name);var props=track.properties();window.ga("send","event",{eventAction:track.event(),eventCategory:props.category||this._category||"All",eventLabel:props.label,eventValue:formatValue(props.value||track.revenue()),nonInteraction:props.noninteraction||opts.noninteraction})};GA.prototype.completedOrder=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products();var props=track.properties();if(!orderId)return;if(!this.ecommerce){window.ga("require","ecommerce");this.ecommerce=true}window.ga("ecommerce:addTransaction",{affiliation:props.affiliation,shipping:track.shipping(),revenue:total,tax:track.tax(),id:orderId,currency:track.currency()});each(products,function(product){var track=new Track({properties:product});window.ga("ecommerce:addItem",{category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name(),sku:track.sku(),id:orderId,currency:track.currency()})});window.ga("ecommerce:send")};GA.prototype.initializeClassic=function(){var opts=this.options;var anonymize=opts.anonymizeIp;var db=opts.doubleClick;var domain=opts.domain;var enhanced=opts.enhancedLinkAttribution;var ignore=opts.ignoredReferrers;var sample=opts.siteSpeedSampleRate;window._gaq=window._gaq||[];push("_setAccount",opts.trackingId);push("_setAllowLinker",true);if(anonymize)push("_gat._anonymizeIp");if(domain)push("_setDomainName",domain);if(sample)push("_setSiteSpeedSampleRate",sample);if(enhanced){var protocol="https:"===document.location.protocol?"https:":"http:";var pluginUrl=protocol+"//www.google-analytics.com/plugins/ga/inpage_linkid.js";push("_require","inpage_linkid",pluginUrl)}if(ignore){if(!is.array(ignore))ignore=[ignore];each(ignore,function(domain){push("_addIgnoredRef",domain)})}if(this.options.doubleClick){this.load("double click",this.ready)}else{var name=useHttps()?"https":"http";this.load(name,this.ready)}};GA.prototype.loadedClassic=function(){return!!(window._gaq&&window._gaq.push!==Array.prototype.push)};GA.prototype.pageClassic=function(page){var opts=page.options(this.name);var category=page.category();var props=page.properties();var name=page.fullName();var track;push("_trackPageview",path(props,this.options));if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{noninteraction:true})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{noninteraction:true})}};GA.prototype.trackClassic=function(track,options){var opts=options||track.options(this.name);var props=track.properties();var revenue=track.revenue();var event=track.event();var category=this._category||props.category||"All";var label=props.label;var value=formatValue(revenue||props.value);var noninteraction=props.noninteraction||opts.noninteraction;push("_trackEvent",category,event,label,value,noninteraction)};GA.prototype.completedOrderClassic=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products()||[];var props=track.properties();var currency=track.currency();if(!orderId)return;push("_addTrans",orderId,props.affiliation,total,track.tax(),track.shipping(),track.city(),track.state(),track.country());each(products,function(product){var track=new Track({properties:product});push("_addItem",orderId,track.sku(),track.name(),track.category(),track.price(),track.quantity())});push("_set","currencyCode",currency);push("_trackTrans")};function path(properties,options){if(!properties)return;var str=properties.path;if(options.includeSearch&&properties.search)str+=properties.search;return str}function formatValue(value){if(!value||value<0)return 0;return Math.round(value)}function metrics(obj,data){var dimensions=data.dimensions;var metrics=data.metrics;var names=keys(metrics).concat(keys(dimensions));var ret={};for(var i=0;i<names.length;++i){var name=names[i];var key=metrics[name]||dimensions[name];var value=dot(obj,name)||obj[name];if(null==value)continue;ret[key]=value}return ret}},{"analytics.js-integration":81,"global-queue":150,object:157,canonical:158,"use-https":83,facade:122,callback:86,"load-script":118,"obj-case":159,each:4,type:7,url:160,is:84}],157:[function(require,module,exports){var has=Object.prototype.hasOwnProperty;exports.keys=Object.keys||function(obj){var keys=[];for(var key in obj){if(has.call(obj,key)){keys.push(key)}}return keys};exports.values=function(obj){var vals=[];for(var key in obj){if(has.call(obj,key)){vals.push(obj[key])}}return vals};exports.merge=function(a,b){for(var key in b){if(has.call(b,key)){a[key]=b[key]}}return a};exports.length=function(obj){return exports.keys(obj).length};exports.isEmpty=function(obj){return 0==exports.length(obj)}},{}],158:[function(require,module,exports){module.exports=function canonical(){var tags=document.getElementsByTagName("link");for(var i=0,tag;tag=tags[i];i++){if("canonical"==tag.getAttribute("rel"))return tag.getAttribute("href")}}},{}],159:[function(require,module,exports){var Case=require("case");var identity=function(_){return _};var cases=[identity,Case.upper,Case.lower,Case.snake,Case.pascal,Case.camel,Case.constant,Case.title,Case.capital,Case.sentence];module.exports=module.exports.find=multiple(find);module.exports.replace=function(obj,key,val){multiple(replace).apply(this,arguments);return obj};module.exports.del=function(obj,key){multiple(del).apply(this,arguments);return obj};function multiple(fn){return function(obj,key,val){var keys=key.split(".");if(keys.length===0)return;while(keys.length>1){key=keys.shift();obj=find(obj,key);if(obj===null||obj===undefined)return}key=keys.shift();return fn(obj,key,val)}}function find(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))return obj[cased]}}function del(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))delete obj[cased]}return obj}function replace(obj,key,val){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))obj[cased]=val}return obj}},{"case":161}],161:[function(require,module,exports){var cases=require("./cases");module.exports=exports=determineCase;function determineCase(string){for(var key in cases){if(key=="none")continue;var convert=cases[key];if(convert(string)==string)return key}return null}exports.add=function(name,convert){exports[name]=cases[name]=convert};for(var key in cases){exports.add(key,cases[key])}},{"./cases":162}],162:[function(require,module,exports){var camel=require("to-camel-case"),capital=require("to-capital-case"),constant=require("to-constant-case"),dot=require("to-dot-case"),none=require("to-no-case"),pascal=require("to-pascal-case"),sentence=require("to-sentence-case"),slug=require("to-slug-case"),snake=require("to-snake-case"),space=require("to-space-case"),title=require("to-title-case");exports.camel=camel;exports.pascal=pascal;exports.dot=dot;exports.slug=slug;exports.snake=snake;exports.space=space;exports.constant=constant;exports.capital=capital;exports.title=title;exports.sentence=sentence;exports.lower=function(string){return none(string).toLowerCase()};exports.upper=function(string){return none(string).toUpperCase()};exports.inverse=function(string){for(var i=0,char;char=string[i];i++){if(!/[a-z]/i.test(char))continue;var upper=char.toUpperCase();var lower=char.toLowerCase();string[i]=char==upper?lower:upper}return string};exports.none=none},{"to-camel-case":163,"to-capital-case":164,"to-constant-case":165,"to-dot-case":166,"to-no-case":115,"to-pascal-case":167,"to-sentence-case":168,"to-slug-case":169,"to-snake-case":170,"to-space-case":171,"to-title-case":172}],163:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toCamelCase;function toCamelCase(string){return toSpace(string).replace(/\s(\w)/g,function(matches,letter){return letter.toUpperCase()})}},{"to-space-case":171}],171:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}},{"to-no-case":115}],164:[function(require,module,exports){var clean=require("to-no-case");module.exports=toCapitalCase;function toCapitalCase(string){return clean(string).replace(/(^|\s)(\w)/g,function(matches,previous,letter){return previous+letter.toUpperCase()})}},{"to-no-case":115}],165:[function(require,module,exports){var snake=require("to-snake-case");module.exports=toConstantCase;function toConstantCase(string){return snake(string).toUpperCase()}},{"to-snake-case":170}],170:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}},{"to-space-case":171}],166:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toDotCase;function toDotCase(string){return toSpace(string).replace(/\s/g,".")}},{"to-space-case":171}],167:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toPascalCase;function toPascalCase(string){return toSpace(string).replace(/(?:^|\s)(\w)/g,function(matches,letter){return letter.toUpperCase()})}},{"to-space-case":171}],168:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSentenceCase;function toSentenceCase(string){return clean(string).replace(/[a-z]/i,function(letter){return letter.toUpperCase()})}},{"to-no-case":115}],169:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSlugCase;function toSlugCase(string){return toSpace(string).replace(/\s/g,"-")}},{"to-space-case":171}],172:[function(require,module,exports){var capital=require("to-capital-case"),escape=require("escape-regexp"),map=require("map"),minors=require("title-case-minors");module.exports=toTitleCase;var escaped=map(minors,escape);var minorMatcher=new RegExp("[^^]\\b("+escaped.join("|")+")\\b","ig");var colonMatcher=/:\s*(\w)/g;function toTitleCase(string){return capital(string).replace(minorMatcher,function(minor){return minor.toLowerCase()}).replace(colonMatcher,function(letter){return letter.toUpperCase()})}},{"to-capital-case":164,"escape-regexp":173,map:174,"title-case-minors":175}],173:[function(require,module,exports){module.exports=function(str){return String(str).replace(/([.*+?=^!:${}()|[\]\/\\])/g,"\\$1")}},{}],174:[function(require,module,exports){var each=require("each");module.exports=function map(obj,iterator){var arr=[];each(obj,function(o){arr.push(iterator.apply(null,arguments))});return arr}},{each:104}],175:[function(require,module,exports){module.exports=["a","an","and","as","at","but","by","en","for","from","how","if","in","neither","nor","of","on","only","onto","out","or","per","so","than","that","the","to","until","up","upon","v","v.","versus","vs","vs.","via","when","with","without","yet"]},{}],160:[function(require,module,exports){exports.parse=function(url){var a=document.createElement("a");a.href=url;return{href:a.href,host:a.host,port:a.port,hash:a.hash,hostname:a.hostname,pathname:a.pathname,protocol:a.protocol,search:a.search,query:a.search.slice(1)}};exports.isAbsolute=function(url){if(0==url.indexOf("//"))return true;if(~url.indexOf("://"))return true;return false};exports.isRelative=function(url){return!exports.isAbsolute(url)};exports.isCrossDomain=function(url){url=exports.parse(url);return url.hostname!=location.hostname||url.port!=location.port||url.protocol!=location.protocol}},{}],36:[function(require,module,exports){var push=require("global-queue")("dataLayer",{wrap:false});var integration=require("analytics.js-integration");var GTM=module.exports=integration("Google Tag Manager").assumesPageview().global("dataLayer").global("google_tag_manager").option("containerId","").option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//www.googletagmanager.com/gtm.js?id={{ containerId }}&l=dataLayer">');GTM.prototype.initialize=function(){push({"gtm.start":+new Date,event:"gtm.js"});this.load(this.ready)};GTM.prototype.loaded=function(){return!!(window.dataLayer&&[].push!=window.dataLayer.push)};GTM.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;var track;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};GTM.prototype.track=function(track){var props=track.properties();props.event=track.event();push(props)}},{"global-queue":150,"analytics.js-integration":81}],37:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var Track=require("facade").Track;var callback=require("callback");var load=require("load-script");var onBody=require("on-body");var each=require("each");var GoSquared=module.exports=integration("GoSquared").assumesPageview().global("_gs").option("siteToken","").option("anonymizeIP",false).option("cookieDomain",null).option("useCookies",true).option("trackHash",false).option("trackLocal",false).option("trackParams",true).tag('<script src="//d1l6p2sc9645hc.cloudfront.net/tracker.js">');GoSquared.prototype.initialize=function(page){var self=this;var options=this.options;var user=this.analytics.user();push(options.siteToken);each(options,function(name,value){if("siteToken"==name)return;if(null==value)return;push("set",name,value)});self.identify(new Identify({traits:user.traits(),userId:user.id()}));self.load(this.ready)};GoSquared.prototype.loaded=function(){return!!(window._gs&&window._gs.v)};GoSquared.prototype.page=function(page){var props=page.properties();var name=page.fullName();push("track",props.path,name||props.title)};GoSquared.prototype.identify=function(identify){var traits=identify.traits({userId:"userID"});var username=identify.username();var email=identify.email();var id=identify.userId();if(id)push("set","visitorID",id);var name=email||username||id;if(name)push("set","visitorName",name);push("set","visitor",traits)};GoSquared.prototype.track=function(track){push("event",track.event(),track.properties())};GoSquared.prototype.completedOrder=function(track){var products=track.products();var items=[];each(products,function(product){var track=new Track({properties:product});items.push({category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name()})});push("transaction",track.orderId(),{revenue:track.total(),track:true},items)};function push(){var _gs=window._gs=window._gs||function(){(_gs.q=_gs.q||[]).push(arguments)};_gs.apply(null,arguments)}},{"analytics.js-integration":81,facade:122,callback:86,"load-script":118,"on-body":119,each:4}],38:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Heap=module.exports=integration("Heap").assumesPageview().global("heap").global("_heapid").option("apiKey","").tag('<script src="//d36lvucg9kzous.cloudfront.net">');Heap.prototype.initialize=function(page){window.heap=window.heap||[];window.heap.load=function(a){window._heapid=a;var d=function(a){return function(){window.heap.push([a].concat(Array.prototype.slice.call(arguments,0)))}},e=["identify","track"];for(var f=0;f<e.length;f++)window.heap[e[f]]=d(e[f])};window.heap.load(this.options.apiKey);this.load(this.ready)};Heap.prototype.loaded=function(){return window.heap&&window.heap.appid};Heap.prototype.identify=function(identify){var traits=identify.traits();var username=identify.username();var id=identify.userId();var handle=username||id;if(handle)traits.handle=handle;delete traits.username;window.heap.identify(traits)};Heap.prototype.track=function(track){window.heap.track(track.event(),track.properties())}},{"analytics.js-integration":81,alias:155}],39:[function(require,module,exports){var integration=require("analytics.js-integration");var Hellobar=module.exports=integration("Hello Bar").assumesPageview().global("_hbq").option("apiKey","").tag('<script src="//s3.amazonaws.com/scripts.hellobar.com/{{ apiKey }}.js">');Hellobar.prototype.initialize=function(page){window._hbq=window._hbq||[];this.load(this.ready)};Hellobar.prototype.loaded=function(){return!!(window._hbq&&window._hbq.push!==Array.prototype.push)}},{"analytics.js-integration":81}],40:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var HitTail=module.exports=integration("HitTail").assumesPageview().global("htk").option("siteId","").tag('<script src="//{{ siteId }}.hittail.com/mlt.js">');HitTail.prototype.initialize=function(page){this.load(this.ready)};HitTail.prototype.loaded=function(){return is.fn(window.htk)}},{"analytics.js-integration":81,is:84}],41:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_hsq");var convert=require("convert-dates");var HubSpot=module.exports=integration("HubSpot").assumesPageview().global("_hsq").option("portalId",null).tag('<script id="hs-analytics" src="https://js.hs-analytics.net/analytics/{{ cache }}/{{ portalId }}.js">');HubSpot.prototype.initialize=function(page){window._hsq=[];var cache=Math.ceil(new Date/3e5)*3e5;this.load({cache:cache},this.ready)};HubSpot.prototype.loaded=function(){return!!(window._hsq&&window._hsq.push!==Array.prototype.push)};HubSpot.prototype.page=function(page){push("_trackPageview")};HubSpot.prototype.identify=function(identify){if(!identify.email())return;var traits=identify.traits();traits=convertDates(traits);push("identify",traits)};HubSpot.prototype.track=function(track){var props=track.properties();props=convertDates(props);push("trackEvent",track.event(),props)};function convertDates(properties){return convert(properties,function(date){return date.getTime()})}},{"analytics.js-integration":81,"global-queue":150,"convert-dates":156}],42:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Improvely=module.exports=integration("Improvely").assumesPageview().global("_improvely").global("improvely").option("domain","").option("projectId",null).tag('<script src="//{{ domain }}.iljmp.com/improvely.js">');Improvely.prototype.initialize=function(page){window._improvely=[];window.improvely={init:function(e,t){window._improvely.push(["init",e,t])},goal:function(e){window._improvely.push(["goal",e])},label:function(e){window._improvely.push(["label",e])}};var domain=this.options.domain;var id=this.options.projectId;window.improvely.init(domain,id);this.load(this.ready)};Improvely.prototype.loaded=function(){return!!(window.improvely&&window.improvely.identify)};Improvely.prototype.identify=function(identify){var id=identify.userId();if(id)window.improvely.label(id)};Improvely.prototype.track=function(track){var props=track.properties({revenue:"amount"});props.type=track.event();window.improvely.goal(props)}},{"analytics.js-integration":81,alias:155}],43:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_iva");var Track=require("facade").Track;var is=require("is");var has=Object.prototype.hasOwnProperty;var InsideVault=module.exports=integration("InsideVault").global("_iva").option("clientId","").option("domain","").tag('<script src="//analytics.staticiv.com/iva.js">').mapping("events");InsideVault.prototype.initialize=function(page){var domain=this.options.domain;window._iva=window._iva||[];push("setClientId",this.options.clientId);if(domain)push("setDomain",domain);this.load(this.ready)};InsideVault.prototype.loaded=function(){return!!(window._iva&&window._iva.push!==Array.prototype.push)};InsideVault.prototype.page=function(page){push("trackEvent","click")};InsideVault.prototype.track=function(track){var user=this.analytics.user();var events=this.options.events;var event=track.event();var value=track.revenue()||track.value()||0;var eventId=track.orderId()||user.id()||"";if(!has.call(events,event))return;event=events[event];if(event!="sale"){push("trackEvent",event,value,eventId)}}},{"analytics.js-integration":81,"global-queue":150,facade:122,is:84}],44:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("__insp");var alias=require("alias");var clone=require("clone");var Inspectlet=module.exports=integration("Inspectlet").assumesPageview().global("__insp").global("__insp_").option("wid","").tag('<script src="//www.inspectlet.com/inspectlet.js">');Inspectlet.prototype.initialize=function(page){push("wid",this.options.wid);this.load(this.ready)};Inspectlet.prototype.loaded=function(){return!!window.__insp_};Inspectlet.prototype.identify=function(identify){var traits=identify.traits({id:"userid"});push("tagSession",traits)};Inspectlet.prototype.track=function(track){push("tagSession",track.event())}},{"analytics.js-integration":81,"global-queue":150,alias:155,clone:154}],45:[function(require,module,exports){var integration=require("analytics.js-integration");var convertDates=require("convert-dates");var defaults=require("defaults");var isEmail=require("is-email");var load=require("load-script");var empty=require("is-empty");var alias=require("alias");var each=require("each");var when=require("when");var is=require("is");var Intercom=module.exports=integration("Intercom").assumesPageview().global("Intercom").option("activator","#IntercomDefaultWidget").option("appId","").option("inbox",false).tag('<script src="https://static.intercomcdn.com/intercom.v1.js">');Intercom.prototype.initialize=function(page){var self=this;this.load(function(){when(function(){return self.loaded()},self.ready)})};Intercom.prototype.loaded=function(){return is.fn(window.Intercom)};Intercom.prototype.page=function(page){window.Intercom("update")};Intercom.prototype.identify=function(identify){var traits=identify.traits({userId:"user_id"});var activator=this.options.activator;var opts=identify.options(this.name);var companyCreated=identify.companyCreated();var created=identify.created();var email=identify.email();var name=identify.name();var id=identify.userId();var group=this.analytics.group();if(!id&&!traits.email)return;traits.app_id=this.options.appId;if(null!=traits.company&&!is.object(traits.company))delete traits.company;if(traits.company)defaults(traits.company,group.traits());if(name)traits.name=name;if(traits.company&&companyCreated)traits.company.created=companyCreated;if(created)traits.created=created;traits=convertDates(traits,formatDate);traits=alias(traits,{created:"created_at"});if(traits.company)traits.company=alias(traits.company,{created:"created_at"});if(opts.increments)traits.increments=opts.increments;if(opts.userHash)traits.user_hash=opts.userHash;if(opts.user_hash)traits.user_hash=opts.user_hash;if("#IntercomDefaultWidget"!=activator){traits.widget={activator:activator}}var method=this._id!==id?"boot":"update";this._id=id;window.Intercom(method,traits)};Intercom.prototype.group=function(group){var props=group.properties();var id=group.groupId();if(id)props.id=id;window.Intercom("update",{company:props})};Intercom.prototype.track=function(track){window.Intercom("trackEvent",track.event(),track.properties())};function formatDate(date){return Math.floor(date/1e3)}},{"analytics.js-integration":81,"convert-dates":156,defaults:149,"is-email":145,"load-script":118,"is-empty":116,alias:155,each:4,when:121,is:84}],46:[function(require,module,exports){var integration=require("analytics.js-integration");var Keen=module.exports=integration("Keen IO").global("Keen").option("projectId","").option("readKey","").option("writeKey","").option("ipAddon",false).option("uaAddon",false).option("urlAddon",false).option("referrerAddon",false).option("trackNamedPages",true).option("trackAllPages",false).option("trackCategorizedPages",true).tag('<script src="//d26b395fwzu5fz.cloudfront.net/3.0.7/{{ lib }}.min.js">');Keen.prototype.initialize=function(){var options=this.options;!function(a,b){if(void 0===b[a]){b["_"+a]={},b[a]=function(c){b["_"+a].clients=b["_"+a].clients||{},b["_"+a].clients[c.projectId]=this,this._config=c},b[a].ready=function(c){b["_"+a].ready=b["_"+a].ready||[],b["_"+a].ready.push(c)};for(var c=["addEvent","setGlobalProperties","trackExternalLink","on"],d=0;d<c.length;d++){var e=c[d],f=function(a){return function(){return this["_"+a]=this["_"+a]||[],this["_"+a].push(arguments),this}};b[a].prototype[e]=f(e)}}}("Keen",window);this.client=new window.Keen({projectId:options.projectId,writeKey:options.writeKey,readKey:options.readKey});var lib=this.options.readKey?"keen":"keen-tracker";this.load({lib:lib},this.ready)};Keen.prototype.loaded=function(){return!!(window.Keen&&window.Keen.prototype.configure)};Keen.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Keen.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var user={};var options=this.options;if(id)user.userId=id;if(traits)user.traits=traits;var props={user:user};var addons=[];if(options.ipAddon){addons.push({name:"keen:ip_to_geo",input:{ip:"ip_address"},output:"ip_geo_info"});props.ip_address="${keen.ip}"}if(options.uaAddon){addons.push({name:"keen:ua_parser",input:{ua_string:"user_agent"},output:"parsed_user_agent"});props.user_agent="${keen.user_agent}"}if(options.urlAddon){addons.push({name:"keen:url_parser",input:{url:"page_url"},output:"parsed_page_url"});props.page_url=document.location.href}if(options.referrerAddon){addons.push({name:"keen:referrer_parser",input:{referrer_url:"referrer_url",page_url:"page_url"},output:"referrer_info"});props.referrer_url=document.referrer;props.page_url=document.location.href}props.keen={timestamp:identify.timestamp(),addons:addons};this.client.setGlobalProperties(function(){return props})};Keen.prototype.track=function(track){this.client.addEvent(track.event(),track.properties())}},{"analytics.js-integration":81}],47:[function(require,module,exports){var integration=require("analytics.js-integration");var indexof=require("indexof");var is=require("is");var Kenshoo=module.exports=integration("Kenshoo").global("k_trackevent").option("cid","").option("subdomain","").option("events",[]).tag('<script src="//{{ subdomain }}.xg4ken.com/media/getpx.php?cid={{ cid }}">');Kenshoo.prototype.initialize=function(page){this.load(this.ready)};Kenshoo.prototype.loaded=function(){return is.fn(window.k_trackevent)};Kenshoo.prototype.track=function(track){var events=this.options.events;var traits=track.traits();var event=track.event();var revenue=track.revenue()||0;if(!~indexof(events,event))return;var params=["id="+this.options.cid,"type=conv","val="+revenue,"orderId="+track.orderId(),"promoCode="+track.coupon(),"valueCurrency="+track.currency(),"GCID=","kw=","product="];
window.k_trackevent(params,this.options.subdomain)}},{"analytics.js-integration":81,indexof:107,is:84}],48:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_kmq");var Track=require("facade").Track;var alias=require("alias");var Batch=require("batch");var each=require("each");var is=require("is");var KISSmetrics=module.exports=integration("KISSmetrics").assumesPageview().global("_kmq").global("KM").global("_kmil").option("apiKey","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("prefixProperties",true).tag("useless",'<script src="//i.kissmetrics.com/i.js">').tag("library",'<script src="//doug1izaerwt3.cloudfront.net/{{ apiKey }}.1.js">');exports.isMobile=navigator.userAgent.match(/Android/i)||navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/iPhone|iPod/i)||navigator.userAgent.match(/iPad/i)||navigator.userAgent.match(/Opera Mini/i)||navigator.userAgent.match(/IEMobile/i);KISSmetrics.prototype.initialize=function(page){var self=this;window._kmq=[];if(exports.isMobile)push("set",{"Mobile Session":"Yes"});var batch=new Batch;batch.push(function(done){self.load("useless",done)});batch.push(function(done){self.load("library",done)});batch.end(function(){self.trackPage(page);self.ready()})};KISSmetrics.prototype.loaded=function(){return is.object(window.KM)};KISSmetrics.prototype.page=function(page){if(!window.KM_SKIP_PAGE_VIEW)window.KM.pageView();this.trackPage(page)};KISSmetrics.prototype.trackPage=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};KISSmetrics.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();if(id)push("identify",id);if(traits)push("set",traits)};KISSmetrics.prototype.track=function(track){var mapping={revenue:"Billing Amount"};var event=track.event();var properties=track.properties(mapping);if(this.options.prefixProperties)properties=prefix(event,properties);push("record",event,properties)};KISSmetrics.prototype.alias=function(alias){push("alias",alias.to(),alias.from())};KISSmetrics.prototype.completedOrder=function(track){var products=track.products();var event=track.event();push("record",event,prefix(event,track.properties()));window._kmq.push(function(){var km=window.KM;each(products,function(product,i){var temp=new Track({event:event,properties:product});var item=prefix(event,product);item._t=km.ts()+i;item._d=1;km.set(item)})})};function prefix(event,properties){var prefixed={};each(properties,function(key,val){if(key==="Billing Amount"){prefixed[key]=val}else{prefixed[event+" - "+key]=val}});return prefixed}},{"analytics.js-integration":81,"global-queue":150,facade:122,alias:155,batch:176,each:4,is:84}],176:[function(require,module,exports){try{var EventEmitter=require("events").EventEmitter}catch(err){var Emitter=require("emitter")}function noop(){}module.exports=Batch;function Batch(){if(!(this instanceof Batch))return new Batch;this.fns=[];this.concurrency(Infinity);this.throws(true);for(var i=0,len=arguments.length;i<len;++i){this.push(arguments[i])}}if(EventEmitter){Batch.prototype.__proto__=EventEmitter.prototype}else{Emitter(Batch.prototype)}Batch.prototype.concurrency=function(n){this.n=n;return this};Batch.prototype.push=function(fn){this.fns.push(fn);return this};Batch.prototype.throws=function(throws){this.e=!!throws;return this};Batch.prototype.end=function(cb){var self=this,total=this.fns.length,pending=total,results=[],errors=[],cb=cb||noop,fns=this.fns,max=this.n,throws=this.e,index=0,done;if(!fns.length)return cb(null,results);function next(){var i=index++;var fn=fns[i];if(!fn)return;var start=new Date;try{fn(callback)}catch(err){callback(err)}function callback(err,res){if(done)return;if(err&&throws)return done=true,cb(err);var complete=total-pending+1;var end=new Date;results[i]=res;errors[i]=err;self.emit("progress",{index:i,value:res,error:err,pending:pending,total:total,complete:complete,percent:complete/total*100|0,start:start,end:end,duration:end-start});if(--pending)next();else if(!throws)cb(errors,results);else cb(null,results)}}for(var i=0;i<fns.length;i++){if(i==max)break;next()}return this}},{emitter:177}],177:[function(require,module,exports){module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}on.fn=fn;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var cb;for(var i=0;i<callbacks.length;i++){cb=callbacks[i];if(cb===fn||cb.fn===fn){callbacks.splice(i,1);break}}return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{}],49:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_learnq");var tick=require("next-tick");var alias=require("alias");var aliases={id:"$id",email:"$email",firstName:"$first_name",lastName:"$last_name",phone:"$phone_number",title:"$title"};var Klaviyo=module.exports=integration("Klaviyo").assumesPageview().global("_learnq").option("apiKey","").tag('<script src="//a.klaviyo.com/media/js/learnmarklet.js">');Klaviyo.prototype.initialize=function(page){var self=this;push("account",this.options.apiKey);this.load(function(){tick(self.ready)})};Klaviyo.prototype.loaded=function(){return!!(window._learnq&&window._learnq.push!==Array.prototype.push)};Klaviyo.prototype.identify=function(identify){var traits=identify.traits(aliases);if(!traits.$id&&!traits.$email)return;push("identify",traits)};Klaviyo.prototype.group=function(group){var props=group.properties();if(!props.name)return;push("identify",{$organization:props.name})};Klaviyo.prototype.track=function(track){push("track",track.event(),track.properties({revenue:"$value"}))}},{"analytics.js-integration":81,"global-queue":150,"next-tick":95,alias:155}],50:[function(require,module,exports){var integration=require("analytics.js-integration");var LeadLander=module.exports=integration("LeadLander").assumesPageview().global("llactid").global("trackalyzer").option("accountId",null).tag('<script src="http://t6.trackalyzer.com/trackalyze-nodoc.js">');LeadLander.prototype.initialize=function(page){window.llactid=this.options.accountId;this.load(this.ready)};LeadLander.prototype.loaded=function(){return!!window.trackalyzer}},{"analytics.js-integration":81}],51:[function(require,module,exports){var integration=require("analytics.js-integration");var clone=require("clone");var each=require("each");var Identify=require("facade").Identify;var when=require("when");var LiveChat=module.exports=integration("LiveChat").assumesPageview().global("__lc").global("__lc_inited").global("LC_API").global("LC_Invite").option("group",0).option("license","").tag('<script src="//cdn.livechatinc.com/tracking.js">');LiveChat.prototype.initialize=function(page){var self=this;var user=this.analytics.user();var identify=new Identify({userId:user.id(),traits:user.traits()});window.__lc=clone(this.options);window.__lc.visitor={name:identify.name(),email:identify.email()};this.load(function(){when(function(){return self.loaded()},self.ready)})};LiveChat.prototype.loaded=function(){return!!(window.LC_API&&window.LC_Invite)};LiveChat.prototype.identify=function(identify){var traits=identify.traits({userId:"User ID"});window.LC_API.set_custom_variables(convert(traits))};function convert(traits){var arr=[];each(traits,function(key,value){arr.push({name:key,value:value})});return arr}},{"analytics.js-integration":81,clone:154,each:4,facade:122,when:121}],52:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var useHttps=require("use-https");var LuckyOrange=module.exports=integration("Lucky Orange").assumesPageview().global("_loq").global("__wtw_watcher_added").global("__wtw_lucky_site_id").global("__wtw_lucky_is_segment_io").global("__wtw_custom_user_data").option("siteId",null).tag("http",'<script src="http://www.luckyorange.com/w.js?{{ cache }}">').tag("https",'<script src="https://ssl.luckyorange.com/w.js?{{ cache }}">');LuckyOrange.prototype.initialize=function(page){var user=this.analytics.user();window._loq||(window._loq=[]);window.__wtw_lucky_site_id=this.options.siteId;this.identify(new Identify({traits:user.traits(),userId:user.id()}));var cache=Math.floor((new Date).getTime()/6e4);var name=useHttps()?"https":"http";this.load(name,{cache:cache},this.ready)};LuckyOrange.prototype.loaded=function(){return!!window.__wtw_watcher_added};LuckyOrange.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var name=identify.name();if(name)traits.name=name;if(email)traits.email=email;window.__wtw_custom_user_data=traits}},{"analytics.js-integration":81,facade:122,"use-https":83}],53:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Lytics=module.exports=integration("Lytics").global("jstag").option("cid","").option("cookie","seerid").option("delay",2e3).option("sessionTimeout",1800).option("url","//c.lytics.io").tag('<script src="//c.lytics.io/static/io.min.js">');var aliases={sessionTimeout:"sessecs"};Lytics.prototype.initialize=function(page){var options=alias(this.options,aliases);window.jstag=function(){var t={_q:[],_c:options,ts:(new Date).getTime()};t.send=function(){this._q.push(["ready","send",Array.prototype.slice.call(arguments)]);return this};return t}();this.load(this.ready)};Lytics.prototype.loaded=function(){return!!(window.jstag&&window.jstag.bind)};Lytics.prototype.page=function(page){window.jstag.send(page.properties())};Lytics.prototype.identify=function(identify){var traits=identify.traits({userId:"_uid"});window.jstag.send(traits)};Lytics.prototype.track=function(track){var props=track.properties();props._e=track.event();window.jstag.send(props)}},{"analytics.js-integration":81,alias:155}],54:[function(require,module,exports){var alias=require("alias");var clone=require("clone");var dates=require("convert-dates");var integration=require("analytics.js-integration");var is=require("is");var iso=require("to-iso-string");var indexof=require("indexof");var del=require("obj-case").del;var some=require("some");var Mixpanel=module.exports=integration("Mixpanel").global("mixpanel").option("increments",[]).option("cookieName","").option("nameTag",true).option("pageview",false).option("people",false).option("token","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//cdn.mxpnl.com/libs/mixpanel-2.2.min.js">');var optionsAliases={cookieName:"cookie_name"};Mixpanel.prototype.initialize=function(){(function(c,a){window.mixpanel=a;var b,d,h,e;a._i=[];a.init=function(b,c,f){function d(a,b){var c=b.split(".");2==c.length&&(a=a[c[0]],b=c[1]);a[b]=function(){a.push([b].concat(Array.prototype.slice.call(arguments,0)))}}var g=a;"undefined"!==typeof f?g=a[f]=[]:f="mixpanel";g.people=g.people||[];h=["disable","track","track_pageview","track_links","track_forms","register","register_once","unregister","identify","alias","name_tag","set_config","people.set","people.increment","people.track_charge","people.append"];for(e=0;e<h.length;e++)d(g,h[e]);a._i.push([b,c,f])};a.__SV=1.2})(document,window.mixpanel||[]);this.options.increments=lowercase(this.options.increments);var options=alias(this.options,optionsAliases);window.mixpanel.init(options.token,options);this.load(this.ready)};Mixpanel.prototype.loaded=function(){return!!(window.mixpanel&&window.mixpanel.config)};Mixpanel.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};var traitAliases={created:"$created",email:"$email",firstName:"$first_name",lastName:"$last_name",lastSeen:"$last_seen",name:"$name",username:"$username",phone:"$phone"};Mixpanel.prototype.identify=function(identify){var username=identify.username();var email=identify.email();var id=identify.userId();if(id)window.mixpanel.identify(id);var nametag=email||username||id;if(nametag)window.mixpanel.name_tag(nametag);var traits=identify.traits(traitAliases);if(traits.$created)del(traits,"createdAt");window.mixpanel.register(dates(traits,iso));if(this.options.people)window.mixpanel.people.set(traits)};Mixpanel.prototype.track=function(track){var increments=this.options.increments;var increment=track.event().toLowerCase();var people=this.options.people;var props=track.properties();var revenue=track.revenue();delete props.distinct_id;delete props.ip;delete props.mp_name_tag;delete props.mp_note;delete props.token;for(var key in props){var val=props[key];if(is.array(val)&&some(val,is.object))props[key]=val.length}if(people&&~indexof(increments,increment)){window.mixpanel.people.increment(track.event());window.mixpanel.people.set("Last "+track.event(),new Date)}props=dates(props,iso);window.mixpanel.track(track.event(),props);if(revenue&&people){window.mixpanel.people.track_charge(revenue)}};Mixpanel.prototype.alias=function(alias){var mp=window.mixpanel;var to=alias.to();if(mp.get_distinct_id&&mp.get_distinct_id()===to)return;if(mp.get_property&&mp.get_property("$people_distinct_id")===to)return;mp.alias(to,alias.from())};function lowercase(arr){var ret=new Array(arr.length);for(var i=0;i<arr.length;++i){ret[i]=String(arr[i]).toLowerCase()}return ret}},{alias:155,clone:154,"convert-dates":156,"analytics.js-integration":81,is:84,"to-iso-string":153,indexof:107,"obj-case":159,some:178}],178:[function(require,module,exports){var some=[].some;module.exports=function(arr,fn){if(some)return some.call(arr,fn);for(var i=0,l=arr.length;i<l;++i){if(fn(arr[i],i))return true}return false}},{}],55:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var is=require("is");var Mojn=module.exports=integration("Mojn").option("customerCode","").global("_mojnTrack").tag('<script src="https://track.idtargeting.com/{{ customerCode }}/track.js">');Mojn.prototype.initialize=function(){window._mojnTrack=window._mojnTrack||[];window._mojnTrack.push({cid:this.options.customerCode});var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Mojn.prototype.loaded=function(){return is.object(window._mojnTrack)};Mojn.prototype.identify=function(identify){var email=identify.email();if(!email)return;var img=new Image;img.src="//matcher.idtargeting.com/analytics.gif?cid="+this.options.customerCode+"&_mjnctid="+email;img.width=1;img.height=1;return img};Mojn.prototype.track=function(track){var properties=track.properties();var revenue=properties.revenue;var currency=properties.currency||"";var conv=currency+revenue;if(!revenue)return;window._mojnTrack.push({conv:conv});return conv}},{"analytics.js-integration":81,bind:93,when:121,is:84}],56:[function(require,module,exports){var push=require("global-queue")("_mfq");var integration=require("analytics.js-integration");var each=require("each");var Mouseflow=module.exports=integration("Mouseflow").assumesPageview().global("mouseflow").global("_mfq").option("apiKey","").option("mouseflowHtmlDelay",0).tag('<script src="//cdn.mouseflow.com/projects/{{ apiKey }}.js">');Mouseflow.prototype.initialize=function(page){window.mouseflowHtmlDelay=this.options.mouseflowHtmlDelay;this.load(this.ready)};Mouseflow.prototype.loaded=function(){return!!window.mouseflow};Mouseflow.prototype.page=function(page){if(!window.mouseflow)return;if("function"!=typeof mouseflow.newPageView)return;mouseflow.newPageView()};Mouseflow.prototype.identify=function(identify){set(identify.traits())};Mouseflow.prototype.track=function(track){var props=track.properties();props.event=track.event();set(props)};function set(obj){each(obj,function(key,value){push("setVariable",key,value)})}},{"global-queue":150,"analytics.js-integration":81,each:4}],57:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var each=require("each");var is=require("is");var MouseStats=module.exports=integration("MouseStats").assumesPageview().global("msaa").global("MouseStatsVisitorPlaybacks").option("accountNumber","").tag("http",'<script src="http://www2.mousestats.com/js/{{ path }}.js?{{ cache }}">').tag("https",'<script src="https://ssl.mousestats.com/js/{{ path }}.js?{{ cache }}">');MouseStats.prototype.initialize=function(page){var number=this.options.accountNumber;var path=number.slice(0,1)+"/"+number.slice(1,2)+"/"+number;var cache=Math.floor((new Date).getTime()/6e4);var name=useHttps()?"https":"http";this.load(name,{path:path,cache:cache},this.ready)};MouseStats.prototype.loaded=function(){return is.array(window.MouseStatsVisitorPlaybacks)};MouseStats.prototype.identify=function(identify){each(identify.traits(),function(key,value){window.MouseStatsVisitorPlaybacks.customVariable(key,value)})}},{"analytics.js-integration":81,"use-https":83,each:4,is:84}],58:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("__nls");var Navilytics=module.exports=integration("Navilytics").assumesPageview().global("__nls").option("memberId","").option("projectId","").tag('<script src="//www.navilytics.com/nls.js?mid={{ memberId }}&pid={{ projectId }}">');Navilytics.prototype.initialize=function(page){window.__nls=window.__nls||[];this.load(this.ready)};Navilytics.prototype.loaded=function(){return!!(window.__nls&&[].push!=window.__nls.push)};Navilytics.prototype.track=function(track){push("tagRecording",track.event())}},{"analytics.js-integration":81,"global-queue":150}],59:[function(require,module,exports){var integration=require("analytics.js-integration");var https=require("use-https");var tick=require("next-tick");var Olark=module.exports=integration("Olark").assumesPageview().global("olark").option("identify",true).option("page",true).option("siteId","").option("groupId","").option("track",false);Olark.prototype.initialize=function(page){var self=this;this.load(function(){tick(self.ready)});var groupId=this.options.groupId;if(groupId)api("chat.setOperatorGroup",{group:groupId});api("box.onExpand",function(){self._open=true});api("box.onShrink",function(){self._open=false})};Olark.prototype.loaded=function(){return!!window.olark};Olark.prototype.load=function(callback){var el=document.getElementById("olark");window.olark||function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i," onl"+'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()}({loader:"static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});window.olark.identify(this.options.siteId);callback()};Olark.prototype.page=function(page){if(!this.options.page)return;var props=page.properties();var name=page.fullName();if(!name&&!props.url)return;name=name?name+" page":props.url;this.notify("looking at "+name)};Olark.prototype.identify=function(identify){if(!this.options.identify)return;var username=identify.username();var traits=identify.traits();var id=identify.userId();var email=identify.email();var phone=identify.phone();var name=identify.name()||identify.firstName();if(traits)api("visitor.updateCustomFields",traits);if(email)api("visitor.updateEmailAddress",{emailAddress:email});if(phone)api("visitor.updatePhoneNumber",{phoneNumber:phone});if(name)api("visitor.updateFullName",{fullName:name});var nickname=name||email||username||id;if(name&&email)nickname+=" ("+email+")";if(nickname)api("chat.updateVisitorNickname",{snippet:nickname})};Olark.prototype.track=function(track){if(!this.options.track)return;this.notify('visitor triggered "'+track.event()+'"')};Olark.prototype.notify=function(message){if(!this._open)return;message=message.toLowerCase();api("visitor.getDetails",function(data){if(!data||!data.isConversing)return;api("chat.sendNotificationToOperator",{body:message})})};function api(action,value){window.olark("api."+action,value)}},{"analytics.js-integration":81,"use-https":83,"next-tick":95}],60:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("optimizely");var callback=require("callback");var tick=require("next-tick");var bind=require("bind");var each=require("each");var Optimizely=module.exports=integration("Optimizely").option("variations",true).option("trackNamedPages",true).option("trackCategorizedPages",true);Optimizely.prototype.initialize=function(){if(this.options.variations){var self=this;tick(function(){self.replay()})}this.ready()};Optimizely.prototype.track=function(track){var props=track.properties();if(props.revenue)props.revenue*=100;push("trackEvent",track.event(),props)};Optimizely.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Optimizely.prototype.replay=function(){if(!window.optimizely)return;var data=window.optimizely.data;if(!data)return;var experiments=data.experiments;var map=data.state.variationNamesMap;var traits={};each(map,function(experimentId,variation){var experiment=experiments[experimentId].name;traits["Experiment: "+experiment]=variation});this.analytics.identify(traits)}},{"analytics.js-integration":81,"global-queue":150,callback:86,"next-tick":95,bind:93,each:4}],61:[function(require,module,exports){var integration=require("analytics.js-integration");var PerfectAudience=module.exports=integration("Perfect Audience").assumesPageview().global("_pa").option("siteId","").tag('<script src="//tag.perfectaudience.com/serve/{{ siteId }}.js">');PerfectAudience.prototype.initialize=function(page){window._pa=window._pa||{};this.load(this.ready)};PerfectAudience.prototype.loaded=function(){return!!(window._pa&&window._pa.track)};PerfectAudience.prototype.track=function(track){window._pa.track(track.event(),track.properties())}},{"analytics.js-integration":81}],62:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_prum");var date=require("load-date");var Pingdom=module.exports=integration("Pingdom").assumesPageview().global("_prum").global("PRUM_EPISODES").option("id","").tag('<script src="//rum-static.pingdom.net/prum.min.js">');Pingdom.prototype.initialize=function(page){window._prum=window._prum||[];push("id",this.options.id);push("mark","firstbyte",date.getTime());var self=this;this.load(this.ready)};Pingdom.prototype.loaded=function(){return!!(window._prum&&window._prum.push!==Array.prototype.push)}},{"analytics.js-integration":81,"global-queue":150,"load-date":151}],63:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_paq");var each=require("each");var Piwik=module.exports=integration("Piwik").global("_paq").option("url",null).option("siteId","").mapping("goals").tag('<script src="{{ url }}/piwik.js">');Piwik.prototype.initialize=function(){window._paq=window._paq||[];push("setSiteId",this.options.siteId);push("setTrackerUrl",this.options.url+"/piwik.php");push("enableLinkTracking");this.load(this.ready)};Piwik.prototype.loaded=function(){return!!(window._paq&&window._paq.push!=[].push)};Piwik.prototype.page=function(page){push("trackPageView")};Piwik.prototype.track=function(track){var goals=this.goals(track.event());var revenue=track.revenue()||0;each(goals,function(goal){push("trackGoal",goal,revenue)})}},{"analytics.js-integration":81,"global-queue":150,each:4}],64:[function(require,module,exports){var integration=require("analytics.js-integration");var convertDates=require("convert-dates");var push=require("global-queue")("_lnq");var alias=require("alias");var Preact=module.exports=integration("Preact").assumesPageview().global("_lnq").option("projectCode","").tag('<script src="//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js">');Preact.prototype.initialize=function(page){window._lnq=window._lnq||[];push("_setCode",this.options.projectCode);this.load(this.ready)};Preact.prototype.loaded=function(){return!!(window._lnq&&window._lnq.push!==Array.prototype.push)};Preact.prototype.identify=function(identify){if(!identify.userId())return;var traits=identify.traits({created:"created_at"});traits=convertDates(traits,convertDate);push("_setPersonData",{name:identify.name(),email:identify.email(),uid:identify.userId(),properties:traits})};Preact.prototype.group=function(group){if(!group.groupId())return;push("_setAccount",group.traits())};Preact.prototype.track=function(track){var props=track.properties();var revenue=track.revenue();var event=track.event();var special={name:event};if(revenue){special.revenue=revenue*100;delete props.revenue}if(props.note){special.note=props.note;delete props.note}push("_logEvent",special,props)};function convertDate(date){return Math.floor(date/1e3)}},{"analytics.js-integration":81,"convert-dates":156,"global-queue":150,alias:155}],65:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_kiq");var Facade=require("facade");var Identify=Facade.Identify;var bind=require("bind");var when=require("when");var Qualaroo=module.exports=integration("Qualaroo").assumesPageview().global("_kiq").option("customerId","").option("siteToken","").option("track",false).tag('<script src="//s3.amazonaws.com/ki.js/{{ customerId }}/{{ siteToken }}.js">');Qualaroo.prototype.initialize=function(page){window._kiq=window._kiq||[];var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Qualaroo.prototype.loaded=function(){return!!(window._kiq&&window._kiq.push!==Array.prototype.push)};Qualaroo.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var email=identify.email();if(email)id=email;if(id)push("identify",id);if(traits)push("set",traits)};Qualaroo.prototype.track=function(track){if(!this.options.track)return;var event=track.event();var traits={};traits["Triggered: "+event]=true;this.identify(new Identify({traits:traits}))}},{"analytics.js-integration":81,"global-queue":150,facade:122,bind:93,when:121}],66:[function(require,module,exports){var push=require("global-queue")("_qevents",{wrap:false});var integration=require("analytics.js-integration");var useHttps=require("use-https");var Quantcast=module.exports=integration("Quantcast").assumesPageview().global("_qevents").global("__qc").option("pCode",null).option("advertise",false).tag("http",'<script src="http://edge.quantserve.com/quant.js">').tag("https",'<script src="https://secure.quantserve.com/quant.js">');Quantcast.prototype.initialize=function(page){window._qevents=window._qevents||[];var opts=this.options;var settings={qacct:opts.pCode};var user=this.analytics.user();if(user.id())settings.uid=user.id();if(page){settings.labels=this.labels("page",page.category(),page.name())}push(settings);var name=useHttps()?"https":"http";this.load(name,this.ready)};Quantcast.prototype.loaded=function(){return!!window.__qc};Quantcast.prototype.page=function(page){var category=page.category();var name=page.name();var settings={event:"refresh",labels:this.labels("page",category,name),qacct:this.options.pCode};var user=this.analytics.user();if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.identify=function(identify){var id=identify.userId();if(id){window._qevents[0]=window._qevents[0]||{};window._qevents[0].uid=id}};Quantcast.prototype.track=function(track){var name=track.event();var revenue=track.revenue();var settings={event:"click",labels:this.labels("event",name),qacct:this.options.pCode};var user=this.analytics.user();if(null!=revenue)settings.revenue=revenue+"";if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.completedOrder=function(track){var name=track.event();var revenue=track.total();var labels=this.labels("event",name);var category=track.category();if(this.options.advertise&&category){labels+=","+this.labels("pcat",category)}var settings={event:"refresh",labels:labels,revenue:revenue+"",orderid:track.orderId(),qacct:this.options.pCode};push(settings)};Quantcast.prototype.labels=function(type){var args=[].slice.call(arguments,1);var advertise=this.options.advertise;var ret=[];if(advertise&&"page"==type)type="event";if(advertise)type="_fp."+type;for(var i=0;i<args.length;++i){if(null==args[i])continue;var value=String(args[i]);ret.push(value.replace(/,/g,";"))}ret=advertise?ret.join(" "):ret.join(".");return[type,ret].join(".")}},{"global-queue":150,"analytics.js-integration":81,"use-https":83}],67:[function(require,module,exports){var integration=require("analytics.js-integration");var extend=require("extend");var is=require("is");var RollbarIntegration=module.exports=integration("Rollbar").global("Rollbar").option("identify",true).option("accessToken","").option("environment","unknown").option("captureUncaught",true);RollbarIntegration.prototype.initialize=function(page){var _rollbarConfig=this.config={accessToken:this.options.accessToken,captureUncaught:this.options.captureUncaught,payload:{environment:this.options.environment}};(function(a){function b(b){this.shimId=++g,this.notifier=null,this.parentShim=b,this.logger=function(){},a.console&&void 0===a.console.shimId&&(this.logger=a.console.log)
}function c(b,c,d){!d[4]&&a._rollbarWrappedError&&(d[4]=a._rollbarWrappedError,a._rollbarWrappedError=null),b.uncaughtError.apply(b,d),c&&c.apply(a,d)}function d(c){var d=b;return f(function(){if(this.notifier)return this.notifier[c].apply(this.notifier,arguments);var b=this,e="scope"===c;e&&(b=new d(this));var f=Array.prototype.slice.call(arguments,0),g={shim:b,method:c,args:f,ts:new Date};return a._rollbarShimQueue.push(g),e?b:void 0})}function e(a,b){if(b.hasOwnProperty&&b.hasOwnProperty("addEventListener")){var c=b.addEventListener;b.addEventListener=function(b,d,e){c.call(this,b,a.wrap(d),e)};var d=b.removeEventListener;b.removeEventListener=function(a,b,c){d.call(this,a,b._wrapped||b,c)}}}function f(a,b){return b=b||this.logger,function(){try{return a.apply(this,arguments)}catch(c){b("Rollbar internal error:",c)}}}var g=0;b.init=function(a,d){var g=d.globalAlias||"Rollbar";if("object"==typeof a[g])return a[g];a._rollbarShimQueue=[],a._rollbarWrappedError=null,d=d||{};var h=new b;return f(function(){if(h.configure(d),d.captureUncaught){var b=a.onerror;a.onerror=function(){var a=Array.prototype.slice.call(arguments,0);c(h,b,a)};var f,i,j=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"];for(f=0;f<j.length;++f)i=j[f],a[i]&&a[i].prototype&&e(h,a[i].prototype)}return a[g]=h,h},h.logger)()},b.prototype.loadFull=function(a,b,c,d,e){var g=f(function(){var a=b.createElement("script"),e=b.getElementsByTagName("script")[0];a.src=d.rollbarJsUrl,a.async=!c,a.onload=h,e.parentNode.insertBefore(a,e)},this.logger),h=f(function(){var b;if(void 0===a._rollbarPayloadQueue){var c,d,f,g;for(b=new Error("rollbar.js did not load");c=a._rollbarShimQueue.shift();)for(f=c.args,g=0;g<f.length;++g)if(d=f[g],"function"==typeof d){d(b);break}}e&&e(b)},this.logger);f(function(){c?g():a.addEventListener?a.addEventListener("load",g,!1):a.attachEvent("onload",g)},this.logger)()},b.prototype.wrap=function(b){if("function"!=typeof b)return b;if(b._isWrap)return b;if(!b._wrapped){b._wrapped=function(){try{return b.apply(this,arguments)}catch(c){throw a._rollbarWrappedError=c,c}},b._wrapped._isWrap=!0;for(var c in b)b.hasOwnProperty(c)&&(b._wrapped[c]=b[c])}return b._wrapped};for(var h="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),i=0;i<h.length;++i)b.prototype[h[i]]=d(h[i]);var j="//d37gvrvc0wt4s1.cloudfront.net/js/v1.0/rollbar.min.js";_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||j,b.init(a,_rollbarConfig)})(window,document);this.load(this.ready)};RollbarIntegration.prototype.loaded=function(){return is.object(window.Rollbar)&&null==window.Rollbar.shimId};RollbarIntegration.prototype.load=function(callback){window.Rollbar.loadFull(window,document,true,this.config,callback)};RollbarIntegration.prototype.identify=function(identify){if(!this.options.identify)return;var uid=identify.userId();if(uid===null||uid===undefined)return;var rollbar=window.Rollbar;var person={id:uid};extend(person,identify.traits());rollbar.configure({payload:{person:person}})}},{"analytics.js-integration":81,extend:120,is:84}],68:[function(require,module,exports){var integration=require("analytics.js-integration");var SaaSquatch=module.exports=integration("SaaSquatch").option("tenantAlias","").global("_sqh").tag('<script src="//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js">');SaaSquatch.prototype.initialize=function(page){window._sqh=window._sqh||[];this.load(this.ready)};SaaSquatch.prototype.loaded=function(){return window._sqh&&window._sqh.push!=[].push};SaaSquatch.prototype.identify=function(identify){var sqh=window._sqh;var accountId=identify.proxy("traits.accountId");var image=identify.proxy("traits.referralImage");var opts=identify.options(this.name);var id=identify.userId();var email=identify.email();if(!(id||email))return;if(this.called)return;var init={tenant_alias:this.options.tenantAlias,first_name:identify.firstName(),last_name:identify.lastName(),user_image:identify.avatar(),email:email,user_id:id};if(accountId)init.account_id=accountId;if(opts.checksum)init.checksum=opts.checksum;if(image)init.fb_share_image=image;sqh.push(["init",init]);this.called=true;this.load()}},{"analytics.js-integration":81}],69:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var Sentry=module.exports=integration("Sentry").global("Raven").option("config","").tag('<script src="//cdn.ravenjs.com/1.1.10/native/raven.min.js">');Sentry.prototype.initialize=function(){var config=this.options.config;var self=this;this.load(function(){window.Raven.config(config).install();self.ready()})};Sentry.prototype.loaded=function(){return is.object(window.Raven)};Sentry.prototype.identify=function(identify){window.Raven.setUser(identify.traits())}},{"analytics.js-integration":81,is:84}],70:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var SnapEngage=module.exports=integration("SnapEngage").assumesPageview().global("SnapABug").option("apiKey","").tag('<script src="//commondatastorage.googleapis.com/code.snapengage.com/js/{{ apiKey }}.js">');SnapEngage.prototype.initialize=function(page){this.load(this.ready)};SnapEngage.prototype.loaded=function(){return is.object(window.SnapABug)};SnapEngage.prototype.identify=function(identify){var email=identify.email();if(!email)return;window.SnapABug.setUserEmail(email)}},{"analytics.js-integration":81,is:84}],71:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var Spinnakr=module.exports=integration("Spinnakr").assumesPageview().global("_spinnakr_site_id").global("_spinnakr").option("siteId","").tag('<script src="//d3ojzyhbolvoi5.cloudfront.net/js/so.js">');Spinnakr.prototype.initialize=function(page){window._spinnakr_site_id=this.options.siteId;var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Spinnakr.prototype.loaded=function(){return!!window._spinnakr}},{"analytics.js-integration":81,bind:93,when:121}],72:[function(require,module,exports){var integration=require("analytics.js-integration");var slug=require("slug");var push=require("global-queue")("_tsq");var Tapstream=module.exports=integration("Tapstream").assumesPageview().global("_tsq").option("accountName","").option("trackAllPages",true).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//cdn.tapstream.com/static/js/tapstream.js">');Tapstream.prototype.initialize=function(page){window._tsq=window._tsq||[];push("setAccountName",this.options.accountName);this.load(this.ready)};Tapstream.prototype.loaded=function(){return!!(window._tsq&&window._tsq.push!==Array.prototype.push)};Tapstream.prototype.page=function(page){var category=page.category();var opts=this.options;var name=page.fullName();if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Tapstream.prototype.track=function(track){var props=track.properties();push("fireHit",slug(track.event()),[props.url])}},{"analytics.js-integration":81,slug:91,"global-queue":150}],73:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var clone=require("clone");var Trakio=module.exports=integration("trak.io").assumesPageview().global("trak").option("token","").option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js">');var optionsAliases={initialPageview:"auto_track_page_view"};Trakio.prototype.initialize=function(page){var options=this.options;window.trak=window.trak||[];window.trak.io=window.trak.io||{};window.trak.push=window.trak.push||function(){};window.trak.io.load=window.trak.io.load||function(e){var r=function(e){return function(){window.trak.push([e].concat(Array.prototype.slice.call(arguments,0)))}},i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"];for(var s=0;s<i.length;s++)window.trak.io[i[s]]=r(i[s]);window.trak.io.initialize.apply(window.trak.io,arguments)};window.trak.io.load(options.token,alias(options,optionsAliases));this.load(this.ready)};Trakio.prototype.loaded=function(){return!!(window.trak&&window.trak.loaded)};Trakio.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();window.trak.io.page_view(props.path,name||props.title);if(name&&this.options.trackNamedPages){this.track(page.track(name))}if(category&&this.options.trackCategorizedPages){this.track(page.track(category))}};var traitAliases={avatar:"avatar_url",firstName:"first_name",lastName:"last_name"};Trakio.prototype.identify=function(identify){var traits=identify.traits(traitAliases);var id=identify.userId();if(id){window.trak.io.identify(id,traits)}else{window.trak.io.identify(traits)}};Trakio.prototype.track=function(track){window.trak.io.track(track.event(),track.properties())};Trakio.prototype.alias=function(alias){if(!window.trak.io.distinct_id)return;var from=alias.from();var to=alias.to();if(to===window.trak.io.distinct_id())return;if(from){window.trak.io.alias(from,to)}else{window.trak.io.alias(to)}}},{"analytics.js-integration":81,alias:155,clone:154}],74:[function(require,module,exports){var integration=require("analytics.js-integration");var each=require("each");var has=Object.prototype.hasOwnProperty;var TwitterAds=module.exports=integration("Twitter Ads").option("page","").tag('<img src="//analytics.twitter.com/i/adsct?txn_id={{ pixelId }}&p_id=Twitter"/>').mapping("events");TwitterAds.prototype.initialize=function(){this.ready()};TwitterAds.prototype.page=function(page){if(this.options.page){this.load({pixelId:this.options.page})}};TwitterAds.prototype.track=function(track){var events=this.events(track.event());var self=this;each(events,function(pixelId){self.load({pixelId:pixelId})})}},{"analytics.js-integration":81,each:4}],75:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("UserVoice");var convertDates=require("convert-dates");var unix=require("to-unix-timestamp");var alias=require("alias");var clone=require("clone");var UserVoice=module.exports=integration("UserVoice").assumesPageview().global("UserVoice").global("showClassicWidget").option("apiKey","").option("classic",false).option("forumId",null).option("showWidget",true).option("mode","contact").option("accentColor","#448dd6").option("smartvote",true).option("trigger",null).option("triggerPosition","bottom-right").option("triggerColor","#ffffff").option("triggerBackgroundColor","rgba(46, 49, 51, 0.6)").option("classicMode","full").option("primaryColor","#cc6d00").option("linkColor","#007dbf").option("defaultMode","support").option("tabLabel","Feedback & Support").option("tabColor","#cc6d00").option("tabPosition","middle-right").option("tabInverted",false).tag('<script src="//widget.uservoice.com/{{ apiKey }}.js">');UserVoice.on("construct",function(integration){if(!integration.options.classic)return;integration.group=undefined;integration.identify=integration.identifyClassic;integration.initialize=integration.initializeClassic});UserVoice.prototype.initialize=function(page){var options=this.options;var opts=formatOptions(options);push("set",opts);push("autoprompt",{});if(options.showWidget){options.trigger?push("addTrigger",options.trigger,opts):push("addTrigger",opts)}this.load(this.ready)};UserVoice.prototype.loaded=function(){return!!(window.UserVoice&&window.UserVoice.push!==Array.prototype.push)};UserVoice.prototype.identify=function(identify){var traits=identify.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",traits)};UserVoice.prototype.group=function(group){var traits=group.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",{account:traits})};UserVoice.prototype.initializeClassic=function(){var options=this.options;window.showClassicWidget=showClassicWidget;if(options.showWidget)showClassicWidget("showTab",formatClassicOptions(options));this.load(this.ready)};UserVoice.prototype.identifyClassic=function(identify){push("setCustomFields",identify.traits())};function formatOptions(options){return alias(options,{forumId:"forum_id",accentColor:"accent_color",smartvote:"smartvote_enabled",triggerColor:"trigger_color",triggerBackgroundColor:"trigger_background_color",triggerPosition:"trigger_position"})}function formatClassicOptions(options){return alias(options,{forumId:"forum_id",classicMode:"mode",primaryColor:"primary_color",tabPosition:"tab_position",tabColor:"tab_color",linkColor:"link_color",defaultMode:"default_mode",tabLabel:"tab_label",tabInverted:"tab_inverted"})}function showClassicWidget(type,options){type=type||"showLightbox";push(type,"classic_widget",options)}},{"analytics.js-integration":81,"global-queue":150,"convert-dates":156,"to-unix-timestamp":179,alias:155,clone:154}],179:[function(require,module,exports){module.exports=toUnixTimestamp;function toUnixTimestamp(date){return Math.floor(date.getTime()/1e3)}},{}],76:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_veroq");var cookie=require("component/cookie");var Vero=module.exports=integration("Vero").global("_veroq").option("apiKey","").tag('<script src="//d3qxef4rp70elm.cloudfront.net/m.js">');Vero.prototype.initialize=function(page){if(!cookie("__veroc4"))cookie("__veroc4","[]");push("init",{api_key:this.options.apiKey});this.load(this.ready)};Vero.prototype.loaded=function(){return!!(window._veroq&&window._veroq.push!==Array.prototype.push)};Vero.prototype.page=function(page){push("trackPageview")};Vero.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var id=identify.userId();if(!id||!email)return;push("user",traits)};Vero.prototype.track=function(track){push("track",track.event(),track.properties())}},{"analytics.js-integration":81,"global-queue":150,"component/cookie":180}],180:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;module.exports=function(name,value,options){switch(arguments.length){case 3:case 2:return set(name,value,options);case 1:return get(name);default:return all()}};function set(name,value,options){options=options||{};var str=encode(name)+"="+encode(value);if(null==value)options.maxage=-1;if(options.maxage){options.expires=new Date(+new Date+options.maxage)}if(options.path)str+="; path="+options.path;if(options.domain)str+="; domain="+options.domain;if(options.expires)str+="; expires="+options.expires.toGMTString();if(options.secure)str+="; secure";document.cookie=str}function all(){return parse(document.cookie)}function get(name){return all()[name]}function parse(str){var obj={};var pairs=str.split(/ *; */);var pair;if(""==pairs[0])return obj;for(var i=0;i<pairs.length;++i){pair=pairs[i].split("=");obj[decode(pair[0])]=decode(pair[1])}return obj}},{}],77:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var each=require("each");var VWO=module.exports=integration("Visual Website Optimizer").option("replay",true);VWO.prototype.initialize=function(){if(this.options.replay)this.replay();this.ready()};VWO.prototype.replay=function(){var analytics=this.analytics;tick(function(){experiments(function(err,traits){if(traits)analytics.identify(traits)})})};function experiments(fn){enqueue(function(){var data={};var ids=window._vwo_exp_ids;if(!ids)return fn();each(ids,function(id){var name=variation(id);if(name)data["Experiment: "+id]=name});fn(null,data)})}function enqueue(fn){window._vis_opt_queue=window._vis_opt_queue||[];window._vis_opt_queue.push(fn)}function variation(id){var experiments=window._vwo_exp;if(!experiments)return null;var experiment=experiments[id];var variationId=experiment.combination_chosen;return variationId?experiment.comb_n[variationId]:null}},{"analytics.js-integration":81,"next-tick":95,each:4}],78:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var WebEngage=module.exports=integration("WebEngage").assumesPageview().global("_weq").global("webengage").option("widgetVersion","4.0").option("licenseCode","").tag("http",'<script src="http://cdn.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">').tag("https",'<script src="https://ssl.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">');WebEngage.prototype.initialize=function(page){var _weq=window._weq=window._weq||{};_weq["webengage.licenseCode"]=this.options.licenseCode;_weq["webengage.widgetVersion"]=this.options.widgetVersion;var name=useHttps()?"https":"http";this.load(name,this.ready)};WebEngage.prototype.loaded=function(){return!!window.webengage}},{"analytics.js-integration":81,"use-https":83}],79:[function(require,module,exports){var integration=require("analytics.js-integration");var snake=require("to-snake-case");var isEmail=require("is-email");var extend=require("extend");var each=require("each");var type=require("type");var Woopra=module.exports=integration("Woopra").global("woopra").option("domain","").option("cookieName","wooTracker").option("cookieDomain",null).option("cookiePath","/").option("ping",true).option("pingInterval",12e3).option("idleTimeout",3e5).option("downloadTracking",true).option("outgoingTracking",true).option("outgoingIgnoreSubdomain",true).option("downloadPause",200).option("outgoingPause",400).option("ignoreQueryUrl",true).option("hideCampaign",false).tag('<script src="//static.woopra.com/js/w.js">');Woopra.prototype.initialize=function(page){(function(){var i,s,z,w=window,d=document,a=arguments,q="script",f=["config","track","identify","visit","push","call"],c=function(){var i,self=this;self._e=[];for(i=0;i<f.length;i++){(function(f){self[f]=function(){self._e.push([f].concat(Array.prototype.slice.call(arguments,0)));return self}})(f[i])}};w._w=w._w||{};for(i=0;i<a.length;i++){w._w[a[i]]=w[a[i]]=w[a[i]]||new c}})("woopra");this.load(this.ready);each(this.options,function(key,value){key=snake(key);if(null==value)return;if(""===value)return;window.woopra.config(key,value)})};Woopra.prototype.loaded=function(){return!!(window.woopra&&window.woopra.loaded)};Woopra.prototype.page=function(page){var props=page.properties();var name=page.fullName();if(name)props.title=name;window.woopra.track("pv",props)};Woopra.prototype.identify=function(identify){var traits=identify.traits();if(identify.name())traits.name=identify.name();window.woopra.identify(traits).push()};Woopra.prototype.track=function(track){window.woopra.track(track.event(),track.properties())}},{"analytics.js-integration":81,"to-snake-case":82,"is-email":145,extend:120,each:4,type:7}],80:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var bind=require("bind");var when=require("when");var Yandex=module.exports=integration("Yandex Metrica").assumesPageview().global("yandex_metrika_callbacks").global("Ya").option("counterId",null).option("clickmap",false).option("webvisor",false).tag('<script src="//mc.yandex.ru/metrika/watch.js">');Yandex.prototype.initialize=function(page){var id=this.options.counterId;var clickmap=this.options.clickmap;var webvisor=this.options.webvisor;push(function(){window["yaCounter"+id]=new window.Ya.Metrika({id:id,clickmap:clickmap,webvisor:webvisor})});var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,function(){tick(ready)})})};Yandex.prototype.loaded=function(){return!!(window.Ya&&window.Ya.Metrika)};function push(callback){window.yandex_metrika_callbacks=window.yandex_metrika_callbacks||[];window.yandex_metrika_callbacks.push(callback)}},{"analytics.js-integration":81,"next-tick":95,bind:93,when:121}],3:[function(require,module,exports){var after=require("after");var bind=require("bind");var callback=require("callback");var canonical=require("canonical");var clone=require("clone");var cookie=require("./cookie");var debug=require("debug");var defaults=require("defaults");var each=require("each");var Emitter=require("emitter");var group=require("./group");var is=require("is");var isEmail=require("is-email");var isMeta=require("is-meta");var newDate=require("new-date");var on=require("event").bind;var prevent=require("prevent");var querystring=require("querystring");var size=require("object").length;var store=require("./store");var url=require("url");var user=require("./user");var Facade=require("facade");var Identify=Facade.Identify;var Group=Facade.Group;var Alias=Facade.Alias;var Track=Facade.Track;var Page=Facade.Page;exports=module.exports=Analytics;exports.cookie=cookie;exports.store=store;function Analytics(){this.Integrations={};this._integrations={};this._readied=false;this._timeout=300;this._user=user;bind.all(this);var self=this;this.on("initialize",function(settings,options){if(options.initialPageview)self.page()});this.on("initialize",function(){self._parseQuery()})}Emitter(Analytics.prototype);Analytics.prototype.use=function(plugin){plugin(this);return this};Analytics.prototype.addIntegration=function(Integration){var name=Integration.prototype.name;if(!name)throw new TypeError("attempted to add an invalid integration");this.Integrations[name]=Integration;return this};Analytics.prototype.init=Analytics.prototype.initialize=function(settings,options){settings=settings||{};options=options||{};this._options(options);this._readied=false;var self=this;each(settings,function(name){var Integration=self.Integrations[name];if(!Integration)delete settings[name]});each(settings,function(name,opts){var Integration=self.Integrations[name];var integration=new Integration(clone(opts));self.add(integration)});var integrations=this._integrations;user.load();group.load();var ready=after(size(integrations),function(){self._readied=true;self.emit("ready")});each(integrations,function(name,integration){if(options.initialPageview&&integration.options.initialPageview===false){integration.page=after(2,integration.page)}integration.analytics=self;integration.once("ready",ready);integration.initialize()});this.initialized=true;this.emit("initialize",settings,options);return this};Analytics.prototype.add=function(integration){this._integrations[integration.name]=integration;return this};Analytics.prototype.identify=function(id,traits,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=user.id();user.identify(id,traits);id=user.id();traits=user.traits();this._invoke("identify",message(Identify,{options:options,traits:traits,userId:id}));this.emit("identify",id,traits,options);this._callback(fn);return this};Analytics.prototype.user=function(){return user};Analytics.prototype.group=function(id,traits,options,fn){if(0===arguments.length)return group;if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=group.id();group.identify(id,traits);id=group.id();traits=group.traits();this._invoke("group",message(Group,{options:options,traits:traits,groupId:id}));this.emit("group",id,traits,options);this._callback(fn);return this};Analytics.prototype.track=function(event,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=null,properties=null;this._invoke("track",message(Track,{properties:properties,options:options,event:event}));this.emit("track",event,properties,options);this._callback(fn);return this};Analytics.prototype.trackClick=Analytics.prototype.trackLink=function(links,event,properties){if(!links)return this;if(is.element(links))links=[links];var self=this;each(links,function(el){if(!is.element(el))throw new TypeError("Must pass HTMLElement to `analytics.trackLink`.");on(el,"click",function(e){var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);if(el.href&&el.target!=="_blank"&&!isMeta(e)){prevent(e);self._callback(function(){window.location.href=el.href})}})});return this};Analytics.prototype.trackSubmit=Analytics.prototype.trackForm=function(forms,event,properties){if(!forms)return this;if(is.element(forms))forms=[forms];var self=this;each(forms,function(el){if(!is.element(el))throw new TypeError("Must pass HTMLElement to `analytics.trackForm`.");function handler(e){prevent(e);var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);self._callback(function(){el.submit()})}var $=window.jQuery||window.Zepto;if($){$(el).submit(handler)}else{on(el,"submit",handler)}});return this};Analytics.prototype.page=function(category,name,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=properties=null;if(is.fn(name))fn=name,options=properties=name=null;if(is.object(category))options=name,properties=category,name=category=null;if(is.object(name))options=properties,properties=name,name=null;if(is.string(category)&&!is.string(name))name=category,category=null;var defs={path:canonicalPath(),referrer:document.referrer,title:document.title,search:location.search};if(name)defs.name=name;if(category)defs.category=category;properties=clone(properties)||{};defaults(properties,defs);properties.url=properties.url||canonicalUrl(properties.search);this._invoke("page",message(Page,{properties:properties,category:category,options:options,name:name}));this.emit("page",category,name,properties,options);this._callback(fn);return this};Analytics.prototype.pageview=function(url,options){var properties={};if(url)properties.path=url;this.page(properties);return this};Analytics.prototype.alias=function(to,from,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(from))fn=from,options=null,from=null;if(is.object(from))options=from,from=null;this._invoke("alias",message(Alias,{options:options,from:from,to:to}));this.emit("alias",to,from,options);this._callback(fn);return this};Analytics.prototype.ready=function(fn){if(!is.fn(fn))return this;this._readied?callback.async(fn):this.once("ready",fn);return this};Analytics.prototype.timeout=function(timeout){this._timeout=timeout};Analytics.prototype.debug=function(str){if(0==arguments.length||str){debug.enable("analytics:"+(str||"*"))}else{debug.disable()}};Analytics.prototype._options=function(options){options=options||{};cookie.options(options.cookie);store.options(options.localStorage);user.options(options.user);group.options(options.group);return this};Analytics.prototype._callback=function(fn){callback.async(fn,this._timeout);return this};Analytics.prototype._invoke=function(method,facade){var options=facade.options();this.emit("invoke",facade);each(this._integrations,function(name,integration){if(!facade.enabled(name))return;integration.invoke.call(integration,method,facade)});return this};Analytics.prototype.push=function(args){var method=args.shift();if(!this[method])return;this[method].apply(this,args)};Analytics.prototype._parseQuery=function(){var q=querystring.parse(window.location.search);if(q.ajs_uid)this.identify(q.ajs_uid);if(q.ajs_event)this.track(q.ajs_event);return this};function canonicalPath(){var canon=canonical();if(!canon)return window.location.pathname;var parsed=url.parse(canon);return parsed.pathname}function canonicalUrl(search){var canon=canonical();if(canon)return~canon.indexOf("?")?canon:canon+search;var url=window.location.href;var i=url.indexOf("#");return-1==i?url:url.slice(0,i)}function message(Type,msg){var ctx=msg.options||{};if(ctx.timestamp||ctx.integrations||ctx.context||ctx.anonymousId){msg=defaults(ctx,msg);delete msg.options}return new Type(msg)}},{after:103,bind:181,callback:86,canonical:158,clone:87,"./cookie":182,debug:183,defaults:89,each:4,emitter:100,"./group":184,is:84,"is-email":145,"is-meta":185,"new-date":137,event:186,prevent:187,querystring:188,object:157,"./store":189,url:160,"./user":190,facade:122}],181:[function(require,module,exports){try{var bind=require("bind")}catch(e){var bind=require("bind-component")}var bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;function bindMethods(obj,methods){methods=[].slice.call(arguments,1);for(var i=0,method;method=methods[i];i++){obj[method]=bind(obj,obj[method])}return obj}},{bind:93,"bind-all":94}],182:[function(require,module,exports){var debug=require("debug")("analytics.js:cookie");var bind=require("bind");var cookie=require("cookie");var clone=require("clone");var defaults=require("defaults");var json=require("json");var topDomain=require("top-domain");function Cookie(options){this.options(options)}Cookie.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};var domain="."+topDomain(window.location.href);this._options=defaults(options,{maxage:31536e6,path:"/",domain:domain});this.set("ajs:test",true);if(!this.get("ajs:test")){debug("fallback to domain=null");this._options.domain=null}this.remove("ajs:test")};Cookie.prototype.set=function(key,value){try{value=json.stringify(value);cookie(key,value,clone(this._options));return true}catch(e){return false}};Cookie.prototype.get=function(key){try{var value=cookie(key);value=value?json.parse(value):null;return value}catch(e){return null}};Cookie.prototype.remove=function(key){try{cookie(key,null,clone(this._options));return true}catch(e){return false}};module.exports=bind.all(new Cookie);module.exports.Cookie=Cookie},{debug:183,bind:181,cookie:180,clone:87,defaults:89,json:191,"top-domain":192}],183:[function(require,module,exports){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}},{"./lib/debug":193,"./debug":194}],193:[function(require,module,exports){var tty=require("tty");module.exports=debug;var names=[],skips=[];(process.env.DEBUG||"").split(/[\s,]+/).forEach(function(name){name=name.replace("*",".*?");if(name[0]==="-"){skips.push(new RegExp("^"+name.substr(1)+"$"))}else{names.push(new RegExp("^"+name+"$"))}});var colors=[6,2,3,4,5,1];var prev={};var prevColor=0;var isatty=tty.isatty(2);function color(){return colors[prevColor++%colors.length]}function humanize(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"}function debug(name){function disabled(){}disabled.enabled=false;var match=skips.some(function(re){return re.test(name)});if(match)return disabled;match=names.some(function(re){return re.test(name)});if(!match)return disabled;var c=color();function colored(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(prev[name]||curr);prev[name]=curr;fmt=" [9"+c+"m"+name+" "+"[3"+c+"m[90m"+fmt+"[3"+c+"m"+" +"+humanize(ms)+"[0m";console.error.apply(this,arguments)}function plain(fmt){fmt=coerce(fmt);fmt=(new Date).toUTCString()+" "+name+" "+fmt;console.error.apply(this,arguments)}colored.enabled=plain.enabled=true;return isatty||process.env.DEBUG_COLORS?colored:plain}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{}],194:[function(require,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);
var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],191:[function(require,module,exports){var json=window.JSON||{};var stringify=json.stringify;var parse=json.parse;module.exports=parse&&stringify?JSON:require("json-fallback")},{"json-fallback":195}],195:[function(require,module,exports){(function(){"use strict";var JSON=module.exports={};function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()}}var cx,escapable,gap,indent,meta,rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==="string"){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function"){escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else if(typeof space==="string"){indent=space}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}})()},{}],192:[function(require,module,exports){var parse=require("url").parse;module.exports=domain;var regexp=/[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i;function domain(url){var host=parse(url).hostname;var match=host.match(regexp);return match?match[0]:""}},{url:160}],184:[function(require,module,exports){var debug=require("debug")("analytics:group");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");Group.defaults={persist:true,cookie:{key:"ajs_group_id"},localStorage:{key:"ajs_group_properties"}};function Group(options){this.defaults=Group.defaults;this.debug=debug;Entity.call(this,options)}inherit(Group,Entity);module.exports=bind.all(new Group);module.exports.Group=Group},{debug:183,"./entity":196,inherit:197,bind:181}],196:[function(require,module,exports){var traverse=require("isodate-traverse");var defaults=require("defaults");var cookie=require("./cookie");var store=require("./store");var extend=require("extend");var clone=require("clone");module.exports=Entity;function Entity(options){this.protocol=window.location.protocol;this.options(options)}Entity.prototype.storage=function(){return"file:"==this.protocol||"chrome-extension:"==this.protocol?store:cookie};Entity.prototype.options=function(options){if(arguments.length===0)return this._options;options||(options={});defaults(options,this.defaults||{});this._options=options};Entity.prototype.id=function(id){switch(arguments.length){case 0:return this._getId();case 1:return this._setId(id)}};Entity.prototype._getId=function(){var storage=this.storage();var ret=this._options.persist?storage.get(this._options.cookie.key):this._id;return ret===undefined?null:ret};Entity.prototype._setId=function(id){var storage=this.storage();if(this._options.persist){storage.set(this._options.cookie.key,id)}else{this._id=id}};Entity.prototype.properties=Entity.prototype.traits=function(traits){switch(arguments.length){case 0:return this._getTraits();case 1:return this._setTraits(traits)}};Entity.prototype._getTraits=function(){var ret=this._options.persist?store.get(this._options.localStorage.key):this._traits;return ret?traverse(clone(ret)):{}};Entity.prototype._setTraits=function(traits){traits||(traits={});if(this._options.persist){store.set(this._options.localStorage.key,traits)}else{this._traits=traits}};Entity.prototype.identify=function(id,traits){traits||(traits={});var current=this.id();if(current===null||current===id)traits=extend(this.traits(),traits);if(id)this.id(id);this.debug("identify %o, %o",id,traits);this.traits(traits);this.save()};Entity.prototype.save=function(){if(!this._options.persist)return false;cookie.set(this._options.cookie.key,this.id());store.set(this._options.localStorage.key,this.traits());return true};Entity.prototype.logout=function(){this.id(null);this.traits({});cookie.remove(this._options.cookie.key);store.remove(this._options.localStorage.key)};Entity.prototype.reset=function(){this.logout();this.options({})};Entity.prototype.load=function(){this.id(cookie.get(this._options.cookie.key));this.traits(store.get(this._options.localStorage.key))}},{"isodate-traverse":132,defaults:89,"./cookie":182,"./store":189,extend:120,clone:87}],189:[function(require,module,exports){var bind=require("bind");var defaults=require("defaults");var store=require("store.js");function Store(options){this.options(options)}Store.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};defaults(options,{enabled:true});this.enabled=options.enabled&&store.enabled;this._options=options};Store.prototype.set=function(key,value){if(!this.enabled)return false;return store.set(key,value)};Store.prototype.get=function(key){if(!this.enabled)return null;return store.get(key)};Store.prototype.remove=function(key){if(!this.enabled)return false;return store.remove(key)};module.exports=bind.all(new Store);module.exports.Store=Store},{bind:181,defaults:89,"store.js":198}],198:[function(require,module,exports){var json=require("json"),store={},win=window,doc=win.document,localStorageName="localStorage",namespace="__storejs__",storage;store.disabled=false;store.set=function(key,value){};store.get=function(key){};store.remove=function(key){};store.clear=function(){};store.transact=function(key,defaultVal,transactionFn){var val=store.get(key);if(transactionFn==null){transactionFn=defaultVal;defaultVal=null}if(typeof val=="undefined"){val=defaultVal||{}}transactionFn(val);store.set(key,val)};store.getAll=function(){};store.serialize=function(value){return json.stringify(value)};store.deserialize=function(value){if(typeof value!="string"){return undefined}try{return json.parse(value)}catch(e){return value||undefined}};function isLocalStorageNameSupported(){try{return localStorageName in win&&win[localStorageName]}catch(err){return false}}if(isLocalStorageNameSupported()){storage=win[localStorageName];store.set=function(key,val){if(val===undefined){return store.remove(key)}storage.setItem(key,store.serialize(val));return val};store.get=function(key){return store.deserialize(storage.getItem(key))};store.remove=function(key){storage.removeItem(key)};store.clear=function(){storage.clear()};store.getAll=function(){var ret={};for(var i=0;i<storage.length;++i){var key=storage.key(i);ret[key]=store.get(key)}return ret}}else if(doc.documentElement.addBehavior){var storageOwner,storageContainer;try{storageContainer=new ActiveXObject("htmlfile");storageContainer.open();storageContainer.write("<s"+"cript>document.w=window</s"+'cript><iframe src="/favicon.ico"></iframe>');storageContainer.close();storageOwner=storageContainer.w.frames[0].document;storage=storageOwner.createElement("div")}catch(e){storage=doc.createElement("div");storageOwner=doc.body}function withIEStorage(storeFunction){return function(){var args=Array.prototype.slice.call(arguments,0);args.unshift(storage);storageOwner.appendChild(storage);storage.addBehavior("#default#userData");storage.load(localStorageName);var result=storeFunction.apply(store,args);storageOwner.removeChild(storage);return result}}var forbiddenCharsRegex=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");function ieKeyFix(key){return key.replace(forbiddenCharsRegex,"___")}store.set=withIEStorage(function(storage,key,val){key=ieKeyFix(key);if(val===undefined){return store.remove(key)}storage.setAttribute(key,store.serialize(val));storage.save(localStorageName);return val});store.get=withIEStorage(function(storage,key){key=ieKeyFix(key);return store.deserialize(storage.getAttribute(key))});store.remove=withIEStorage(function(storage,key){key=ieKeyFix(key);storage.removeAttribute(key);storage.save(localStorageName)});store.clear=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;storage.load(localStorageName);for(var i=0,attr;attr=attributes[i];i++){storage.removeAttribute(attr.name)}storage.save(localStorageName)});store.getAll=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;var ret={};for(var i=0,attr;attr=attributes[i];++i){var key=ieKeyFix(attr.name);ret[attr.name]=store.deserialize(storage.getAttribute(key))}return ret})}try{store.set(namespace,namespace);if(store.get(namespace)!=namespace){store.disabled=true}store.remove(namespace)}catch(e){store.disabled=true}store.enabled=!store.disabled;module.exports=store},{json:191}],197:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],185:[function(require,module,exports){module.exports=function isMeta(e){if(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)return true;var which=e.which,button=e.button;if(!which&&button!==undefined){return!button&1&&!button&2&&button&4}else if(which===2){return true}return false}},{}],186:[function(require,module,exports){exports.bind=function(el,type,fn,capture){if(el.addEventListener){el.addEventListener(type,fn,capture||false)}else{el.attachEvent("on"+type,fn)}return fn};exports.unbind=function(el,type,fn,capture){if(el.removeEventListener){el.removeEventListener(type,fn,capture||false)}else{el.detachEvent("on"+type,fn)}return fn}},{}],187:[function(require,module,exports){module.exports=function(e){e=e||window.event;return e.preventDefault?e.preventDefault():e.returnValue=false}},{}],188:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=/(\w+)\[(\d+)\]/.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:146,type:7}],190:[function(require,module,exports){var debug=require("debug")("analytics:user");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");var cookie=require("./cookie");User.defaults={persist:true,cookie:{key:"ajs_user_id",oldKey:"ajs_user"},localStorage:{key:"ajs_user_traits"}};function User(options){this.defaults=User.defaults;this.debug=debug;Entity.call(this,options)}inherit(User,Entity);User.prototype.load=function(){if(this._loadOldCookie())return;Entity.prototype.load.call(this)};User.prototype._loadOldCookie=function(){var user=cookie.get(this._options.cookie.oldKey);if(!user)return false;this.id(user.id);this.traits(user.traits);cookie.remove(this._options.cookie.oldKey);return true};module.exports=bind.all(new User);module.exports.User=User},{debug:183,"./entity":196,inherit:197,bind:181,"./cookie":182}],5:[function(require,module,exports){module.exports="2.3.21"},{}]},{},{1:"analytics"}); |
source-frontend/src/Home.js | Everstar/MusicRadio | /**
* Created by tsengkasing on 12/8/2016.
*/
import React from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import {Card, CardHeader,} from 'material-ui/Card';
import { hashHistory } from 'react-router'
import LinearProgress from 'material-ui/LinearProgress'
import Divider from 'material-ui/Divider';
import Subheader from 'material-ui/Subheader';
import {List, ListItem} from 'material-ui/List';
import TextField from 'material-ui/TextField';
import {GridList, GridTile} from 'material-ui/GridList';
import Paper from 'material-ui/Paper';
import Avatar from 'material-ui/Avatar';
import $ from 'jquery';
import Auth from './account/Auth';
import API from './API'
const styles = {
wrapper: {
display: 'flex',
flexWrap: 'wrap',
},
autoWidth: {
width : 'auto',
maxWidth : '64px',
},
paper : {
height: 128,
maxWidth: '1024px',
marginBottom: 20,
textAlign: 'center',
},
root: {
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-around',
},
gridList: {
display: 'flex',
flexWrap: 'nowrap',
overflowX: 'auto',
textAlign : 'left',
},
titleStyle: {
color: 'rgb(0, 188, 212)',
},
imageInput: {
cursor: 'pointer',
position: 'absolute',
top: 0,
bottom: 0,
right: 0,
left: 0,
width: '100%',
opacity: 0,
},
};
class UploadAvator extends React.Component {
state = {
open: false,
};
handleOpen = () => {
this.setState({open: true});
};
handleClose = () => {
this.setState({open: false});
};
handleSubmit = () => {
$('#uploadAvator').click();
this.setState({open: false});
};
render() {
const actions = [
<FlatButton
label="取消"
primary={true}
onTouchTap={this.handleClose}
/>,
<FlatButton
label="确定"
primary={true}
onTouchTap={this.handleSubmit}
/>,
];
return (
<div>
<Dialog
title="Upload a Avator"
actions={actions}
modal={false}
open={this.state.open}
onRequestClose={this.handleClose}
>
<form id="changeAvator" method="post" encType="multipart/form-data" action={API.Avatar} target="uploadFrame">
<FlatButton label="Choose an Image" labelPosition="before">
<input type="file" style={styles.imageInput} name="image_file" />
</FlatButton>
<input type="submit" value="upload" id="uploadAvator" style={{visibility : 'collapse'}}/>
</form>
</Dialog>
</div>
);
}
}
export default class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
avator_url : 'http://img.neverstar.top/default.jpg',
exp: 0,
exp_max : 100,
level : 1,
gender : "male",
ctr_songlist : 0,
liked_songlist : 0,
following_num : 0,
moments : [],
recommend_user_list : [],
recommend_song_list : [],
};
};
//获取用户信息
getUserInfo = () => {
const URL = API.Info;
$.ajax({
url : URL,
type : 'POST',
contentType: 'application/json',
headers : {
'target' : 'api',
},
success : function(data, textStatus, jqXHR) {
console.log(data);
this.setState({
avator_url : data.avator_url,
exp : data.exp,
exp_max : data.exp_max,
level : data.level,
gender : data.gender === 'M' ? 'Male' : 'Female',
ctr_songlist: data.ctr_songlist,
liked_songlist: data.liked_songlist,
following_num: data.friends_num,
});
}.bind(this),
error : function(xhr, textStatus) {
console.log(xhr.status + '\n' + textStatus + '\n');
}
});
};
changeAvatar = () => {
this.refs.UploadAvatorDialog.handleOpen();
};
getMoments = () => {
const URL = API.Moment;
$.ajax({
url : URL,
type : 'POST',
contentType: 'application/json;charset=UTF-8',
dataType: 'json',
headers : {
'target' : 'api',
},
success : function(data, textStatus, jqXHR) {
console.log(data);
for(let i = 0; i < data.length; i++) {
let avator_url = data[i].avator_url;
if(avator_url === null) continue;
data[i].avator_url = avator_url.replace(/.*\\resources\\images\\/, "http://radioimg.neverstar.top/");
data[i].avator_url = avator_url.replace(/.*\/resources\/images\//, "http://radioimg.neverstar.top/");
};
this.setState({moments : data});
}.bind(this),
error : function(xhr, textStatus) {
console.log(xhr.status + '\n' + textStatus + '\n');
}
});
};
getNeteaseSonginfo = (song_id) => {
const URL = API.SongInfo;
let music_info = {};
$.ajax({
url : URL,
async : false,
type : 'GET',
headers : {
target : 'api'
},
data : {
id : song_id,
},
success : function(data, textStatus, jqXHR) {
music_info = data;
},
error : function(xhr, textStatus) {
console.log(xhr.status + '\n' + textStatus + '\n');
}
});
return music_info;
};
getLocalSongInfo = (song_id) => {
let song_info;
const URL = API.LocalSongInfo;
$.ajax({
url : URL,
type : 'GET',
async : false,
contentType: 'application/json;charset=UTF-8',
dataType: 'json',
headers : {
'target' : 'api',
},
data : {
id : song_id,
},
success : function(data, textStatus, jqXHR) {
let avator_url = data.avator_url;
if(avator_url != null) data.avator_url = avator_url.replace(/.*\\resources\\images\\/, "http://radioimg.neverstar.top/");
if(avator_url != null) data.avator_url = avator_url.replace(/.*\/resources\/images\//, "http://radioimg.neverstar.top/");
song_info = data;
},
error : function(xhr, textStatus) {
console.log(xhr.status + '\n' + textStatus + '\n');
}
});
if(song_info.netease_id !== 0) {
song_info = this.getNeteaseSonginfo(song_info.netease_id);
}else{
song_info.song_artists = song_info.artists;
}
return song_info;
};
getRecommendSongs = () => {
const URL = API.RecommendSong;
$.ajax({
url : URL,
type : 'GET',
contentType: 'application/json;charset=UTF-8',
dataType: 'json',
headers : {
'target' : 'api',
},
data : {
data : 1,
},
success : function(data, textStatus, jqXHR) {
let detail_list = [];
for(let i = 0; i < data.length; i++) {
let info = this.getLocalSongInfo(data[i]);
info.song_id = data[i];
detail_list.push(info);
}
console.log(detail_list);
this.setState({recommend_song_list : detail_list});
}.bind(this),
error : function(xhr, textStatus) {
console.log(xhr.status + '\n' + textStatus + '\n');
}
});
};
getRecommendUserInfo = (user_id) => {
let info = {};
const URL = API.Info;
$.ajax({
url : URL,
type : 'GET',
async : false,
contentType: 'application/json;charset=UTF-8',
dataType: 'json',
headers : {
'target' : 'api',
},
data : {
id : user_id,
},
success : function(data, textStatus, jqXHR) {
info = data;
},
error : function(xhr, textStatus) {
console.log(xhr.status + '\n' + textStatus + '\n');
}
});
return info;
};
getRecommendUsers = () => {
const URL = API.RecommendUser;
$.ajax({
url : URL,
type : 'GET',
contentType: 'application/json;charset=UTF-8',
dataType: 'json',
headers : {
'target' : 'api',
},
data : {
data : 1,
},
success : function(data, textStatus, jqXHR) {
console.log(data);
let detail_list = [];
for(let i = 0; i < data.length; i++) {
detail_list.push(this.getRecommendUserInfo(data[i]));
}
console.log(detail_list);
this.setState({recommend_user_list : detail_list});
}.bind(this),
error : function(xhr, textStatus) {
console.log(xhr.status + '\n' + textStatus + '\n');
}
});
};
onClickRecommendSong = (event) => {
window.open('/radio.html?type=song&song_id=' + event.target.getAttribute('about'));
};
onClickRecommendUser = (event) => {
hashHistory.push('/user/' + event.target.getAttribute('about'));
};
componentWillMount() {
this.getUserInfo();
};
componentDidMount() {
this.getMoments();
this.getRecommendSongs();
this.getRecommendUsers();
};
render() {
let avator_url = this.state.avator_url;
if(avator_url !== null) avator_url = avator_url.replace(/.*\\resources\\images\\/, "http://radioimg.neverstar.top/");
if(avator_url !== null) avator_url = avator_url.replace(/.*\/resources\/images\//, "http://radioimg.neverstar.top/");
return (
<div style={{maxWidth: '1024px', margin:'0 auto'}}>
<Card containerStyle={{margin: 16}}
style={{background : 'transparent'}}>
<CardHeader
title={Auth.username}
titleStyle={{fontSize:'3vh'}}
subtitle={this.state.gender}
subtitleStyle={{fontSize:'2vh'}}
avatar={<Avatar src={avator_url} size={100} onTouchTap={this.changeAvatar} />}
/>
<div style={{width: '96%', margin:'0 auto'}}>
Lv{this.state.level}<LinearProgress mode="determinate" value={this.state.exp} max={this.state.exp_max} />
</div>
<List>
<ListItem primaryText="Created Song Lists" rightIcon={<TextField value={this.state.ctr_songlist} id="crt" inputStyle={styles.autoWidth} readOnly="true" underlineShow={false} />} />
<ListItem primaryText="Liked Song Lists" rightIcon={<TextField value={this.state.liked_songlist} id="lik" inputStyle={styles.autoWidth} readOnly="true" underlineShow={false} />} />
<ListItem primaryText="Following" rightIcon={<TextField value={this.state.following_num} id="friend" inputStyle={styles.autoWidth} readOnly="true" underlineShow={false} />} />
</List>
</Card>
<Divider style={{marginTop : '2%'}}/>
{/*歌曲推荐*/}
<Subheader>Today's Songs Recommend</Subheader>
<div style={styles.root}>
<GridList style={styles.gridList} cols={2.2}>
{this.state.recommend_song_list.map((song, index) => (
<GridTile
key={index}
cols={index}
title={song.song_name}
titleStyle={styles.titleStyle}
subtitle={song.song_artists}
titleBackground="linear-gradient(to top, rgba(0,0,0,0.7) 0%,rgba(0,0,0,0.3) 70%,rgba(0,0,0,0) 100%)"
>
<img src={'http://img.neverstar.top/' + index + '.jpg'} alt="居然找不到图片" onClick={this.onClickRecommendSong} about={song.song_id}
style={this.state.recommend_song_list.length > 1 ? null : {width:'100%', height:'auto'}} />
</GridTile>
))}
</GridList>
</div>
<Divider style={{marginTop : '2%'}}/>
{/*用户推荐*/}
<Subheader>Today's Users Recommend</Subheader>
<div style={styles.root}>
<GridList style={styles.gridList} cols={2.2}>
{this.state.recommend_user_list.map((user, index) => (
<GridTile
style={{display : user.avator_url ? 'block' : 'none'}}
cols={index}
key={index}
title={user.username}
titleStyle={styles.titleStyle}
subtitle={'level ' + user.level}
titleBackground="linear-gradient(to top, rgba(0,0,0,0.7) 0%,rgba(0,0,0,0.3) 70%,rgba(0,0,0,0) 100%)"
>
<img src={user.avator_url} alt="居然找不到头像" onClick={this.onClickRecommendUser} about={user.id}
style={this.state.recommend_user_list.length > 2 ? null : {width:'100%', height:'auto'}} />
</GridTile>
))}
</GridList>
</div>
<Divider style={{marginTop : '2%'}}/>
<Subheader>Your following's moment</Subheader>
{this.state.moments.map((moment, index) => (
<Paper style={styles.paper} zDepth={1} key={index} >
<ListItem
primaryText={<p>{moment.username} <b>{moment.type.toUpperCase()}</b> {moment.songlist_name}</p>}
secondaryText={moment.time}
leftAvatar={<Avatar src={moment.avator_url} style={{left:'16%', top:'16px'}} size={50} />}
/>
</Paper>
))}
<Divider style={{marginTop : '2%'}}/>
<UploadAvator ref="UploadAvatorDialog" />
</div>
);
}
} |
example/examples/PublicMethodsExample.react.js | Neophy7e/react-bootstrap-typeahead | import React from 'react';
import {Button, ButtonToolbar} from 'react-bootstrap';
import {Typeahead} from '../../src/';
import options from '../../example/exampleData';
/* example-start */
const PublicMethodsExample = React.createClass({
render() {
return (
<div>
<Typeahead
labelKey="name"
multiple
options={options}
placeholder="Choose a state..."
ref={ref => this._typeahead = ref}
selected={options.slice(0, 4)}
/>
<ButtonToolbar style={{marginTop: '10px'}}>
<Button onClick={() => this._typeahead.getInstance().clear()}>
Clear
</Button>
<Button onClick={() => this._typeahead.getInstance().focus()}>
Focus
</Button>
<Button
onClick={() => {
const instance = this._typeahead.getInstance();
instance.focus();
setTimeout(() => instance.blur(), 1000);
}}>
Focus, then blur after 1 second
</Button>
</ButtonToolbar>
</div>
);
},
});
/* example-end */
export default PublicMethodsExample;
|
app/javascript/mastodon/features/ui/components/upload_area.js | anon5r/mastonon | import React from 'react';
import PropTypes from 'prop-types';
import Motion from '../../ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import { FormattedMessage } from 'react-intl';
export default class UploadArea extends React.PureComponent {
static propTypes = {
active: PropTypes.bool,
onClose: PropTypes.func,
};
handleKeyUp = (e) => {
const keyCode = e.keyCode;
if (this.props.active) {
switch(keyCode) {
case 27:
e.preventDefault();
e.stopPropagation();
this.props.onClose();
break;
}
}
}
componentDidMount () {
window.addEventListener('keyup', this.handleKeyUp, false);
}
componentWillUnmount () {
window.removeEventListener('keyup', this.handleKeyUp);
}
render () {
const { active } = this.props;
return (
<Motion defaultStyle={{ backgroundOpacity: 0, backgroundScale: 0.95 }} style={{ backgroundOpacity: spring(active ? 1 : 0, { stiffness: 150, damping: 15 }), backgroundScale: spring(active ? 1 : 0.95, { stiffness: 200, damping: 3 }) }}>
{({ backgroundOpacity, backgroundScale }) => (
<div className='upload-area' style={{ visibility: active ? 'visible' : 'hidden', opacity: backgroundOpacity }}>
<div className='upload-area__drop'>
<div className='upload-area__background' style={{ transform: `scale(${backgroundScale})` }} />
<div className='upload-area__content'><FormattedMessage id='upload_area.title' defaultMessage='Drag & drop to upload' /></div>
</div>
</div>
)}
</Motion>
);
}
}
|
app/containers/LanguageProvider/index.js | carney520/lg-react-boilerplate | /*
*
* LanguageProvider
*
* this component connects the redux state language locale to the
* IntlProvider component and i18n messages (loaded from `app/translations`)
*/
import React from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { IntlProvider } from 'react-intl';
import { makeSelectLocale } from './selectors';
export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render () {
return (
<IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}>
{React.Children.only(this.props.children)}
</IntlProvider>
);
}
}
LanguageProvider.propTypes = {
locale: React.PropTypes.string,
messages: React.PropTypes.object,
children: React.PropTypes.element.isRequired,
};
const mapStateToProps = createSelector(
makeSelectLocale(),
locale => ({ locale })
);
function mapDispatchToProps (dispatch) {
return {
dispatch,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(LanguageProvider);
|
packages/material-ui-icons/src/HomeOutlined.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M12 5.69l5 4.5V18h-2v-6H9v6H7v-7.81l5-4.5M12 3L2 12h3v8h6v-6h2v6h6v-8h3L12 3z" />
, 'HomeOutlined');
|
src/component/game.js | heroinedor/tictactoe | import React from 'react';
import ReactDOM from 'react-dom';
import Board from './board'
import calculateWinner from '../util/func'
export default class Game extends React.Component {
constructor(){
super();
this.state = {
history: [{
squares: Array(9).fill(null)
}],
xIsNext: true,
stepNumber: 0,
};
}
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateWinner(current.squares);
let status;
if (winner){
status= 'Winner: ' + winner;
}else{
status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
}
const moves = history.map((step,move) => {
const desc = move ? 'Move #' + move : 'Game start';
return (
<li key={move}>
<a href="#" onClick={() => this.jumpTo(move)}>{desc}</a>
</li>
);
});
return (
<div className="game">
<div className="game-board">
<Board squares={current.squares} onClick={(i) => this.handleClick(i)}/>
</div>
<div className="game-info">
<div>{status}</div>
<ol>{moves}</ol>
</div>
</div>
);
}
handleClick(i){
const history = this.state.history;
const current = history[history.length - 1];
const squares = current.squares.slice();
if (calculateWinner(squares) || squares[i] ){
return;
}
squares[i] = this.state.xIsNext ? 'X' : 'O';
this.setState({
history: history.concat([{
squares : squares
}]),
xIsNext : !this.state.xIsNext,
stepNumber: history.length,
});
}
jumpTo(step){
this.setState({
xIsNext: (step % 2) ? false: true,
stepNumber: step,
})
}
} |
src/sharedTypes.js | RafalFilipek/just-box | // @flow
import React from 'react';
import { type UnitElement } from './unit';
export type MixedType = string | number | UnitElement;
export type RenderFunc = () => React.Element<*>;
|
spec/javascripts/jsx/gradebook/default_gradebook/components/GradebookMenuSpec.js | djbender/canvas-lms | /*
* Copyright (C) 2017 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import $ from 'jquery'
import {mount} from 'enzyme'
import GradebookMenu from 'jsx/gradebook/default_gradebook/components/GradebookMenu'
QUnit.module('GradebookMenu', {
setup() {
this.wrapper = mount(
<GradebookMenu
variant="DefaultGradebook"
learningMasteryEnabled
courseUrl="http://someUrl/"
navigate={() => {}}
/>
)
},
teardown() {
this.wrapper.unmount()
}
})
test('Gradebook trigger button is present', function() {
equal(
this.wrapper
.find('Button')
.text()
.trim(),
'Gradebook'
)
})
test('#handleIndividualGradebookSelect calls setLocation', function() {
const setLocationStub = sandbox.stub(GradebookMenu.prototype, 'setLocation')
this.wrapper.find('button').simulate('click')
document.querySelector('[data-menu-item-id="individual-gradebook"]').click()
const url = `${
this.wrapper.props().courseUrl
}/gradebook/change_gradebook_version?version=individual`
ok(setLocationStub.withArgs(url).calledOnce)
})
test('#handleGradebookHistorySelect calls setLocation', function() {
const setLocationStub = sandbox.stub(GradebookMenu.prototype, 'setLocation')
this.wrapper.find('button').simulate('click')
document.querySelector('[data-menu-item-id="gradebook-history"]').click()
const url = `${this.wrapper.props().courseUrl}/gradebook/history`
ok(setLocationStub.withArgs(url).calledOnce)
})
QUnit.module('Variant DefaultGradebook with Learning Mastery Enabled', {
setup() {
this.navigateStub = sinon.stub()
this.wrapper = mount(
<GradebookMenu
variant="DefaultGradebook"
learningMasteryEnabled
courseUrl="http://someUrl/"
navigate={this.navigateStub}
/>
)
this.wrapper.find('button').simulate('click')
this.menuItems = $('[role="menu"]:contains("Learning Mastery…")')[0].children
},
teardown() {
this.wrapper.unmount()
}
})
test('handleDefaultGradbookLearningMasterySelect calls navigate', function() {
document.querySelector('[data-menu-item-id="learning-mastery"]').click()
ok(this.navigateStub.withArgs('tab-outcome', {trigger: true}).calledOnce)
})
test('Learning Mastery Menu Item is first in the Menu', function() {
equal(this.menuItems[0].textContent.trim(), 'Learning Mastery…')
})
test('Individual Gradebook Menu Item is second in the Menu', function() {
equal(this.menuItems[1].textContent.trim(), 'Individual View…')
})
test('Menu Item Separator is third in the Menu', function() {
equal(this.menuItems[2].firstElementChild.getAttribute('role'), 'presentation')
})
test('Gradebook History Menu Item is fourth in the Menu', function() {
equal(this.menuItems[3].textContent.trim(), 'Gradebook History…')
})
QUnit.module('Variant DefaultGradebook with Learning Mastery Disabled', {
setup() {
this.wrapper = mount(
<GradebookMenu
variant="DefaultGradebook"
learningMasteryEnabled={false}
courseUrl="http://someUrl/"
navigate={() => {}}
/>
)
this.wrapper.find('button').simulate('click')
this.menuItems = $('[role="menu"]:contains("Individual View…")')[0].children
},
teardown() {
this.wrapper.unmount()
}
})
test('Individual Gradebook Menu Item is first in the Menu', function() {
equal(this.menuItems[0].textContent.trim(), 'Individual View…')
})
test('Menu Item Separator is second in the Menu', function() {
equal(this.menuItems[1].firstElementChild.getAttribute('role'), 'presentation')
})
test('Gradebook History Menu Item is second in the Menu', function() {
equal(this.menuItems[2].textContent.trim(), 'Gradebook History…')
})
QUnit.module('Variant DefaultGradebookLearningMastery with Learning Mastery Enabled', {
setup() {
this.navigateStub = sinon.stub()
this.wrapper = mount(
<GradebookMenu
variant="DefaultGradebookLearningMastery"
learningMasteryEnabled
courseUrl="http://someUrl/"
navigate={this.navigateStub}
/>
)
this.wrapper.find('button').simulate('click')
this.menuItems = $('[role="menu"]:contains("Gradebook…")')[0].children
},
teardown() {
this.wrapper.unmount()
}
})
test('handleDefaultGradbookSelect calls navigate', function() {
document.querySelector('[data-menu-item-id="default-gradebook"]').click()
ok(this.navigateStub.withArgs('tab-assignment', {trigger: true}).calledOnce)
})
test('Learning Mastery trigger button is present', function() {
equal(
this.wrapper
.find('Button')
.text()
.trim(),
'Learning Mastery'
)
})
test('DefaultGradebook Menu Item is first in the Menu', function() {
equal(this.menuItems[0].textContent.trim(), 'Gradebook…')
})
test('Individual Gradebook Menu Item is second in the Menu', function() {
equal(this.menuItems[1].textContent.trim(), 'Individual View…')
})
test('Menu Item Separator is third in the Menu', function() {
equal(this.menuItems[2].firstElementChild.getAttribute('role'), 'presentation')
})
test('Gradebook History Menu Item is fourth in the Menu', function() {
equal(this.menuItems[3].textContent.trim(), 'Gradebook History…')
})
|
ajax/libs/yui/3.10.2/simpleyui/simpleyui-debug.js | the-destro/cdnjs | /**
The YUI module contains the components required for building the YUI seed file.
This includes the script loading mechanism, a simple queue, and the core
utilities for the library.
@module yui
@main yui
@submodule yui-base
**/
/*jshint eqeqeq: false*/
if (typeof YUI != 'undefined') {
YUI._YUI = YUI;
}
/**
The YUI global namespace object. This is the constructor for all YUI instances.
This is a self-instantiable factory function, meaning you don't need to precede
it with the `new` operator. You can invoke it directly like this:
YUI().use('*', function (Y) {
// Y is a new YUI instance.
});
But it also works like this:
var Y = YUI();
The `YUI` constructor accepts an optional config object, like this:
YUI({
debug: true,
combine: false
}).use('node', function (Y) {
// Y.Node is ready to use.
});
See the API docs for the <a href="config.html">Config</a> class for the complete
list of supported configuration properties accepted by the YUI constuctor.
If a global `YUI` object is already defined, the existing YUI object will not be
overwritten, to ensure that defined namespaces are preserved.
Each YUI instance has full custom event support, but only if the event system is
available.
@class YUI
@uses EventTarget
@constructor
@global
@param {Object} [config]* Zero or more optional configuration objects. Config
values are stored in the `Y.config` property. See the
<a href="config.html">Config</a> docs for the list of supported properties.
**/
/*global YUI*/
/*global YUI_config*/
var YUI = function() {
var i = 0,
Y = this,
args = arguments,
l = args.length,
instanceOf = function(o, type) {
return (o && o.hasOwnProperty && (o instanceof type));
},
gconf = (typeof YUI_config !== 'undefined') && YUI_config;
if (!(instanceOf(Y, YUI))) {
Y = new YUI();
} else {
// set up the core environment
Y._init();
/**
Master configuration that might span multiple contexts in a non-
browser environment. It is applied first to all instances in all
contexts.
@example
YUI.GlobalConfig = {
filter: 'debug'
};
YUI().use('node', function (Y) {
// debug files used here
});
YUI({
filter: 'min'
}).use('node', function (Y) {
// min files used here
});
@property {Object} GlobalConfig
@global
@static
**/
if (YUI.GlobalConfig) {
Y.applyConfig(YUI.GlobalConfig);
}
/**
Page-level config applied to all YUI instances created on the
current page. This is applied after `YUI.GlobalConfig` and before
any instance-level configuration.
@example
// Single global var to include before YUI seed file
YUI_config = {
filter: 'debug'
};
YUI().use('node', function (Y) {
// debug files used here
});
YUI({
filter: 'min'
}).use('node', function (Y) {
// min files used here
});
@property {Object} YUI_config
@global
**/
if (gconf) {
Y.applyConfig(gconf);
}
// bind the specified additional modules for this instance
if (!l) {
Y._setup();
}
}
if (l) {
// Each instance can accept one or more configuration objects.
// These are applied after YUI.GlobalConfig and YUI_Config,
// overriding values set in those config files if there is a
// matching property.
for (; i < l; i++) {
Y.applyConfig(args[i]);
}
Y._setup();
}
Y.instanceOf = instanceOf;
return Y;
};
(function() {
var proto, prop,
VERSION = '@VERSION@',
PERIOD = '.',
BASE = 'http://yui.yahooapis.com/',
/*
These CSS class names can't be generated by
getClassName since it is not available at the
time they are being used.
*/
DOC_LABEL = 'yui3-js-enabled',
CSS_STAMP_EL = 'yui3-css-stamp',
NOOP = function() {},
SLICE = Array.prototype.slice,
APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo
'io.xdrResponse': 1, // can call. this should
'SWF.eventHandler': 1 }, // be done at build time
hasWin = (typeof window != 'undefined'),
win = (hasWin) ? window : null,
doc = (hasWin) ? win.document : null,
docEl = doc && doc.documentElement,
docClass = docEl && docEl.className,
instances = {},
time = new Date().getTime(),
add = function(el, type, fn, capture) {
if (el && el.addEventListener) {
el.addEventListener(type, fn, capture);
} else if (el && el.attachEvent) {
el.attachEvent('on' + type, fn);
}
},
remove = function(el, type, fn, capture) {
if (el && el.removeEventListener) {
// this can throw an uncaught exception in FF
try {
el.removeEventListener(type, fn, capture);
} catch (ex) {}
} else if (el && el.detachEvent) {
el.detachEvent('on' + type, fn);
}
},
handleLoad = function() {
YUI.Env.windowLoaded = true;
YUI.Env.DOMReady = true;
if (hasWin) {
remove(window, 'load', handleLoad);
}
},
getLoader = function(Y, o) {
var loader = Y.Env._loader,
lCore = [ 'loader-base' ],
G_ENV = YUI.Env,
mods = G_ENV.mods;
if (loader) {
//loader._config(Y.config);
loader.ignoreRegistered = false;
loader.onEnd = null;
loader.data = null;
loader.required = [];
loader.loadType = null;
} else {
loader = new Y.Loader(Y.config);
Y.Env._loader = loader;
}
if (mods && mods.loader) {
lCore = [].concat(lCore, YUI.Env.loaderExtras);
}
YUI.Env.core = Y.Array.dedupe([].concat(YUI.Env.core, lCore));
return loader;
},
clobber = function(r, s) {
for (var i in s) {
if (s.hasOwnProperty(i)) {
r[i] = s[i];
}
}
},
ALREADY_DONE = { success: true };
// Stamp the documentElement (HTML) with a class of "yui-loaded" to
// enable styles that need to key off of JS being enabled.
if (docEl && docClass.indexOf(DOC_LABEL) == -1) {
if (docClass) {
docClass += ' ';
}
docClass += DOC_LABEL;
docEl.className = docClass;
}
if (VERSION.indexOf('@') > -1) {
VERSION = '3.5.0'; // dev time hack for cdn test
}
proto = {
/**
Applies a new configuration object to the config of this YUI instance. This
will merge new group/module definitions, and will also update the loader
cache if necessary. Updating `Y.config` directly will not update the cache.
@method applyConfig
@param {Object} o the configuration object.
@since 3.2.0
**/
applyConfig: function(o) {
o = o || NOOP;
var attr,
name,
// detail,
config = this.config,
mods = config.modules,
groups = config.groups,
aliases = config.aliases,
loader = this.Env._loader;
for (name in o) {
if (o.hasOwnProperty(name)) {
attr = o[name];
if (mods && name == 'modules') {
clobber(mods, attr);
} else if (aliases && name == 'aliases') {
clobber(aliases, attr);
} else if (groups && name == 'groups') {
clobber(groups, attr);
} else if (name == 'win') {
config[name] = (attr && attr.contentWindow) || attr;
config.doc = config[name] ? config[name].document : null;
} else if (name == '_yuid') {
// preserve the guid
} else {
config[name] = attr;
}
}
}
if (loader) {
loader._config(o);
}
},
/**
Old way to apply a config to this instance (calls `applyConfig` under the
hood).
@private
@method _config
@param {Object} o The config to apply
**/
_config: function(o) {
this.applyConfig(o);
},
/**
Initializes this YUI instance.
@private
@method _init
**/
_init: function() {
var filter, el,
Y = this,
G_ENV = YUI.Env,
Env = Y.Env,
prop;
/**
The version number of this YUI instance.
This value is typically updated by a script when a YUI release is built,
so it may not reflect the correct version number when YUI is run from
the development source tree.
@property {String} version
**/
Y.version = VERSION;
if (!Env) {
Y.Env = {
core: ['get', 'features', 'intl-base', 'yui-log', 'yui-later'],
loaderExtras: ['loader-rollup', 'loader-yui3'],
mods: {}, // flat module map
versions: {}, // version module map
base: BASE,
cdn: BASE + VERSION + '/build/',
// bootstrapped: false,
_idx: 0,
_used: {},
_attached: {},
_missed: [],
_yidx: 0,
_uidx: 0,
_guidp: 'y',
_loaded: {},
// serviced: {},
// Regex in English:
// I'll start at the \b(simpleyui).
// 1. Look in the test string for "simpleyui" or "yui" or
// "yui-base" or "yui-davglass" or "yui-foobar" that comes after a word break. That is, it
// can't match "foyui" or "i_heart_simpleyui". This can be anywhere in the string.
// 2. After #1 must come a forward slash followed by the string matched in #1, so
// "yui-base/yui-base" or "simpleyui/simpleyui" or "yui-pants/yui-pants".
// 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min",
// so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt".
// 4. This is followed by ".js", so "yui/yui.js", "simpleyui/simpleyui-min.js"
// 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string,
// then capture the junk between the LAST "&" and the string in 1-4. So
// "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-davglass/yui-davglass.js"
// will capture "3.3.0/build/"
//
// Regex Exploded:
// (?:\? Find a ?
// (?:[^&]*&) followed by 0..n characters followed by an &
// * in fact, find as many sets of characters followed by a & as you can
// ([^&]*) capture the stuff after the last & in \1
// )? but it's ok if all this ?junk&more_junk stuff isn't even there
// \b(simpleyui| after a word break find either the string "simpleyui" or
// yui(?:-\w+)? the string "yui" optionally followed by a -, then more characters
// ) and store the simpleyui or yui-* string in \2
// \/\2 then comes a / followed by the simpleyui or yui-* string in \2
// (?:-(min|debug))? optionally followed by "-min" or "-debug"
// .js and ending in ".js"
_BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(simpleyui|yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/,
parseBasePath: function(src, pattern) {
var match = src.match(pattern),
path, filter;
if (match) {
path = RegExp.leftContext || src.slice(0, src.indexOf(match[0]));
// this is to set up the path to the loader. The file
// filter for loader should match the yui include.
filter = match[3];
// extract correct path for mixed combo urls
// http://yuilibrary.com/projects/yui3/ticket/2528423
if (match[1]) {
path += '?' + match[1];
}
path = {
filter: filter,
path: path
};
}
return path;
},
getBase: G_ENV && G_ENV.getBase ||
function(pattern) {
var nodes = (doc && doc.getElementsByTagName('script')) || [],
path = Env.cdn, parsed,
i, len, src;
for (i = 0, len = nodes.length; i < len; ++i) {
src = nodes[i].src;
if (src) {
parsed = Y.Env.parseBasePath(src, pattern);
if (parsed) {
filter = parsed.filter;
path = parsed.path;
break;
}
}
}
// use CDN default
return path;
}
};
Env = Y.Env;
Env._loaded[VERSION] = {};
if (G_ENV && Y !== YUI) {
Env._yidx = ++G_ENV._yidx;
Env._guidp = ('yui_' + VERSION + '_' +
Env._yidx + '_' + time).replace(/[^a-z0-9_]+/g, '_');
} else if (YUI._YUI) {
G_ENV = YUI._YUI.Env;
Env._yidx += G_ENV._yidx;
Env._uidx += G_ENV._uidx;
for (prop in G_ENV) {
if (!(prop in Env)) {
Env[prop] = G_ENV[prop];
}
}
delete YUI._YUI;
}
Y.id = Y.stamp(Y);
instances[Y.id] = Y;
}
Y.constructor = YUI;
// configuration defaults
Y.config = Y.config || {
bootstrap: true,
cacheUse: true,
debug: true,
doc: doc,
fetchCSS: true,
throwFail: true,
useBrowserConsole: true,
useNativeES5: true,
win: win,
global: Function('return this')()
};
//Register the CSS stamp element
if (doc && !doc.getElementById(CSS_STAMP_EL)) {
el = doc.createElement('div');
el.innerHTML = '<div id="' + CSS_STAMP_EL + '" style="position: absolute !important; visibility: hidden !important"></div>';
YUI.Env.cssStampEl = el.firstChild;
if (doc.body) {
doc.body.appendChild(YUI.Env.cssStampEl);
} else {
docEl.insertBefore(YUI.Env.cssStampEl, docEl.firstChild);
}
} else if (doc && doc.getElementById(CSS_STAMP_EL) && !YUI.Env.cssStampEl) {
YUI.Env.cssStampEl = doc.getElementById(CSS_STAMP_EL);
}
Y.config.lang = Y.config.lang || 'en-US';
Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE);
if (!filter || (!('mindebug').indexOf(filter))) {
filter = 'min';
}
filter = (filter) ? '-' + filter : filter;
Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js';
},
/**
Finishes the instance setup. Attaches whatever YUI modules were defined
at the time that this instance was created.
@method _setup
@private
**/
_setup: function() {
var i, Y = this,
core = [],
mods = YUI.Env.mods,
extras = Y.config.core || [].concat(YUI.Env.core); //Clone it..
for (i = 0; i < extras.length; i++) {
if (mods[extras[i]]) {
core.push(extras[i]);
}
}
Y._attach(['yui-base']);
Y._attach(core);
if (Y.Loader) {
getLoader(Y);
}
// Y.log(Y.id + ' initialized', 'info', 'yui');
},
/**
Executes the named method on the specified YUI instance if that method is
whitelisted.
@method applyTo
@param {String} id YUI instance id.
@param {String} method Name of the method to execute. For example:
'Object.keys'.
@param {Array} args Arguments to apply to the method.
@return {Mixed} Return value from the applied method, or `null` if the
specified instance was not found or the method was not whitelisted.
**/
applyTo: function(id, method, args) {
if (!(method in APPLY_TO_AUTH)) {
this.log(method + ': applyTo not allowed', 'warn', 'yui');
return null;
}
var instance = instances[id], nest, m, i;
if (instance) {
nest = method.split('.');
m = instance;
for (i = 0; i < nest.length; i = i + 1) {
m = m[nest[i]];
if (!m) {
this.log('applyTo not found: ' + method, 'warn', 'yui');
}
}
return m && m.apply(instance, args);
}
return null;
},
/**
Registers a YUI module and makes it available for use in a `YUI().use()` call or
as a dependency for other modules.
The easiest way to create a first-class YUI module is to use
<a href="http://yui.github.com/shifter/">Shifter</a>, the YUI component build
tool.
Shifter will automatically wrap your module code in a `YUI.add()` call along
with any configuration info required for the module.
@example
YUI.add('davglass', function (Y) {
Y.davglass = function () {
Y.log('Dav was here!');
};
}, '3.4.0', {
requires: ['harley-davidson', 'mt-dew']
});
@method add
@param {String} name Module name.
@param {Function} fn Function containing module code. This function will be
executed whenever the module is attached to a specific YUI instance.
@param {YUI} fn.Y The YUI instance to which this module is attached.
@param {String} fn.name Name of the module
@param {String} version Module version number. This is currently used only for
informational purposes, and is not used internally by YUI.
@param {Object} [config] Module config.
@param {Array} [config.requires] Array of other module names that must be
attached before this module can be attached.
@param {Array} [config.optional] Array of optional module names that should
be attached before this module is attached if they've already been
loaded. If the `loadOptional` YUI option is `true`, optional modules
that have not yet been loaded will be loaded just as if they were hard
requirements.
@param {Array} [config.use] Array of module names that are included within
or otherwise provided by this module, and which should be attached
automatically when this module is attached. This makes it possible to
create "virtual rollup" modules that simply attach a collection of other
modules or submodules.
@return {YUI} This YUI instance.
**/
add: function(name, fn, version, details) {
details = details || {};
var env = YUI.Env,
mod = {
name: name,
fn: fn,
version: version,
details: details
},
//Instance hash so we don't apply it to the same instance twice
applied = {},
loader, inst,
i, versions = env.versions;
env.mods[name] = mod;
versions[version] = versions[version] || {};
versions[version][name] = mod;
for (i in instances) {
if (instances.hasOwnProperty(i)) {
inst = instances[i];
if (!applied[inst.id]) {
applied[inst.id] = true;
loader = inst.Env._loader;
if (loader) {
if (!loader.moduleInfo[name] || loader.moduleInfo[name].temp) {
loader.addModule(details, name);
}
}
}
}
}
return this;
},
/**
Executes the callback function associated with each required module,
attaching the module to this YUI instance.
@method _attach
@param {Array} r The array of modules to attach
@param {Boolean} [moot=false] If `true`, don't throw a warning if the module
is not attached.
@private
**/
_attach: function(r, moot) {
var i, name, mod, details, req, use, after,
mods = YUI.Env.mods,
aliases = YUI.Env.aliases,
Y = this, j,
cache = YUI.Env._renderedMods,
loader = Y.Env._loader,
done = Y.Env._attached,
len = r.length, loader, def, go,
c = [];
//Check for conditional modules (in a second+ instance) and add their requirements
//TODO I hate this entire method, it needs to be fixed ASAP (3.5.0) ^davglass
for (i = 0; i < len; i++) {
name = r[i];
mod = mods[name];
c.push(name);
if (loader && loader.conditions[name]) {
for (j in loader.conditions[name]) {
if (loader.conditions[name].hasOwnProperty(j)) {
def = loader.conditions[name][j];
go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y)));
if (go) {
c.push(def.name);
}
}
}
}
}
r = c;
len = r.length;
for (i = 0; i < len; i++) {
if (!done[r[i]]) {
name = r[i];
mod = mods[name];
if (aliases && aliases[name] && !mod) {
Y._attach(aliases[name]);
continue;
}
if (!mod) {
if (loader && loader.moduleInfo[name]) {
mod = loader.moduleInfo[name];
moot = true;
}
// Y.log('no js def for: ' + name, 'info', 'yui');
//if (!loader || !loader.moduleInfo[name]) {
//if ((!loader || !loader.moduleInfo[name]) && !moot) {
if (!moot && name) {
if ((name.indexOf('skin-') === -1) && (name.indexOf('css') === -1)) {
Y.Env._missed.push(name);
Y.Env._missed = Y.Array.dedupe(Y.Env._missed);
Y.message('NOT loaded: ' + name, 'warn', 'yui');
}
}
} else {
done[name] = true;
//Don't like this, but in case a mod was asked for once, then we fetch it
//We need to remove it from the missed list ^davglass
for (j = 0; j < Y.Env._missed.length; j++) {
if (Y.Env._missed[j] === name) {
Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui');
Y.Env._missed.splice(j, 1);
}
}
/*
If it's a temp module, we need to redo it's requirements if it's already loaded
since it may have been loaded by another instance and it's dependencies might
have been redefined inside the fetched file.
*/
if (loader && cache && cache[name] && cache[name].temp) {
loader.getRequires(cache[name]);
req = [];
for (j in loader.moduleInfo[name].expanded_map) {
if (loader.moduleInfo[name].expanded_map.hasOwnProperty(j)) {
req.push(j);
}
}
Y._attach(req);
}
details = mod.details;
req = details.requires;
use = details.use;
after = details.after;
//Force Intl load if there is a language (Loader logic) @todo fix this shit
if (details.lang) {
req = req || [];
req.unshift('intl');
}
if (req) {
for (j = 0; j < req.length; j++) {
if (!done[req[j]]) {
if (!Y._attach(req)) {
return false;
}
break;
}
}
}
if (after) {
for (j = 0; j < after.length; j++) {
if (!done[after[j]]) {
if (!Y._attach(after, true)) {
return false;
}
break;
}
}
}
if (mod.fn) {
if (Y.config.throwFail) {
mod.fn(Y, name);
} else {
try {
mod.fn(Y, name);
} catch (e) {
Y.error('Attach error: ' + name, e, name);
return false;
}
}
}
if (use) {
for (j = 0; j < use.length; j++) {
if (!done[use[j]]) {
if (!Y._attach(use)) {
return false;
}
break;
}
}
}
}
}
}
return true;
},
/**
Delays the `use` callback until another event has taken place such as
`window.onload`, `domready`, `contentready`, or `available`.
@private
@method _delayCallback
@param {Function} cb The original `use` callback.
@param {String|Object} until Either an event name ('load', 'domready', etc.)
or an object containing event/args keys for contentready/available.
@return {Function}
**/
_delayCallback: function(cb, until) {
var Y = this,
mod = ['event-base'];
until = (Y.Lang.isObject(until) ? until : { event: until });
if (until.event === 'load') {
mod.push('event-synthetic');
}
Y.log('Delaying use callback until: ' + until.event, 'info', 'yui');
return function() {
Y.log('Use callback fired, waiting on delay', 'info', 'yui');
var args = arguments;
Y._use(mod, function() {
Y.log('Delayed use wrapper callback after dependencies', 'info', 'yui');
Y.on(until.event, function() {
args[1].delayUntil = until.event;
Y.log('Delayed use callback done after ' + until.event, 'info', 'yui');
cb.apply(Y, args);
}, until.args);
});
};
},
/**
Attaches one or more modules to this YUI instance. When this is executed,
the requirements of the desired modules are analyzed, and one of several
things can happen:
* All required modules have already been loaded, and just need to be
attached to this YUI instance. In this case, the `use()` callback will
be executed synchronously after the modules are attached.
* One or more modules have not yet been loaded, or the Get utility is not
available, or the `bootstrap` config option is `false`. In this case,
a warning is issued indicating that modules are missing, but all
available modules will still be attached and the `use()` callback will
be executed synchronously.
* One or more modules are missing and the Loader is not available but the
Get utility is, and `bootstrap` is not `false`. In this case, the Get
utility will be used to load the Loader, and we will then proceed to
the following state:
* One or more modules are missing and the Loader is available. In this
case, the Loader will be used to resolve the dependency tree for the
missing modules and load them and their dependencies. When the Loader is
finished loading modules, the `use()` callback will be executed
asynchronously.
@example
// Loads and attaches dd and its dependencies.
YUI().use('dd', function (Y) {
// ...
});
// Loads and attaches dd and node as well as all of their dependencies.
YUI().use(['dd', 'node'], function (Y) {
// ...
});
// Attaches all modules that have already been loaded.
YUI().use('*', function (Y) {
// ...
});
// Attaches a gallery module.
YUI().use('gallery-yql', function (Y) {
// ...
});
// Attaches a YUI 2in3 module.
YUI().use('yui2-datatable', function (Y) {
// ...
});
@method use
@param {String|Array} modules* One or more module names to attach.
@param {Function} [callback] Callback function to be executed once all
specified modules and their dependencies have been attached.
@param {YUI} callback.Y The YUI instance created for this sandbox.
@param {Object} callback.status Object containing `success`, `msg` and
`data` properties.
@chainable
**/
use: function() {
var args = SLICE.call(arguments, 0),
callback = args[args.length - 1],
Y = this,
i = 0,
name,
Env = Y.Env,
provisioned = true;
// The last argument supplied to use can be a load complete callback
if (Y.Lang.isFunction(callback)) {
args.pop();
if (Y.config.delayUntil) {
callback = Y._delayCallback(callback, Y.config.delayUntil);
}
} else {
callback = null;
}
if (Y.Lang.isArray(args[0])) {
args = args[0];
}
if (Y.config.cacheUse) {
while ((name = args[i++])) {
if (!Env._attached[name]) {
provisioned = false;
break;
}
}
if (provisioned) {
if (args.length) {
Y.log('already provisioned: ' + args, 'info', 'yui');
}
Y._notify(callback, ALREADY_DONE, args);
return Y;
}
}
if (Y._loading) {
Y._useQueue = Y._useQueue || new Y.Queue();
Y._useQueue.add([args, callback]);
} else {
Y._use(args, function(Y, response) {
Y._notify(callback, response, args);
});
}
return Y;
},
/**
Handles Loader notifications about attachment/load errors.
@method _notify
@param {Function} callback Callback to pass to `Y.config.loadErrorFn`.
@param {Object} response Response returned from Loader.
@param {Array} args Arguments passed from Loader.
@private
**/
_notify: function(callback, response, args) {
if (!response.success && this.config.loadErrorFn) {
this.config.loadErrorFn.call(this, this, callback, response, args);
} else if (callback) {
if (this.Env._missed && this.Env._missed.length) {
response.msg = 'Missing modules: ' + this.Env._missed.join();
response.success = false;
}
if (this.config.throwFail) {
callback(this, response);
} else {
try {
callback(this, response);
} catch (e) {
this.error('use callback error', e, args);
}
}
}
},
/**
Called from the `use` method queue to ensure that only one set of loading
logic is performed at a time.
@method _use
@param {String} args* One or more modules to attach.
@param {Function} [callback] Function to call once all required modules have
been attached.
@private
**/
_use: function(args, callback) {
if (!this.Array) {
this._attach(['yui-base']);
}
var len, loader, handleBoot,
Y = this,
G_ENV = YUI.Env,
mods = G_ENV.mods,
Env = Y.Env,
used = Env._used,
aliases = G_ENV.aliases,
queue = G_ENV._loaderQueue,
firstArg = args[0],
YArray = Y.Array,
config = Y.config,
boot = config.bootstrap,
missing = [],
i,
r = [],
ret = true,
fetchCSS = config.fetchCSS,
process = function(names, skip) {
var i = 0, a = [], name, len, m, req, use;
if (!names.length) {
return;
}
if (aliases) {
len = names.length;
for (i = 0; i < len; i++) {
if (aliases[names[i]] && !mods[names[i]]) {
a = [].concat(a, aliases[names[i]]);
} else {
a.push(names[i]);
}
}
names = a;
}
len = names.length;
for (i = 0; i < len; i++) {
name = names[i];
if (!skip) {
r.push(name);
}
// only attach a module once
if (used[name]) {
continue;
}
m = mods[name];
req = null;
use = null;
if (m) {
used[name] = true;
req = m.details.requires;
use = m.details.use;
} else {
// CSS files don't register themselves, see if it has
// been loaded
if (!G_ENV._loaded[VERSION][name]) {
missing.push(name);
} else {
used[name] = true; // probably css
}
}
// make sure requirements are attached
if (req && req.length) {
process(req);
}
// make sure we grab the submodule dependencies too
if (use && use.length) {
process(use, 1);
}
}
},
handleLoader = function(fromLoader) {
var response = fromLoader || {
success: true,
msg: 'not dynamic'
},
redo, origMissing,
ret = true,
data = response.data;
Y._loading = false;
if (data) {
origMissing = missing;
missing = [];
r = [];
process(data);
redo = missing.length;
if (redo) {
if ([].concat(missing).sort().join() ==
origMissing.sort().join()) {
redo = false;
}
}
}
if (redo && data) {
Y._loading = true;
Y._use(missing, function() {
Y.log('Nested use callback: ' + data, 'info', 'yui');
if (Y._attach(data)) {
Y._notify(callback, response, data);
}
});
} else {
if (data) {
// Y.log('attaching from loader: ' + data, 'info', 'yui');
ret = Y._attach(data);
}
if (ret) {
Y._notify(callback, response, args);
}
}
if (Y._useQueue && Y._useQueue.size() && !Y._loading) {
Y._use.apply(Y, Y._useQueue.next());
}
};
// Y.log(Y.id + ': use called: ' + a + ' :: ' + callback, 'info', 'yui');
// YUI().use('*'); // bind everything available
if (firstArg === '*') {
args = [];
for (i in mods) {
if (mods.hasOwnProperty(i)) {
args.push(i);
}
}
ret = Y._attach(args);
if (ret) {
handleLoader();
}
return Y;
}
if ((mods.loader || mods['loader-base']) && !Y.Loader) {
Y.log('Loader was found in meta, but it is not attached. Attaching..', 'info', 'yui');
Y._attach(['loader' + ((!mods.loader) ? '-base' : '')]);
}
// Y.log('before loader requirements: ' + args, 'info', 'yui');
// use loader to expand dependencies and sort the
// requirements if it is available.
if (boot && Y.Loader && args.length) {
Y.log('Using loader to expand dependencies', 'info', 'yui');
loader = getLoader(Y);
loader.require(args);
loader.ignoreRegistered = true;
loader._boot = true;
loader.calculate(null, (fetchCSS) ? null : 'js');
args = loader.sorted;
loader._boot = false;
}
process(args);
len = missing.length;
if (len) {
missing = YArray.dedupe(missing);
len = missing.length;
Y.log('Modules missing: ' + missing + ', ' + missing.length, 'info', 'yui');
}
// dynamic load
if (boot && len && Y.Loader) {
// Y.log('Using loader to fetch missing deps: ' + missing, 'info', 'yui');
Y.log('Using Loader', 'info', 'yui');
Y._loading = true;
loader = getLoader(Y);
loader.onEnd = handleLoader;
loader.context = Y;
loader.data = args;
loader.ignoreRegistered = false;
loader.require(missing);
loader.insert(null, (fetchCSS) ? null : 'js');
} else if (boot && len && Y.Get && !Env.bootstrapped) {
Y._loading = true;
handleBoot = function() {
Y._loading = false;
queue.running = false;
Env.bootstrapped = true;
G_ENV._bootstrapping = false;
if (Y._attach(['loader'])) {
Y._use(args, callback);
}
};
if (G_ENV._bootstrapping) {
Y.log('Waiting for loader', 'info', 'yui');
queue.add(handleBoot);
} else {
G_ENV._bootstrapping = true;
Y.log('Fetching loader: ' + config.base + config.loaderPath, 'info', 'yui');
Y.Get.script(config.base + config.loaderPath, {
onEnd: handleBoot
});
}
} else {
Y.log('Attaching available dependencies: ' + args, 'info', 'yui');
ret = Y._attach(args);
if (ret) {
handleLoader();
}
}
return Y;
},
/**
Utility method for safely creating namespaces if they don't already exist.
May be called statically on the YUI global object or as a method on a YUI
instance.
When called statically, a namespace will be created on the YUI global
object:
// Create `YUI.your.namespace.here` as nested objects, preserving any
// objects that already exist instead of overwriting them.
YUI.namespace('your.namespace.here');
When called as a method on a YUI instance, a namespace will be created on
that instance:
// Creates `Y.property.package`.
Y.namespace('property.package');
Dots in the input string cause `namespace` to create nested objects for each
token. If any part of the requested namespace already exists, the current
object will be left in place and will not be overwritten. This allows
multiple calls to `namespace` to preserve existing namespaced properties.
If the first token in the namespace string is "YAHOO", that token is
discarded. This is legacy behavior for backwards compatibility with YUI 2.
Be careful with namespace tokens. Reserved words may work in some browsers
and not others. For instance, the following will fail in some browsers
because the supported version of JavaScript reserves the word "long":
Y.namespace('really.long.nested.namespace');
Note: If you pass multiple arguments to create multiple namespaces, only the
last one created is returned from this function.
@method namespace
@param {String} namespace* One or more namespaces to create.
@return {Object} Reference to the last namespace object created.
**/
namespace: function() {
var a = arguments, o, i = 0, j, d, arg;
for (; i < a.length; i++) {
o = this; //Reset base object per argument or it will get reused from the last
arg = a[i];
if (arg.indexOf(PERIOD) > -1) { //Skip this if no "." is present
d = arg.split(PERIOD);
for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) {
o[d[j]] = o[d[j]] || {};
o = o[d[j]];
}
} else {
o[arg] = o[arg] || {};
o = o[arg]; //Reset base object to the new object so it's returned
}
}
return o;
},
// this is replaced if the log module is included
log: NOOP,
message: NOOP,
// this is replaced if the dump module is included
dump: function (o) { return ''+o; },
/**
Reports an error.
The reporting mechanism is controlled by the `throwFail` configuration
attribute. If `throwFail` is falsy, the message is logged. If `throwFail` is
truthy, a JS exception is thrown.
If an `errorFn` is specified in the config it must return `true` to indicate
that the exception was handled and keep it from being thrown.
@method error
@param {String} msg Error message.
@param {Error|String} [e] JavaScript error object or an error string.
@param {String} [src] Source of the error (such as the name of the module in
which the error occurred).
@chainable
**/
error: function(msg, e, src) {
//TODO Add check for window.onerror here
var Y = this, ret;
if (Y.config.errorFn) {
ret = Y.config.errorFn.apply(Y, arguments);
}
if (!ret) {
throw (e || new Error(msg));
} else {
Y.message(msg, 'error', ''+src); // don't scrub this one
}
return Y;
},
/**
Generates an id string that is unique among all YUI instances in this
execution context.
@method guid
@param {String} [pre] Prefix.
@return {String} Unique id.
**/
guid: function(pre) {
var id = this.Env._guidp + '_' + (++this.Env._uidx);
return (pre) ? (pre + id) : id;
},
/**
Returns a unique id associated with the given object and (if *readOnly* is
falsy) stamps the object with that id so it can be identified in the future.
Stamping an object involves adding a `_yuid` property to it that contains
the object's id. One exception to this is that in Internet Explorer, DOM
nodes have a `uniqueID` property that contains a browser-generated unique
id, which will be used instead of a YUI-generated id when available.
@method stamp
@param {Object} o Object to stamp.
@param {Boolean} readOnly If truthy and the given object has not already
been stamped, the object will not be modified and `null` will be
returned.
@return {String} Object's unique id, or `null` if *readOnly* was truthy and
the given object was not already stamped.
**/
stamp: function(o, readOnly) {
var uid;
if (!o) {
return o;
}
// IE generates its own unique ID for dom nodes
// The uniqueID property of a document node returns a new ID
if (o.uniqueID && o.nodeType && o.nodeType !== 9) {
uid = o.uniqueID;
} else {
uid = (typeof o === 'string') ? o : o._yuid;
}
if (!uid) {
uid = this.guid();
if (!readOnly) {
try {
o._yuid = uid;
} catch (e) {
uid = null;
}
}
}
return uid;
},
/**
Destroys this YUI instance.
@method destroy
@since 3.3.0
**/
destroy: function() {
var Y = this;
if (Y.Event) {
Y.Event._unload();
}
delete instances[Y.id];
delete Y.Env;
delete Y.config;
}
/**
Safe `instanceof` wrapper that works around a memory leak in IE when the
object being tested is `window` or `document`.
Unless you are testing objects that may be `window` or `document`, you
should use the native `instanceof` operator instead of this method.
@method instanceOf
@param {Object} o Object to check.
@param {Object} type Class to check against.
@since 3.3.0
**/
};
YUI.prototype = proto;
// inheritance utilities are not available yet
for (prop in proto) {
if (proto.hasOwnProperty(prop)) {
YUI[prop] = proto[prop];
}
}
/**
Applies a configuration to all YUI instances in this execution context.
The main use case for this method is in "mashups" where several third-party
scripts need to write to a global YUI config, but cannot share a single
centrally-managed config object. This way they can all call
`YUI.applyConfig({})` instead of overwriting the single global config.
@example
YUI.applyConfig({
modules: {
davglass: {
fullpath: './davglass.js'
}
}
});
YUI.applyConfig({
modules: {
foo: {
fullpath: './foo.js'
}
}
});
YUI().use('davglass', function (Y) {
// Module davglass will be available here.
});
@method applyConfig
@param {Object} o Configuration object to apply.
@static
@since 3.5.0
**/
YUI.applyConfig = function(o) {
if (!o) {
return;
}
//If there is a GlobalConfig, apply it first to set the defaults
if (YUI.GlobalConfig) {
this.prototype.applyConfig.call(this, YUI.GlobalConfig);
}
//Apply this config to it
this.prototype.applyConfig.call(this, o);
//Reset GlobalConfig to the combined config
YUI.GlobalConfig = this.config;
};
// set up the environment
YUI._init();
if (hasWin) {
// add a window load event at load time so we can capture
// the case where it fires before dynamic loading is
// complete.
add(window, 'load', handleLoad);
} else {
handleLoad();
}
YUI.Env.add = add;
YUI.Env.remove = remove;
/*global exports*/
// Support the CommonJS method for exporting our single global
if (typeof exports == 'object') {
exports.YUI = YUI;
/**
* Set a method to be called when `Get.script` is called in Node.js
* `Get` will open the file, then pass it's content and it's path
* to this method before attaching it. Commonly used for code coverage
* instrumentation. <strong>Calling this multiple times will only
* attach the last hook method</strong>. This method is only
* available in Node.js.
* @method setLoadHook
* @static
* @param {Function} fn The function to set
* @param {String} fn.data The content of the file
* @param {String} fn.path The file path of the file
*/
YUI.setLoadHook = function(fn) {
YUI._getLoadHook = fn;
};
/**
* Load hook for `Y.Get.script` in Node.js, see `YUI.setLoadHook`
* @method _getLoadHook
* @private
* @param {String} data The content of the file
* @param {String} path The file path of the file
*/
YUI._getLoadHook = null;
}
}());
/**
Config object that contains all of the configuration options for
this `YUI` instance.
This object is supplied by the implementer when instantiating YUI. Some
properties have default values if they are not supplied by the implementer.
This object should not be updated directly because some values are cached. Use
`applyConfig()` to update the config object on a YUI instance that has already
been configured.
@class config
@static
**/
/**
If `true` (the default), YUI will "bootstrap" the YUI Loader and module metadata
if they're needed to load additional dependencies and aren't already available.
Setting this to `false` will prevent YUI from automatically loading the Loader
and module metadata, so you will need to manually ensure that they're available
or handle dependency resolution yourself.
@property {Boolean} bootstrap
@default true
**/
/**
If `true`, `Y.log()` messages will be written to the browser's debug console
when available and when `useBrowserConsole` is also `true`.
@property {Boolean} debug
@default true
**/
/**
Log messages to the browser console if `debug` is `true` and the browser has a
supported console.
@property {Boolean} useBrowserConsole
@default true
**/
/**
A hash of log sources that should be logged. If specified, only messages from
these sources will be logged. Others will be discarded.
@property {Object} logInclude
@type object
**/
/**
A hash of log sources that should be not be logged. If specified, all sources
will be logged *except* those on this list.
@property {Object} logExclude
**/
/**
When the YUI seed file is dynamically loaded after the `window.onload` event has
fired, set this to `true` to tell YUI that it shouldn't wait for `window.onload`
to occur.
This ensures that components that rely on `window.onload` and the `domready`
custom event will work as expected even when YUI is dynamically injected.
@property {Boolean} injected
@default false
**/
/**
If `true`, `Y.error()` will generate or re-throw a JavaScript error. Otherwise,
errors are merely logged silently.
@property {Boolean} throwFail
@default true
**/
/**
Reference to the global object for this execution context.
In a browser, this is the current `window` object. In Node.js, this is the
Node.js `global` object.
@property {Object} global
**/
/**
The browser window or frame that this YUI instance should operate in.
When running in Node.js, this property is `undefined`, since there is no
`window` object. Use `global` to get a reference to the global object that will
work in both browsers and Node.js.
@property {Window} win
**/
/**
The browser `document` object associated with this YUI instance's `win` object.
When running in Node.js, this property is `undefined`, since there is no
`document` object.
@property {Document} doc
**/
/**
A list of modules that defines the YUI core (overrides the default list).
@property {Array} core
@type Array
@default ['get', 'features', 'intl-base', 'yui-log', 'yui-later', 'loader-base', 'loader-rollup', 'loader-yui3']
**/
/**
A list of languages to use in order of preference.
This list is matched against the list of available languages in modules that the
YUI instance uses to determine the best possible localization of language
sensitive modules.
Languages are represented using BCP 47 language tags, such as "en-GB" for
English as used in the United Kingdom, or "zh-Hans-CN" for simplified Chinese as
used in China. The list may be provided as a comma-separated string or as an
array.
@property {String|String[]} lang
**/
/**
Default date format.
@property {String} dateFormat
@deprecated Use configuration in `DataType.Date.format()` instead.
**/
/**
Default locale.
@property {String} locale
@deprecated Use `config.lang` instead.
**/
/**
Default generic polling interval in milliseconds.
@property {Number} pollInterval
@default 20
**/
/**
The number of dynamic `<script>` nodes to insert by default before automatically
removing them when loading scripts.
This applies only to script nodes because removing the node will not make the
evaluated script unavailable. Dynamic CSS nodes are not auto purged, because
removing a linked style sheet will also remove the style definitions.
@property {Number} purgethreshold
@default 20
**/
/**
Delay in milliseconds to wait after a window `resize` event before firing the
event. If another `resize` event occurs before this delay has elapsed, the
delay will start over to ensure that `resize` events are throttled.
@property {Number} windowResizeDelay
@default 40
**/
/**
Base directory for dynamic loading.
@property {String} base
**/
/**
Base URL for a dynamic combo handler. This will be used to make combo-handled
module requests if `combine` is set to `true.
@property {String} comboBase
@default "http://yui.yahooapis.com/combo?"
**/
/**
Root path to prepend to each module path when creating a combo-handled request.
This is updated for each YUI release to point to a specific version of the
library; for example: "3.8.0/build/".
@property {String} root
**/
/**
Filter to apply to module urls. This filter will modify the default path for all
modules.
The default path for the YUI library is the minified version of the files (e.g.,
event-min.js). The filter property can be a predefined filter or a custom
filter. The valid predefined filters are:
- **debug**: Loads debug versions of modules (e.g., event-debug.js).
- **raw**: Loads raw, non-minified versions of modules without debug logging
(e.g., event.js).
You can also define a custom filter, which must be an object literal containing
a search regular expression and a replacement string:
myFilter: {
searchExp : "-min\\.js",
replaceStr: "-debug.js"
}
@property {Object|String} filter
**/
/**
Skin configuration and customizations.
@property {Object} skin
@param {String} [skin.defaultSkin='sam'] Default skin name. This skin will be
applied automatically to skinnable components if not overridden by a
component-specific skin name.
@param {String} [skin.base='assets/skins/'] Default base path for a skin,
relative to Loader's `base` path.
@param {Object} [skin.overrides] Component-specific skin name overrides. Specify
a component name as the key and, as the value, a string or array of strings
for a skin or skins that should be loaded for that component instead of the
`defaultSkin`.
**/
/**
Hash of per-component filter specifications. If specified for a given component,
this overrides the global `filter` config.
@property {Object} filters
**/
/**
If `true`, YUI will use a combo handler to load multiple modules in as few
requests as possible.
The YUI CDN (which YUI uses by default) supports combo handling, but other
servers may not. If the server from which you're loading YUI does not support
combo handling, set this to `false`.
Providing a value for the `base` config property will cause `combine` to default
to `false` instead of `true`.
@property {Boolean} combine
@default true
*/
/**
Array of module names that should never be dynamically loaded.
@property {String[]} ignore
**/
/**
Array of module names that should always be loaded when required, even if
already present on the page.
@property {String[]} force
**/
/**
DOM element or id that should be used as the insertion point for dynamically
added `<script>` and `<link>` nodes.
@property {HTMLElement|String} insertBefore
**/
/**
Object hash containing attributes to add to dynamically added `<script>` nodes.
@property {Object} jsAttributes
**/
/**
Object hash containing attributes to add to dynamically added `<link>` nodes.
@property {Object} cssAttributes
**/
/**
Timeout in milliseconds before a dynamic JS or CSS request will be considered a
failure. If not set, no timeout will be enforced.
@property {Number} timeout
**/
/**
Callback for the 'CSSComplete' event. When dynamically loading YUI components
with CSS, this property fires when the CSS is finished loading.
This provides an opportunity to enhance the presentation of a loading page a
little bit before the entire loading process is done.
@property {Function} onCSS
**/
/**
A hash of module definitions to add to the list of available YUI modules. These
modules can then be dynamically loaded via the `use()` method.
This is a hash in which keys are module names and values are objects containing
module metadata.
See `Loader.addModule()` for the supported module metadata fields. Also see
`groups`, which provides a way to configure the base and combo spec for a set of
modules.
@example
modules: {
mymod1: {
requires: ['node'],
fullpath: '/mymod1/mymod1.js'
},
mymod2: {
requires: ['mymod1'],
fullpath: '/mymod2/mymod2.js'
},
mymod3: '/js/mymod3.js',
mycssmod: '/css/mycssmod.css'
}
@property {Object} modules
**/
/**
Aliases are dynamic groups of modules that can be used as shortcuts.
@example
YUI({
aliases: {
davglass: [ 'node', 'yql', 'dd' ],
mine: [ 'davglass', 'autocomplete']
}
}).use('mine', function (Y) {
// Node, YQL, DD & AutoComplete available here.
});
@property {Object} aliases
**/
/**
A hash of module group definitions.
For each group you can specify a list of modules and the base path and
combo spec to use when dynamically loading the modules.
@example
groups: {
yui2: {
// specify whether or not this group has a combo service
combine: true,
// The comboSeperator to use with this group's combo handler
comboSep: ';',
// The maxURLLength for this server
maxURLLength: 500,
// the base path for non-combo paths
base: 'http://yui.yahooapis.com/2.8.0r4/build/',
// the path to the combo service
comboBase: 'http://yui.yahooapis.com/combo?',
// a fragment to prepend to the path attribute when
// when building combo urls
root: '2.8.0r4/build/',
// the module definitions
modules: {
yui2_yde: {
path: "yahoo-dom-event/yahoo-dom-event.js"
},
yui2_anim: {
path: "animation/animation.js",
requires: ['yui2_yde']
}
}
}
}
@property {Object} groups
**/
/**
Path to the Loader JS file, relative to the `base` path.
This is used to dynamically bootstrap the Loader when it's needed and isn't yet
available.
@property {String} loaderPath
@default "loader/loader-min.js"
**/
/**
If `true`, YUI will attempt to load CSS dependencies and skins. Set this to
`false` to prevent YUI from loading any CSS, or set it to the string `"force"`
to force CSS dependencies to be loaded even if their associated JS modules are
already loaded.
@property {Boolean|String} fetchCSS
@default true
**/
/**
Default gallery version used to build gallery module urls.
@property {String} gallery
@since 3.1.0
**/
/**
Default YUI 2 version used to build YUI 2 module urls.
This is used for intrinsic YUI 2 support via the 2in3 project. Also see the
`2in3` config for pulling different revisions of the wrapped YUI 2 modules.
@property {String} yui2
@default "2.9.0"
@since 3.1.0
**/
/**
Revision number of YUI 2in3 modules that should be used when loading YUI 2in3.
@property {String} 2in3
@default "4"
@since 3.1.0
**/
/**
Alternate console log function that should be used in environments without a
supported native console. This function is executed with the YUI instance as its
`this` object.
@property {Function} logFn
@since 3.1.0
**/
/**
The minimum log level to log messages for. Log levels are defined
incrementally. Messages greater than or equal to the level specified will
be shown. All others will be discarded. The order of log levels in
increasing priority is:
debug
info
warn
error
@property {String} logLevel
@default 'debug'
@since 3.10.0
**/
/**
Callback to execute when `Y.error()` is called. It receives the error message
and a JavaScript error object if one was provided.
This function is executed with the YUI instance as its `this` object.
Returning `true` from this function will prevent an exception from being thrown.
@property {Function} errorFn
@param {String} errorFn.msg Error message
@param {Object} [errorFn.err] Error object (if one was provided).
@since 3.2.0
**/
/**
A callback to execute when Loader fails to load one or more resources.
This could be because of a script load failure. It could also be because a
module fails to register itself when the `requireRegistration` config is `true`.
If this function is defined, the `use()` callback will only be called when the
loader succeeds. Otherwise, `use()` will always executes unless there was a
JavaScript error when attaching a module.
@property {Function} loadErrorFn
@since 3.3.0
**/
/**
If `true`, Loader will expect all loaded scripts to be first-class YUI modules
that register themselves with the YUI global, and will trigger a failure if a
loaded script does not register a YUI module.
@property {Boolean} requireRegistration
@default false
@since 3.3.0
**/
/**
Cache serviced use() requests.
@property {Boolean} cacheUse
@default true
@since 3.3.0
@deprecated No longer used.
**/
/**
Whether or not YUI should use native ES5 functionality when available for
features like `Y.Array.each()`, `Y.Object()`, etc.
When `false`, YUI will always use its own fallback implementations instead of
relying on ES5 functionality, even when ES5 functionality is available.
@property {Boolean} useNativeES5
@default true
@since 3.5.0
**/
/**
* Leverage native JSON stringify if the browser has a native
* implementation. In general, this is a good idea. See the Known Issues
* section in the JSON user guide for caveats. The default value is true
* for browsers with native JSON support.
*
* @property useNativeJSONStringify
* @type Boolean
* @default true
* @since 3.8.0
*/
/**
* Leverage native JSON parse if the browser has a native implementation.
* In general, this is a good idea. See the Known Issues section in the
* JSON user guide for caveats. The default value is true for browsers with
* native JSON support.
*
* @property useNativeJSONParse
* @type Boolean
* @default true
* @since 3.8.0
*/
/**
Delay the `use` callback until a specific event has passed (`load`, `domready`, `contentready` or `available`)
@property {Object|String} delayUntil
@since 3.6.0
@example
You can use `load` or `domready` strings by default:
YUI({
delayUntil: 'domready'
}, function (Y) {
// This will not execute until 'domeready' occurs.
});
Or you can delay until a node is available (with `available` or `contentready`):
YUI({
delayUntil: {
event: 'available',
args : '#foo'
}
}, function (Y) {
// This will not execute until a node matching the selector "#foo" is
// available in the DOM.
});
**/
YUI.add('yui-base', function (Y, NAME) {
/*
* YUI stub
* @module yui
* @submodule yui-base
*/
/**
* The YUI module contains the components required for building the YUI
* seed file. This includes the script loading mechanism, a simple queue,
* and the core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* Provides core language utilites and extensions used throughout YUI.
*
* @class Lang
* @static
*/
var L = Y.Lang || (Y.Lang = {}),
STRING_PROTO = String.prototype,
TOSTRING = Object.prototype.toString,
TYPES = {
'undefined' : 'undefined',
'number' : 'number',
'boolean' : 'boolean',
'string' : 'string',
'[object Function]': 'function',
'[object RegExp]' : 'regexp',
'[object Array]' : 'array',
'[object Date]' : 'date',
'[object Error]' : 'error'
},
SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g,
TRIMREGEX = /^\s+|\s+$/g,
NATIVE_FN_REGEX = /\{\s*\[(?:native code|function)\]\s*\}/i;
// -- Protected Methods --------------------------------------------------------
/**
Returns `true` if the given function appears to be implemented in native code,
`false` otherwise. Will always return `false` -- even in ES5-capable browsers --
if the `useNativeES5` YUI config option is set to `false`.
This isn't guaranteed to be 100% accurate and won't work for anything other than
functions, but it can be useful for determining whether a function like
`Array.prototype.forEach` is native or a JS shim provided by another library.
There's a great article by @kangax discussing certain flaws with this technique:
<http://perfectionkills.com/detecting-built-in-host-methods/>
While his points are valid, it's still possible to benefit from this function
as long as it's used carefully and sparingly, and in such a way that false
negatives have minimal consequences. It's used internally to avoid using
potentially broken non-native ES5 shims that have been added to the page by
other libraries.
@method _isNative
@param {Function} fn Function to test.
@return {Boolean} `true` if _fn_ appears to be native, `false` otherwise.
@static
@protected
@since 3.5.0
**/
L._isNative = function (fn) {
return !!(Y.config.useNativeES5 && fn && NATIVE_FN_REGEX.test(fn));
};
// -- Public Methods -----------------------------------------------------------
/**
* Determines whether or not the provided item is an array.
*
* Returns `false` for array-like collections such as the function `arguments`
* collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to
* test for an array-like collection.
*
* @method isArray
* @param o The object to test.
* @return {boolean} true if o is an array.
* @static
*/
L.isArray = L._isNative(Array.isArray) ? Array.isArray : function (o) {
return L.type(o) === 'array';
};
/**
* Determines whether or not the provided item is a boolean.
* @method isBoolean
* @static
* @param o The object to test.
* @return {boolean} true if o is a boolean.
*/
L.isBoolean = function(o) {
return typeof o === 'boolean';
};
/**
* Determines whether or not the supplied item is a date instance.
* @method isDate
* @static
* @param o The object to test.
* @return {boolean} true if o is a date.
*/
L.isDate = function(o) {
return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o);
};
/**
* <p>
* Determines whether or not the provided item is a function.
* Note: Internet Explorer thinks certain functions are objects:
* </p>
*
* <pre>
* var obj = document.createElement("object");
* Y.Lang.isFunction(obj.getAttribute) // reports false in IE
*
* var input = document.createElement("input"); // append to body
* Y.Lang.isFunction(input.focus) // reports false in IE
* </pre>
*
* <p>
* You will have to implement additional tests if these functions
* matter to you.
* </p>
*
* @method isFunction
* @static
* @param o The object to test.
* @return {boolean} true if o is a function.
*/
L.isFunction = function(o) {
return L.type(o) === 'function';
};
/**
* Determines whether or not the provided item is null.
* @method isNull
* @static
* @param o The object to test.
* @return {boolean} true if o is null.
*/
L.isNull = function(o) {
return o === null;
};
/**
* Determines whether or not the provided item is a legal number.
* @method isNumber
* @static
* @param o The object to test.
* @return {boolean} true if o is a number.
*/
L.isNumber = function(o) {
return typeof o === 'number' && isFinite(o);
};
/**
* Determines whether or not the provided item is of type object
* or function. Note that arrays are also objects, so
* <code>Y.Lang.isObject([]) === true</code>.
* @method isObject
* @static
* @param o The object to test.
* @param failfn {boolean} fail if the input is a function.
* @return {boolean} true if o is an object.
* @see isPlainObject
*/
L.isObject = function(o, failfn) {
var t = typeof o;
return (o && (t === 'object' ||
(!failfn && (t === 'function' || L.isFunction(o))))) || false;
};
/**
* Determines whether or not the provided item is a string.
* @method isString
* @static
* @param o The object to test.
* @return {boolean} true if o is a string.
*/
L.isString = function(o) {
return typeof o === 'string';
};
/**
* Determines whether or not the provided item is undefined.
* @method isUndefined
* @static
* @param o The object to test.
* @return {boolean} true if o is undefined.
*/
L.isUndefined = function(o) {
return typeof o === 'undefined';
};
/**
* A convenience method for detecting a legitimate non-null value.
* Returns false for null/undefined/NaN, true for other values,
* including 0/false/''
* @method isValue
* @static
* @param o The item to test.
* @return {boolean} true if it is not null/undefined/NaN || false.
*/
L.isValue = function(o) {
var t = L.type(o);
switch (t) {
case 'number':
return isFinite(o);
case 'null': // fallthru
case 'undefined':
return false;
default:
return !!t;
}
};
/**
* Returns the current time in milliseconds.
*
* @method now
* @return {Number} Current time in milliseconds.
* @static
* @since 3.3.0
*/
L.now = Date.now || function () {
return new Date().getTime();
};
/**
* Lightweight version of <code>Y.substitute</code>. Uses the same template
* structure as <code>Y.substitute</code>, but doesn't support recursion,
* auto-object coersion, or formats.
* @method sub
* @param {string} s String to be modified.
* @param {object} o Object containing replacement values.
* @return {string} the substitute result.
* @static
* @since 3.2.0
*/
L.sub = function(s, o) {
return s.replace ? s.replace(SUBREGEX, function (match, key) {
return L.isUndefined(o[key]) ? match : o[key];
}) : s;
};
/**
* Returns a string without any leading or trailing whitespace. If
* the input is not a string, the input will be returned untouched.
* @method trim
* @static
* @param s {string} the string to trim.
* @return {string} the trimmed string.
*/
L.trim = STRING_PROTO.trim ? function(s) {
return s && s.trim ? s.trim() : s;
} : function (s) {
try {
return s.replace(TRIMREGEX, '');
} catch (e) {
return s;
}
};
/**
* Returns a string without any leading whitespace.
* @method trimLeft
* @static
* @param s {string} the string to trim.
* @return {string} the trimmed string.
*/
L.trimLeft = STRING_PROTO.trimLeft ? function (s) {
return s.trimLeft();
} : function (s) {
return s.replace(/^\s+/, '');
};
/**
* Returns a string without any trailing whitespace.
* @method trimRight
* @static
* @param s {string} the string to trim.
* @return {string} the trimmed string.
*/
L.trimRight = STRING_PROTO.trimRight ? function (s) {
return s.trimRight();
} : function (s) {
return s.replace(/\s+$/, '');
};
/**
Returns one of the following strings, representing the type of the item passed
in:
* "array"
* "boolean"
* "date"
* "error"
* "function"
* "null"
* "number"
* "object"
* "regexp"
* "string"
* "undefined"
Known issues:
* `typeof HTMLElementCollection` returns function in Safari, but
`Y.Lang.type()` reports "object", which could be a good thing --
but it actually caused the logic in <code>Y.Lang.isObject</code> to fail.
@method type
@param o the item to test.
@return {string} the detected type.
@static
**/
L.type = function(o) {
return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null');
};
/**
@module yui
@submodule yui-base
*/
var Lang = Y.Lang,
Native = Array.prototype,
hasOwn = Object.prototype.hasOwnProperty;
/**
Provides utility methods for working with arrays. Additional array helpers can
be found in the `collection` and `array-extras` modules.
`Y.Array(thing)` returns a native array created from _thing_. Depending on
_thing_'s type, one of the following will happen:
* Arrays are returned unmodified unless a non-zero _startIndex_ is
specified.
* Array-like collections (see `Array.test()`) are converted to arrays.
* For everything else, a new array is created with _thing_ as the sole
item.
Note: elements that are also collections, such as `<form>` and `<select>`
elements, are not automatically converted to arrays. To force a conversion,
pass `true` as the value of the _force_ parameter.
@class Array
@constructor
@param {Any} thing The thing to arrayify.
@param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like
collection, a subset of items starting at the specified index will be
returned.
@param {Boolean} [force=false] If `true`, _thing_ will be treated as an
array-like collection no matter what.
@return {Array} A native array created from _thing_, according to the rules
described above.
**/
function YArray(thing, startIndex, force) {
var len, result;
/*jshint expr: true*/
startIndex || (startIndex = 0);
if (force || YArray.test(thing)) {
// IE throws when trying to slice HTMLElement collections.
try {
return Native.slice.call(thing, startIndex);
} catch (ex) {
result = [];
for (len = thing.length; startIndex < len; ++startIndex) {
result.push(thing[startIndex]);
}
return result;
}
}
return [thing];
}
Y.Array = YArray;
/**
Dedupes an array of strings, returning an array that's guaranteed to contain
only one copy of a given string.
This method differs from `Array.unique()` in that it's optimized for use only
with strings, whereas `unique` may be used with other types (but is slower).
Using `dedupe()` with non-string values may result in unexpected behavior.
@method dedupe
@param {String[]} array Array of strings to dedupe.
@return {Array} Deduped copy of _array_.
@static
@since 3.4.0
**/
YArray.dedupe = function (array) {
var hash = {},
results = [],
i, item, len;
for (i = 0, len = array.length; i < len; ++i) {
item = array[i];
if (!hasOwn.call(hash, item)) {
hash[item] = 1;
results.push(item);
}
}
return results;
};
/**
Executes the supplied function on each item in the array. This method wraps
the native ES5 `Array.forEach()` method if available.
@method each
@param {Array} array Array to iterate.
@param {Function} fn Function to execute on each item in the array. The function
will receive the following arguments:
@param {Any} fn.item Current array item.
@param {Number} fn.index Current array index.
@param {Array} fn.array Array being iterated.
@param {Object} [thisObj] `this` object to use when calling _fn_.
@return {YUI} The YUI instance.
@static
**/
YArray.each = YArray.forEach = Lang._isNative(Native.forEach) ? function (array, fn, thisObj) {
Native.forEach.call(array || [], fn, thisObj || Y);
return Y;
} : function (array, fn, thisObj) {
for (var i = 0, len = (array && array.length) || 0; i < len; ++i) {
if (i in array) {
fn.call(thisObj || Y, array[i], i, array);
}
}
return Y;
};
/**
Alias for `each()`.
@method forEach
@static
**/
/**
Returns an object using the first array as keys and the second as values. If
the second array is not provided, or if it doesn't contain the same number of
values as the first array, then `true` will be used in place of the missing
values.
@example
Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']);
// => {a: 'foo', b: 'bar', c: true}
@method hash
@param {String[]} keys Array of strings to use as keys.
@param {Array} [values] Array to use as values.
@return {Object} Hash using the first array as keys and the second as values.
@static
**/
YArray.hash = function (keys, values) {
var hash = {},
vlen = (values && values.length) || 0,
i, len;
for (i = 0, len = keys.length; i < len; ++i) {
if (i in keys) {
hash[keys[i]] = vlen > i && i in values ? values[i] : true;
}
}
return hash;
};
/**
Returns the index of the first item in the array that's equal (using a strict
equality check) to the specified _value_, or `-1` if the value isn't found.
This method wraps the native ES5 `Array.indexOf()` method if available.
@method indexOf
@param {Array} array Array to search.
@param {Any} value Value to search for.
@param {Number} [from=0] The index at which to begin the search.
@return {Number} Index of the item strictly equal to _value_, or `-1` if not
found.
@static
**/
YArray.indexOf = Lang._isNative(Native.indexOf) ? function (array, value, from) {
return Native.indexOf.call(array, value, from);
} : function (array, value, from) {
// http://es5.github.com/#x15.4.4.14
var len = array.length;
from = +from || 0;
from = (from > 0 || -1) * Math.floor(Math.abs(from));
if (from < 0) {
from += len;
if (from < 0) {
from = 0;
}
}
for (; from < len; ++from) {
if (from in array && array[from] === value) {
return from;
}
}
return -1;
};
/**
Numeric sort convenience function.
The native `Array.prototype.sort()` function converts values to strings and
sorts them in lexicographic order, which is unsuitable for sorting numeric
values. Provide `Array.numericSort` as a custom sort function when you want
to sort values in numeric order.
@example
[42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort);
// => [4, 8, 15, 16, 23, 42]
@method numericSort
@param {Number} a First value to compare.
@param {Number} b Second value to compare.
@return {Number} Difference between _a_ and _b_.
@static
**/
YArray.numericSort = function (a, b) {
return a - b;
};
/**
Executes the supplied function on each item in the array. Returning a truthy
value from the function will stop the processing of remaining items.
@method some
@param {Array} array Array to iterate over.
@param {Function} fn Function to execute on each item. The function will receive
the following arguments:
@param {Any} fn.value Current array item.
@param {Number} fn.index Current array index.
@param {Array} fn.array Array being iterated over.
@param {Object} [thisObj] `this` object to use when calling _fn_.
@return {Boolean} `true` if the function returns a truthy value on any of the
items in the array; `false` otherwise.
@static
**/
YArray.some = Lang._isNative(Native.some) ? function (array, fn, thisObj) {
return Native.some.call(array, fn, thisObj);
} : function (array, fn, thisObj) {
for (var i = 0, len = array.length; i < len; ++i) {
if (i in array && fn.call(thisObj, array[i], i, array)) {
return true;
}
}
return false;
};
/**
Evaluates _obj_ to determine if it's an array, an array-like collection, or
something else. This is useful when working with the function `arguments`
collection and `HTMLElement` collections.
Note: This implementation doesn't consider elements that are also
collections, such as `<form>` and `<select>`, to be array-like.
@method test
@param {Object} obj Object to test.
@return {Number} A number indicating the results of the test:
* 0: Neither an array nor an array-like collection.
* 1: Real array.
* 2: Array-like collection.
@static
**/
YArray.test = function (obj) {
var result = 0;
if (Lang.isArray(obj)) {
result = 1;
} else if (Lang.isObject(obj)) {
try {
// indexed, but no tagName (element) or scrollTo/document (window. From DOM.isWindow test which we can't use here),
// or functions without apply/call (Safari
// HTMLElementCollection bug).
if ('length' in obj && !obj.tagName && !(obj.scrollTo && obj.document) && !obj.apply) {
result = 2;
}
} catch (ex) {}
}
return result;
};
/**
* The YUI module contains the components required for building the YUI
* seed file. This includes the script loading mechanism, a simple queue,
* and the core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* A simple FIFO queue. Items are added to the Queue with add(1..n items) and
* removed using next().
*
* @class Queue
* @constructor
* @param {MIXED} item* 0..n items to seed the queue.
*/
function Queue() {
this._init();
this.add.apply(this, arguments);
}
Queue.prototype = {
/**
* Initialize the queue
*
* @method _init
* @protected
*/
_init: function() {
/**
* The collection of enqueued items
*
* @property _q
* @type Array
* @protected
*/
this._q = [];
},
/**
* Get the next item in the queue. FIFO support
*
* @method next
* @return {MIXED} the next item in the queue.
*/
next: function() {
return this._q.shift();
},
/**
* Get the last in the queue. LIFO support.
*
* @method last
* @return {MIXED} the last item in the queue.
*/
last: function() {
return this._q.pop();
},
/**
* Add 0..n items to the end of the queue.
*
* @method add
* @param {MIXED} item* 0..n items.
* @return {object} this queue.
*/
add: function() {
this._q.push.apply(this._q, arguments);
return this;
},
/**
* Returns the current number of queued items.
*
* @method size
* @return {Number} The size.
*/
size: function() {
return this._q.length;
}
};
Y.Queue = Queue;
YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue();
/**
The YUI module contains the components required for building the YUI seed file.
This includes the script loading mechanism, a simple queue, and the core
utilities for the library.
@module yui
@submodule yui-base
**/
var CACHED_DELIMITER = '__',
hasOwn = Object.prototype.hasOwnProperty,
isObject = Y.Lang.isObject;
/**
Returns a wrapper for a function which caches the return value of that function,
keyed off of the combined string representation of the argument values provided
when the wrapper is called.
Calling this function again with the same arguments will return the cached value
rather than executing the wrapped function.
Note that since the cache is keyed off of the string representation of arguments
passed to the wrapper function, arguments that aren't strings and don't provide
a meaningful `toString()` method may result in unexpected caching behavior. For
example, the objects `{}` and `{foo: 'bar'}` would both be converted to the
string `[object Object]` when used as a cache key.
@method cached
@param {Function} source The function to memoize.
@param {Object} [cache={}] Object in which to store cached values. You may seed
this object with pre-existing cached values if desired.
@param {any} [refetch] If supplied, this value is compared with the cached value
using a `==` comparison. If the values are equal, the wrapped function is
executed again even though a cached value exists.
@return {Function} Wrapped function.
@for YUI
**/
Y.cached = function (source, cache, refetch) {
/*jshint expr: true*/
cache || (cache = {});
return function (arg) {
var key = arguments.length > 1 ?
Array.prototype.join.call(arguments, CACHED_DELIMITER) :
String(arg);
/*jshint eqeqeq: false*/
if (!(key in cache) || (refetch && cache[key] == refetch)) {
cache[key] = source.apply(source, arguments);
}
return cache[key];
};
};
/**
Returns the `location` object from the window/frame in which this YUI instance
operates, or `undefined` when executing in a non-browser environment
(e.g. Node.js).
It is _not_ recommended to hold references to the `window.location` object
outside of the scope of a function in which its properties are being accessed or
its methods are being called. This is because of a nasty bug/issue that exists
in both Safari and MobileSafari browsers:
[WebKit Bug 34679](https://bugs.webkit.org/show_bug.cgi?id=34679).
@method getLocation
@return {location} The `location` object from the window/frame in which this YUI
instance operates.
@since 3.5.0
**/
Y.getLocation = function () {
// It is safer to look this up every time because yui-base is attached to a
// YUI instance before a user's config is applied; i.e. `Y.config.win` does
// not point the correct window object when this file is loaded.
var win = Y.config.win;
// It is not safe to hold a reference to the `location` object outside the
// scope in which it is being used. The WebKit engine used in Safari and
// MobileSafari will "disconnect" the `location` object from the `window`
// when a page is restored from back/forward history cache.
return win && win.location;
};
/**
Returns a new object containing all of the properties of all the supplied
objects. The properties from later objects will overwrite those in earlier
objects.
Passing in a single object will create a shallow copy of it. For a deep copy,
use `clone()`.
@method merge
@param {Object} objects* One or more objects to merge.
@return {Object} A new merged object.
**/
Y.merge = function () {
var i = 0,
len = arguments.length,
result = {},
key,
obj;
for (; i < len; ++i) {
obj = arguments[i];
for (key in obj) {
if (hasOwn.call(obj, key)) {
result[key] = obj[key];
}
}
}
return result;
};
/**
Mixes _supplier_'s properties into _receiver_.
Properties on _receiver_ or _receiver_'s prototype will not be overwritten or
shadowed unless the _overwrite_ parameter is `true`, and will not be merged
unless the _merge_ parameter is `true`.
In the default mode (0), only properties the supplier owns are copied (prototype
properties are not copied). The following copying modes are available:
* `0`: _Default_. Object to object.
* `1`: Prototype to prototype.
* `2`: Prototype to prototype and object to object.
* `3`: Prototype to object.
* `4`: Object to prototype.
@method mix
@param {Function|Object} receiver The object or function to receive the mixed
properties.
@param {Function|Object} supplier The object or function supplying the
properties to be mixed.
@param {Boolean} [overwrite=false] If `true`, properties that already exist
on the receiver will be overwritten with properties from the supplier.
@param {String[]} [whitelist] An array of property names to copy. If
specified, only the whitelisted properties will be copied, and all others
will be ignored.
@param {Number} [mode=0] Mix mode to use. See above for available modes.
@param {Boolean} [merge=false] If `true`, objects and arrays that already
exist on the receiver will have the corresponding object/array from the
supplier merged into them, rather than being skipped or overwritten. When
both _overwrite_ and _merge_ are `true`, _merge_ takes precedence.
@return {Function|Object|YUI} The receiver, or the YUI instance if the
specified receiver is falsy.
**/
Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) {
var alwaysOverwrite, exists, from, i, key, len, to;
// If no supplier is given, we return the receiver. If no receiver is given,
// we return Y. Returning Y doesn't make much sense to me, but it's
// grandfathered in for backcompat reasons.
if (!receiver || !supplier) {
return receiver || Y;
}
if (mode) {
// In mode 2 (prototype to prototype and object to object), we recurse
// once to do the proto to proto mix. The object to object mix will be
// handled later on.
if (mode === 2) {
Y.mix(receiver.prototype, supplier.prototype, overwrite,
whitelist, 0, merge);
}
// Depending on which mode is specified, we may be copying from or to
// the prototypes of the supplier and receiver.
from = mode === 1 || mode === 3 ? supplier.prototype : supplier;
to = mode === 1 || mode === 4 ? receiver.prototype : receiver;
// If either the supplier or receiver doesn't actually have a
// prototype property, then we could end up with an undefined `from`
// or `to`. If that happens, we abort and return the receiver.
if (!from || !to) {
return receiver;
}
} else {
from = supplier;
to = receiver;
}
// If `overwrite` is truthy and `merge` is falsy, then we can skip a
// property existence check on each iteration and save some time.
alwaysOverwrite = overwrite && !merge;
if (whitelist) {
for (i = 0, len = whitelist.length; i < len; ++i) {
key = whitelist[i];
// We call `Object.prototype.hasOwnProperty` instead of calling
// `hasOwnProperty` on the object itself, since the object's
// `hasOwnProperty` method may have been overridden or removed.
// Also, some native objects don't implement a `hasOwnProperty`
// method.
if (!hasOwn.call(from, key)) {
continue;
}
// The `key in to` check here is (sadly) intentional for backwards
// compatibility reasons. It prevents undesired shadowing of
// prototype members on `to`.
exists = alwaysOverwrite ? false : key in to;
if (merge && exists && isObject(to[key], true)
&& isObject(from[key], true)) {
// If we're in merge mode, and the key is present on both
// objects, and the value on both objects is either an object or
// an array (but not a function), then we recurse to merge the
// `from` value into the `to` value instead of overwriting it.
//
// Note: It's intentional that the whitelist isn't passed to the
// recursive call here. This is legacy behavior that lots of
// code still depends on.
Y.mix(to[key], from[key], overwrite, null, 0, merge);
} else if (overwrite || !exists) {
// We're not in merge mode, so we'll only copy the `from` value
// to the `to` value if we're in overwrite mode or if the
// current key doesn't exist on the `to` object.
to[key] = from[key];
}
}
} else {
for (key in from) {
// The code duplication here is for runtime performance reasons.
// Combining whitelist and non-whitelist operations into a single
// loop or breaking the shared logic out into a function both result
// in worse performance, and Y.mix is critical enough that the byte
// tradeoff is worth it.
if (!hasOwn.call(from, key)) {
continue;
}
// The `key in to` check here is (sadly) intentional for backwards
// compatibility reasons. It prevents undesired shadowing of
// prototype members on `to`.
exists = alwaysOverwrite ? false : key in to;
if (merge && exists && isObject(to[key], true)
&& isObject(from[key], true)) {
Y.mix(to[key], from[key], overwrite, null, 0, merge);
} else if (overwrite || !exists) {
to[key] = from[key];
}
}
// If this is an IE browser with the JScript enumeration bug, force
// enumeration of the buggy properties by making a recursive call with
// the buggy properties as the whitelist.
if (Y.Object._hasEnumBug) {
Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge);
}
}
return receiver;
};
/**
* The YUI module contains the components required for building the YUI
* seed file. This includes the script loading mechanism, a simple queue,
* and the core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* Adds utilities to the YUI instance for working with objects.
*
* @class Object
*/
var Lang = Y.Lang,
hasOwn = Object.prototype.hasOwnProperty,
UNDEFINED, // <-- Note the comma. We're still declaring vars.
/**
* Returns a new object that uses _obj_ as its prototype. This method wraps the
* native ES5 `Object.create()` method if available, but doesn't currently
* pass through `Object.create()`'s second argument (properties) in order to
* ensure compatibility with older browsers.
*
* @method ()
* @param {Object} obj Prototype object.
* @return {Object} New object using _obj_ as its prototype.
* @static
*/
O = Y.Object = Lang._isNative(Object.create) ? function (obj) {
// We currently wrap the native Object.create instead of simply aliasing it
// to ensure consistency with our fallback shim, which currently doesn't
// support Object.create()'s second argument (properties). Once we have a
// safe fallback for the properties arg, we can stop wrapping
// Object.create().
return Object.create(obj);
} : (function () {
// Reusable constructor function for the Object.create() shim.
function F() {}
// The actual shim.
return function (obj) {
F.prototype = obj;
return new F();
};
}()),
/**
* Property names that IE doesn't enumerate in for..in loops, even when they
* should be enumerable. When `_hasEnumBug` is `true`, it's necessary to
* manually enumerate these properties.
*
* @property _forceEnum
* @type String[]
* @protected
* @static
*/
forceEnum = O._forceEnum = [
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toString',
'toLocaleString',
'valueOf'
],
/**
* `true` if this browser has the JScript enumeration bug that prevents
* enumeration of the properties named in the `_forceEnum` array, `false`
* otherwise.
*
* See:
* - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug>
* - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation>
*
* @property _hasEnumBug
* @type Boolean
* @protected
* @static
*/
hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'),
/**
* `true` if this browser incorrectly considers the `prototype` property of
* functions to be enumerable. Currently known to affect Opera 11.50.
*
* @property _hasProtoEnumBug
* @type Boolean
* @protected
* @static
*/
hasProtoEnumBug = O._hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'),
/**
* Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or
* exists only on _obj_'s prototype. This is essentially a safer version of
* `obj.hasOwnProperty()`.
*
* @method owns
* @param {Object} obj Object to test.
* @param {String} key Property name to look for.
* @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise.
* @static
*/
owns = O.owns = function (obj, key) {
return !!obj && hasOwn.call(obj, key);
}; // <-- End of var declarations.
/**
* Alias for `owns()`.
*
* @method hasKey
* @param {Object} obj Object to test.
* @param {String} key Property name to look for.
* @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise.
* @static
*/
O.hasKey = owns;
/**
* Returns an array containing the object's enumerable keys. Does not include
* prototype keys or non-enumerable keys.
*
* Note that keys are returned in enumeration order (that is, in the same order
* that they would be enumerated by a `for-in` loop), which may not be the same
* as the order in which they were defined.
*
* This method is an alias for the native ES5 `Object.keys()` method if
* available.
*
* @example
*
* Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'});
* // => ['a', 'b', 'c']
*
* @method keys
* @param {Object} obj An object.
* @return {String[]} Array of keys.
* @static
*/
O.keys = Lang._isNative(Object.keys) ? Object.keys : function (obj) {
if (!Lang.isObject(obj)) {
throw new TypeError('Object.keys called on a non-object');
}
var keys = [],
i, key, len;
if (hasProtoEnumBug && typeof obj === 'function') {
for (key in obj) {
if (owns(obj, key) && key !== 'prototype') {
keys.push(key);
}
}
} else {
for (key in obj) {
if (owns(obj, key)) {
keys.push(key);
}
}
}
if (hasEnumBug) {
for (i = 0, len = forceEnum.length; i < len; ++i) {
key = forceEnum[i];
if (owns(obj, key)) {
keys.push(key);
}
}
}
return keys;
};
/**
* Returns an array containing the values of the object's enumerable keys.
*
* Note that values are returned in enumeration order (that is, in the same
* order that they would be enumerated by a `for-in` loop), which may not be the
* same as the order in which they were defined.
*
* @example
*
* Y.Object.values({a: 'foo', b: 'bar', c: 'baz'});
* // => ['foo', 'bar', 'baz']
*
* @method values
* @param {Object} obj An object.
* @return {Array} Array of values.
* @static
*/
O.values = function (obj) {
var keys = O.keys(obj),
i = 0,
len = keys.length,
values = [];
for (; i < len; ++i) {
values.push(obj[keys[i]]);
}
return values;
};
/**
* Returns the number of enumerable keys owned by an object.
*
* @method size
* @param {Object} obj An object.
* @return {Number} The object's size.
* @static
*/
O.size = function (obj) {
try {
return O.keys(obj).length;
} catch (ex) {
return 0; // Legacy behavior for non-objects.
}
};
/**
* Returns `true` if the object owns an enumerable property with the specified
* value.
*
* @method hasValue
* @param {Object} obj An object.
* @param {any} value The value to search for.
* @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise.
* @static
*/
O.hasValue = function (obj, value) {
return Y.Array.indexOf(O.values(obj), value) > -1;
};
/**
* Executes a function on each enumerable property in _obj_. The function
* receives the value, the key, and the object itself as parameters (in that
* order).
*
* By default, only properties owned by _obj_ are enumerated. To include
* prototype properties, set the _proto_ parameter to `true`.
*
* @method each
* @param {Object} obj Object to enumerate.
* @param {Function} fn Function to execute on each enumerable property.
* @param {mixed} fn.value Value of the current property.
* @param {String} fn.key Key of the current property.
* @param {Object} fn.obj Object being enumerated.
* @param {Object} [thisObj] `this` object to use when calling _fn_.
* @param {Boolean} [proto=false] Include prototype properties.
* @return {YUI} the YUI instance.
* @chainable
* @static
*/
O.each = function (obj, fn, thisObj, proto) {
var key;
for (key in obj) {
if (proto || owns(obj, key)) {
fn.call(thisObj || Y, obj[key], key, obj);
}
}
return Y;
};
/**
* Executes a function on each enumerable property in _obj_, but halts if the
* function returns a truthy value. The function receives the value, the key,
* and the object itself as paramters (in that order).
*
* By default, only properties owned by _obj_ are enumerated. To include
* prototype properties, set the _proto_ parameter to `true`.
*
* @method some
* @param {Object} obj Object to enumerate.
* @param {Function} fn Function to execute on each enumerable property.
* @param {mixed} fn.value Value of the current property.
* @param {String} fn.key Key of the current property.
* @param {Object} fn.obj Object being enumerated.
* @param {Object} [thisObj] `this` object to use when calling _fn_.
* @param {Boolean} [proto=false] Include prototype properties.
* @return {Boolean} `true` if any execution of _fn_ returns a truthy value,
* `false` otherwise.
* @static
*/
O.some = function (obj, fn, thisObj, proto) {
var key;
for (key in obj) {
if (proto || owns(obj, key)) {
if (fn.call(thisObj || Y, obj[key], key, obj)) {
return true;
}
}
}
return false;
};
/**
* Retrieves the sub value at the provided path,
* from the value object provided.
*
* @method getValue
* @static
* @param o The object from which to extract the property value.
* @param path {Array} A path array, specifying the object traversal path
* from which to obtain the sub value.
* @return {Any} The value stored in the path, undefined if not found,
* undefined if the source is not an object. Returns the source object
* if an empty path is provided.
*/
O.getValue = function(o, path) {
if (!Lang.isObject(o)) {
return UNDEFINED;
}
var i,
p = Y.Array(path),
l = p.length;
for (i = 0; o !== UNDEFINED && i < l; i++) {
o = o[p[i]];
}
return o;
};
/**
* Sets the sub-attribute value at the provided path on the
* value object. Returns the modified value object, or
* undefined if the path is invalid.
*
* @method setValue
* @static
* @param o The object on which to set the sub value.
* @param path {Array} A path array, specifying the object traversal path
* at which to set the sub value.
* @param val {Any} The new value for the sub-attribute.
* @return {Object} The modified object, with the new sub value set, or
* undefined, if the path was invalid.
*/
O.setValue = function(o, path, val) {
var i,
p = Y.Array(path),
leafIdx = p.length - 1,
ref = o;
if (leafIdx >= 0) {
for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) {
ref = ref[p[i]];
}
if (ref !== UNDEFINED) {
ref[p[i]] = val;
} else {
return UNDEFINED;
}
}
return o;
};
/**
* Returns `true` if the object has no enumerable properties of its own.
*
* @method isEmpty
* @param {Object} obj An object.
* @return {Boolean} `true` if the object is empty.
* @static
* @since 3.2.0
*/
O.isEmpty = function (obj) {
return !O.keys(Object(obj)).length;
};
/**
* The YUI module contains the components required for building the YUI seed
* file. This includes the script loading mechanism, a simple queue, and the
* core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* YUI user agent detection.
* Do not fork for a browser if it can be avoided. Use feature detection when
* you can. Use the user agent as a last resort. For all fields listed
* as @type float, UA stores a version number for the browser engine,
* 0 otherwise. This value may or may not map to the version number of
* the browser using the engine. The value is presented as a float so
* that it can easily be used for boolean evaluation as well as for
* looking for a particular range of versions. Because of this,
* some of the granularity of the version info may be lost. The fields that
* are @type string default to null. The API docs list the values that
* these fields can have.
* @class UA
* @static
*/
/**
* Static method on `YUI.Env` for parsing a UA string. Called at instantiation
* to populate `Y.UA`.
*
* @static
* @method parseUA
* @param {String} [subUA=navigator.userAgent] UA string to parse
* @return {Object} The Y.UA object
*/
YUI.Env.parseUA = function(subUA) {
var numberify = function(s) {
var c = 0;
return parseFloat(s.replace(/\./g, function() {
return (c++ === 1) ? '' : '.';
}));
},
win = Y.config.win,
nav = win && win.navigator,
o = {
/**
* Internet Explorer version number or 0. Example: 6
* @property ie
* @type float
* @static
*/
ie: 0,
/**
* Opera version number or 0. Example: 9.2
* @property opera
* @type float
* @static
*/
opera: 0,
/**
* Gecko engine revision number. Will evaluate to 1 if Gecko
* is detected but the revision could not be found. Other browsers
* will be 0. Example: 1.8
* <pre>
* Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7
* Firefox 1.5.0.9: 1.8.0.9 <-- 1.8
* Firefox 2.0.0.3: 1.8.1.3 <-- 1.81
* Firefox 3.0 <-- 1.9
* Firefox 3.5 <-- 1.91
* </pre>
* @property gecko
* @type float
* @static
*/
gecko: 0,
/**
* AppleWebKit version. KHTML browsers that are not WebKit browsers
* will evaluate to 1, other browsers 0. Example: 418.9
* <pre>
* Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the
* latest available for Mac OSX 10.3.
* Safari 2.0.2: 416 <-- hasOwnProperty introduced
* Safari 2.0.4: 418 <-- preventDefault fixed
* Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run
* different versions of webkit
* Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been
* updated, but not updated
* to the latest patch.
* Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native
* SVG and many major issues fixed).
* Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic
* update from 2.x via the 10.4.11 OS patch.
* Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event.
* yahoo.com user agent hack removed.
* </pre>
* http://en.wikipedia.org/wiki/Safari_version_history
* @property webkit
* @type float
* @static
*/
webkit: 0,
/**
* Safari will be detected as webkit, but this property will also
* be populated with the Safari version number
* @property safari
* @type float
* @static
*/
safari: 0,
/**
* Chrome will be detected as webkit, but this property will also
* be populated with the Chrome version number
* @property chrome
* @type float
* @static
*/
chrome: 0,
/**
* The mobile property will be set to a string containing any relevant
* user agent information when a modern mobile browser is detected.
* Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series
* devices with the WebKit-based browser, and Opera Mini.
* @property mobile
* @type string
* @default null
* @static
*/
mobile: null,
/**
* Adobe AIR version number or 0. Only populated if webkit is detected.
* Example: 1.0
* @property air
* @type float
*/
air: 0,
/**
* PhantomJS version number or 0. Only populated if webkit is detected.
* Example: 1.0
* @property phantomjs
* @type float
*/
phantomjs: 0,
/**
* Detects Apple iPad's OS version
* @property ipad
* @type float
* @static
*/
ipad: 0,
/**
* Detects Apple iPhone's OS version
* @property iphone
* @type float
* @static
*/
iphone: 0,
/**
* Detects Apples iPod's OS version
* @property ipod
* @type float
* @static
*/
ipod: 0,
/**
* General truthy check for iPad, iPhone or iPod
* @property ios
* @type Boolean
* @default null
* @static
*/
ios: null,
/**
* Detects Googles Android OS version
* @property android
* @type float
* @static
*/
android: 0,
/**
* Detects Kindle Silk
* @property silk
* @type float
* @static
*/
silk: 0,
/**
* Detects Kindle Silk Acceleration
* @property accel
* @type Boolean
* @static
*/
accel: false,
/**
* Detects Palms WebOS version
* @property webos
* @type float
* @static
*/
webos: 0,
/**
* Google Caja version number or 0.
* @property caja
* @type float
*/
caja: nav && nav.cajaVersion,
/**
* Set to true if the page appears to be in SSL
* @property secure
* @type boolean
* @static
*/
secure: false,
/**
* The operating system. Currently only detecting windows or macintosh
* @property os
* @type string
* @default null
* @static
*/
os: null,
/**
* The Nodejs Version
* @property nodejs
* @type float
* @default 0
* @static
*/
nodejs: 0,
/**
* Window8/IE10 Application host environment
* @property winjs
* @type Boolean
* @static
*/
winjs: !!((typeof Windows !== "undefined") && Windows.System),
/**
* Are touch/msPointer events available on this device
* @property touchEnabled
* @type Boolean
* @static
*/
touchEnabled: false
},
ua = subUA || nav && nav.userAgent,
loc = win && win.location,
href = loc && loc.href,
m;
/**
* The User Agent string that was parsed
* @property userAgent
* @type String
* @static
*/
o.userAgent = ua;
o.secure = href && (href.toLowerCase().indexOf('https') === 0);
if (ua) {
if ((/windows|win32/i).test(ua)) {
o.os = 'windows';
} else if ((/macintosh|mac_powerpc/i).test(ua)) {
o.os = 'macintosh';
} else if ((/android/i).test(ua)) {
o.os = 'android';
} else if ((/symbos/i).test(ua)) {
o.os = 'symbos';
} else if ((/linux/i).test(ua)) {
o.os = 'linux';
} else if ((/rhino/i).test(ua)) {
o.os = 'rhino';
}
// Modern KHTML browsers should qualify as Safari X-Grade
if ((/KHTML/).test(ua)) {
o.webkit = 1;
}
if ((/IEMobile|XBLWP7/).test(ua)) {
o.mobile = 'windows';
}
if ((/Fennec/).test(ua)) {
o.mobile = 'gecko';
}
// Modern WebKit browsers are at least X-Grade
m = ua.match(/AppleWebKit\/([^\s]*)/);
if (m && m[1]) {
o.webkit = numberify(m[1]);
o.safari = o.webkit;
if (/PhantomJS/.test(ua)) {
m = ua.match(/PhantomJS\/([^\s]*)/);
if (m && m[1]) {
o.phantomjs = numberify(m[1]);
}
}
// Mobile browser check
if (/ Mobile\//.test(ua) || (/iPad|iPod|iPhone/).test(ua)) {
o.mobile = 'Apple'; // iPhone or iPod Touch
m = ua.match(/OS ([^\s]*)/);
if (m && m[1]) {
m = numberify(m[1].replace('_', '.'));
}
o.ios = m;
o.os = 'ios';
o.ipad = o.ipod = o.iphone = 0;
m = ua.match(/iPad|iPod|iPhone/);
if (m && m[0]) {
o[m[0].toLowerCase()] = o.ios;
}
} else {
m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/);
if (m) {
// Nokia N-series, webOS, ex: NokiaN95
o.mobile = m[0];
}
if (/webOS/.test(ua)) {
o.mobile = 'WebOS';
m = ua.match(/webOS\/([^\s]*);/);
if (m && m[1]) {
o.webos = numberify(m[1]);
}
}
if (/ Android/.test(ua)) {
if (/Mobile/.test(ua)) {
o.mobile = 'Android';
}
m = ua.match(/Android ([^\s]*);/);
if (m && m[1]) {
o.android = numberify(m[1]);
}
}
if (/Silk/.test(ua)) {
m = ua.match(/Silk\/([^\s]*)\)/);
if (m && m[1]) {
o.silk = numberify(m[1]);
}
if (!o.android) {
o.android = 2.34; //Hack for desktop mode in Kindle
o.os = 'Android';
}
if (/Accelerated=true/.test(ua)) {
o.accel = true;
}
}
}
m = ua.match(/(Chrome|CrMo|CriOS)\/([^\s]*)/);
if (m && m[1] && m[2]) {
o.chrome = numberify(m[2]); // Chrome
o.safari = 0; //Reset safari back to 0
if (m[1] === 'CrMo') {
o.mobile = 'chrome';
}
} else {
m = ua.match(/AdobeAIR\/([^\s]*)/);
if (m) {
o.air = m[0]; // Adobe AIR 1.0 or better
}
}
}
if (!o.webkit) { // not webkit
// @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr)
if (/Opera/.test(ua)) {
m = ua.match(/Opera[\s\/]([^\s]*)/);
if (m && m[1]) {
o.opera = numberify(m[1]);
}
m = ua.match(/Version\/([^\s]*)/);
if (m && m[1]) {
o.opera = numberify(m[1]); // opera 10+
}
if (/Opera Mobi/.test(ua)) {
o.mobile = 'opera';
m = ua.replace('Opera Mobi', '').match(/Opera ([^\s]*)/);
if (m && m[1]) {
o.opera = numberify(m[1]);
}
}
m = ua.match(/Opera Mini[^;]*/);
if (m) {
o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316
}
} else { // not opera or webkit
m = ua.match(/MSIE\s([^;]*)/);
if (m && m[1]) {
o.ie = numberify(m[1]);
} else { // not opera, webkit, or ie
m = ua.match(/Gecko\/([^\s]*)/);
if (m) {
o.gecko = 1; // Gecko detected, look for revision
m = ua.match(/rv:([^\s\)]*)/);
if (m && m[1]) {
o.gecko = numberify(m[1]);
if (/Mobile|Tablet/.test(ua)) {
o.mobile = "ffos";
}
}
}
}
}
}
}
//Check for known properties to tell if touch events are enabled on this device or if
//the number of MSPointer touchpoints on this device is greater than 0.
if (win && nav && !(o.chrome && o.chrome < 6)) {
o.touchEnabled = (("ontouchstart" in win) || (("msMaxTouchPoints" in nav) && (nav.msMaxTouchPoints > 0)));
}
//It was a parsed UA, do not assign the global value.
if (!subUA) {
if (typeof process === 'object') {
if (process.versions && process.versions.node) {
//NodeJS
o.os = process.platform;
o.nodejs = numberify(process.versions.node);
}
}
YUI.Env.UA = o;
}
return o;
};
Y.UA = YUI.Env.UA || YUI.Env.parseUA();
/**
Performs a simple comparison between two version numbers, accounting for
standard versioning logic such as the fact that "535.8" is a lower version than
"535.24", even though a simple numerical comparison would indicate that it's
greater. Also accounts for cases such as "1.1" vs. "1.1.0", which are
considered equivalent.
Returns -1 if version _a_ is lower than version _b_, 0 if they're equivalent,
1 if _a_ is higher than _b_.
Versions may be numbers or strings containing numbers and dots. For example,
both `535` and `"535.8.10"` are acceptable. A version string containing
non-numeric characters, like `"535.8.beta"`, may produce unexpected results.
@method compareVersions
@param {Number|String} a First version number to compare.
@param {Number|String} b Second version number to compare.
@return -1 if _a_ is lower than _b_, 0 if they're equivalent, 1 if _a_ is
higher than _b_.
**/
Y.UA.compareVersions = function (a, b) {
var aPart, aParts, bPart, bParts, i, len;
if (a === b) {
return 0;
}
aParts = (a + '').split('.');
bParts = (b + '').split('.');
for (i = 0, len = Math.max(aParts.length, bParts.length); i < len; ++i) {
aPart = parseInt(aParts[i], 10);
bPart = parseInt(bParts[i], 10);
/*jshint expr: true*/
isNaN(aPart) && (aPart = 0);
isNaN(bPart) && (bPart = 0);
if (aPart < bPart) {
return -1;
}
if (aPart > bPart) {
return 1;
}
}
return 0;
};
YUI.Env.aliases = {
"anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"],
"anim-shape-transform": ["anim-shape"],
"app": ["app-base","app-content","app-transitions","lazy-model-list","model","model-list","model-sync-rest","router","view","view-node-map"],
"attribute": ["attribute-base","attribute-complex"],
"attribute-events": ["attribute-observable"],
"autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"],
"axes": ["axis-numeric","axis-category","axis-time","axis-stacked"],
"axes-base": ["axis-numeric-base","axis-category-base","axis-time-base","axis-stacked-base"],
"base": ["base-base","base-pluginhost","base-build"],
"cache": ["cache-base","cache-offline","cache-plugin"],
"charts": ["charts-base"],
"collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"],
"color": ["color-base","color-hsl","color-harmony"],
"controller": ["router"],
"dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"],
"datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"],
"datatable": ["datatable-core","datatable-table","datatable-head","datatable-body","datatable-base","datatable-column-widths","datatable-message","datatable-mutable","datatable-sort","datatable-datasource"],
"datatype": ["datatype-date","datatype-number","datatype-xml"],
"datatype-date": ["datatype-date-parse","datatype-date-format","datatype-date-math"],
"datatype-number": ["datatype-number-parse","datatype-number-format"],
"datatype-xml": ["datatype-xml-parse","datatype-xml-format"],
"dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"],
"dom": ["dom-base","dom-screen","dom-style","selector-native","selector"],
"editor": ["frame","editor-selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"],
"event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside","event-touch","event-move","event-flick","event-valuechange","event-tap"],
"event-custom": ["event-custom-base","event-custom-complex"],
"event-gestures": ["event-flick","event-move"],
"handlebars": ["handlebars-compiler"],
"highlight": ["highlight-base","highlight-accentfold"],
"history": ["history-base","history-hash","history-hash-ie","history-html5"],
"io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"],
"json": ["json-parse","json-stringify"],
"loader": ["loader-base","loader-rollup","loader-yui3"],
"node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"],
"pluginhost": ["pluginhost-base","pluginhost-config"],
"querystring": ["querystring-parse","querystring-stringify"],
"recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"],
"resize": ["resize-base","resize-proxy","resize-constrain"],
"slider": ["slider-base","slider-value-range","clickable-rail","range-slider"],
"template": ["template-base","template-micro"],
"text": ["text-accentfold","text-wordbreak"],
"widget": ["widget-base","widget-htmlparser","widget-skin","widget-uievents"]
};
}, '@VERSION@', {"use": ["get", "features", "intl-base", "yui-log", "yui-later"]});
YUI.add('get', function (Y, NAME) {
/*jslint boss:true, expr:true, laxbreak: true */
/**
Provides dynamic loading of remote JavaScript and CSS resources.
@module get
@class Get
@static
**/
var Lang = Y.Lang,
CUSTOM_ATTRS, // defined lazily in Y.Get.Transaction._createNode()
Get, Transaction;
Y.Get = Get = {
// -- Public Properties ----------------------------------------------------
/**
Default options for CSS requests. Options specified here will override
global defaults for CSS requests.
See the `options` property for all available options.
@property cssOptions
@type Object
@static
@since 3.5.0
**/
cssOptions: {
attributes: {
rel: 'stylesheet'
},
doc : Y.config.linkDoc || Y.config.doc,
pollInterval: 50
},
/**
Default options for JS requests. Options specified here will override global
defaults for JS requests.
See the `options` property for all available options.
@property jsOptions
@type Object
@static
@since 3.5.0
**/
jsOptions: {
autopurge: true,
doc : Y.config.scriptDoc || Y.config.doc
},
/**
Default options to use for all requests.
Note that while all available options are documented here for ease of
discovery, some options (like callback functions) only make sense at the
transaction level.
Callback functions specified via the options object or the `options`
parameter of the `css()`, `js()`, or `load()` methods will receive the
transaction object as a parameter. See `Y.Get.Transaction` for details on
the properties and methods available on transactions.
@static
@since 3.5.0
@property {Object} options
@property {Boolean} [options.async=false] Whether or not to load scripts
asynchronously, meaning they're requested in parallel and execution
order is not guaranteed. Has no effect on CSS, since CSS is always
loaded asynchronously.
@property {Object} [options.attributes] HTML attribute name/value pairs that
should be added to inserted nodes. By default, the `charset` attribute
will be set to "utf-8" and nodes will be given an auto-generated `id`
attribute, but you can override these with your own values if desired.
@property {Boolean} [options.autopurge] Whether or not to automatically
purge inserted nodes after the purge threshold is reached. This is
`true` by default for JavaScript, but `false` for CSS since purging a
CSS node will also remove any styling applied by the referenced file.
@property {Object} [options.context] `this` object to use when calling
callback functions. Defaults to the transaction object.
@property {Mixed} [options.data] Arbitrary data object to pass to "on*"
callbacks.
@property {Document} [options.doc] Document into which nodes should be
inserted. By default, the current document is used.
@property {HTMLElement|String} [options.insertBefore] HTML element or id
string of an element before which all generated nodes should be
inserted. If not specified, Get will automatically determine the best
place to insert nodes for maximum compatibility.
@property {Function} [options.onEnd] Callback to execute after a transaction
is complete, regardless of whether it succeeded or failed.
@property {Function} [options.onFailure] Callback to execute after a
transaction fails, times out, or is aborted.
@property {Function} [options.onProgress] Callback to execute after each
individual request in a transaction either succeeds or fails.
@property {Function} [options.onSuccess] Callback to execute after a
transaction completes successfully with no errors. Note that in browsers
that don't support the `error` event on CSS `<link>` nodes, a failed CSS
request may still be reported as a success because in these browsers
it can be difficult or impossible to distinguish between success and
failure for CSS resources.
@property {Function} [options.onTimeout] Callback to execute after a
transaction times out.
@property {Number} [options.pollInterval=50] Polling interval (in
milliseconds) for detecting CSS load completion in browsers that don't
support the `load` event on `<link>` nodes. This isn't used for
JavaScript.
@property {Number} [options.purgethreshold=20] Number of nodes to insert
before triggering an automatic purge when `autopurge` is `true`.
@property {Number} [options.timeout] Number of milliseconds to wait before
aborting a transaction. When a timeout occurs, the `onTimeout` callback
is called, followed by `onFailure` and finally `onEnd`. By default,
there is no timeout.
@property {String} [options.type] Resource type ("css" or "js"). This option
is set automatically by the `css()` and `js()` functions and will be
ignored there, but may be useful when using the `load()` function. If
not specified, the type will be inferred from the URL, defaulting to
"js" if the URL doesn't contain a recognizable file extension.
**/
options: {
attributes: {
charset: 'utf-8'
},
purgethreshold: 20
},
// -- Protected Properties -------------------------------------------------
/**
Regex that matches a CSS URL. Used to guess the file type when it's not
specified.
@property REGEX_CSS
@type RegExp
@final
@protected
@static
@since 3.5.0
**/
REGEX_CSS: /\.css(?:[?;].*)?$/i,
/**
Regex that matches a JS URL. Used to guess the file type when it's not
specified.
@property REGEX_JS
@type RegExp
@final
@protected
@static
@since 3.5.0
**/
REGEX_JS : /\.js(?:[?;].*)?$/i,
/**
Contains information about the current environment, such as what script and
link injection features it supports.
This object is created and populated the first time the `_getEnv()` method
is called.
@property _env
@type Object
@protected
@static
@since 3.5.0
**/
/**
Mapping of document _yuid strings to <head> or <base> node references so we
don't have to look the node up each time we want to insert a request node.
@property _insertCache
@type Object
@protected
@static
@since 3.5.0
**/
_insertCache: {},
/**
Information about the currently pending transaction, if any.
This is actually an object with two properties: `callback`, containing the
optional callback passed to `css()`, `load()`, or `js()`; and `transaction`,
containing the actual transaction instance.
@property _pending
@type Object
@protected
@static
@since 3.5.0
**/
_pending: null,
/**
HTML nodes eligible to be purged next time autopurge is triggered.
@property _purgeNodes
@type HTMLElement[]
@protected
@static
@since 3.5.0
**/
_purgeNodes: [],
/**
Queued transactions and associated callbacks.
@property _queue
@type Object[]
@protected
@static
@since 3.5.0
**/
_queue: [],
// -- Public Methods -------------------------------------------------------
/**
Aborts the specified transaction.
This will cause the transaction's `onFailure` callback to be called and
will prevent any new script and link nodes from being added to the document,
but any resources that have already been requested will continue loading
(there's no safe way to prevent this, unfortunately).
*Note:* This method is deprecated as of 3.5.0, and will be removed in a
future version of YUI. Use the transaction-level `abort()` method instead.
@method abort
@param {Get.Transaction} transaction Transaction to abort.
@deprecated Use the `abort()` method on the transaction instead.
@static
**/
abort: function (transaction) {
var i, id, item, len, pending;
Y.log('`Y.Get.abort()` is deprecated as of 3.5.0. Use the `abort()` method on the transaction instead.', 'warn', 'get');
if (!transaction.abort) {
id = transaction;
pending = this._pending;
transaction = null;
if (pending && pending.transaction.id === id) {
transaction = pending.transaction;
this._pending = null;
} else {
for (i = 0, len = this._queue.length; i < len; ++i) {
item = this._queue[i].transaction;
if (item.id === id) {
transaction = item;
this._queue.splice(i, 1);
break;
}
}
}
}
transaction && transaction.abort();
},
/**
Loads one or more CSS files.
The _urls_ parameter may be provided as a URL string, a request object,
or an array of URL strings and/or request objects.
A request object is just an object that contains a `url` property and zero
or more options that should apply specifically to that request.
Request-specific options take priority over transaction-level options and
default options.
URLs may be relative or absolute, and do not have to have the same origin
as the current page.
The `options` parameter may be omitted completely and a callback passed in
its place, if desired.
@example
// Load a single CSS file and log a message on completion.
Y.Get.css('foo.css', function (err) {
if (err) {
Y.log('foo.css failed to load!');
} else {
Y.log('foo.css was loaded successfully');
}
});
// Load multiple CSS files and log a message when all have finished
// loading.
var urls = ['foo.css', 'http://example.com/bar.css', 'baz/quux.css'];
Y.Get.css(urls, function (err) {
if (err) {
Y.log('one or more files failed to load!');
} else {
Y.log('all files loaded successfully');
}
});
// Specify transaction-level options, which will apply to all requests
// within the transaction.
Y.Get.css(urls, {
attributes: {'class': 'my-css'},
timeout : 5000
});
// Specify per-request options, which override transaction-level and
// default options.
Y.Get.css([
{url: 'foo.css', attributes: {id: 'foo'}},
{url: 'bar.css', attributes: {id: 'bar', charset: 'iso-8859-1'}}
]);
@method css
@param {String|Object|Array} urls URL string, request object, or array
of URLs and/or request objects to load.
@param {Object} [options] Options for this transaction. See the
`Y.Get.options` property for a complete list of available options.
@param {Function} [callback] Callback function to be called on completion.
This is a general callback and will be called before any more granular
callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options`
object.
@param {Array|null} callback.err Array of errors that occurred during
the transaction, or `null` on success.
@param {Get.Transaction} callback.transaction Transaction object.
@return {Get.Transaction} Transaction object.
@static
**/
css: function (urls, options, callback) {
return this._load('css', urls, options, callback);
},
/**
Loads one or more JavaScript resources.
The _urls_ parameter may be provided as a URL string, a request object,
or an array of URL strings and/or request objects.
A request object is just an object that contains a `url` property and zero
or more options that should apply specifically to that request.
Request-specific options take priority over transaction-level options and
default options.
URLs may be relative or absolute, and do not have to have the same origin
as the current page.
The `options` parameter may be omitted completely and a callback passed in
its place, if desired.
Scripts will be executed in the order they're specified unless the `async`
option is `true`, in which case they'll be loaded in parallel and executed
in whatever order they finish loading.
@example
// Load a single JS file and log a message on completion.
Y.Get.js('foo.js', function (err) {
if (err) {
Y.log('foo.js failed to load!');
} else {
Y.log('foo.js was loaded successfully');
}
});
// Load multiple JS files, execute them in order, and log a message when
// all have finished loading.
var urls = ['foo.js', 'http://example.com/bar.js', 'baz/quux.js'];
Y.Get.js(urls, function (err) {
if (err) {
Y.log('one or more files failed to load!');
} else {
Y.log('all files loaded successfully');
}
});
// Specify transaction-level options, which will apply to all requests
// within the transaction.
Y.Get.js(urls, {
attributes: {'class': 'my-js'},
timeout : 5000
});
// Specify per-request options, which override transaction-level and
// default options.
Y.Get.js([
{url: 'foo.js', attributes: {id: 'foo'}},
{url: 'bar.js', attributes: {id: 'bar', charset: 'iso-8859-1'}}
]);
@method js
@param {String|Object|Array} urls URL string, request object, or array
of URLs and/or request objects to load.
@param {Object} [options] Options for this transaction. See the
`Y.Get.options` property for a complete list of available options.
@param {Function} [callback] Callback function to be called on completion.
This is a general callback and will be called before any more granular
callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options`
object.
@param {Array|null} callback.err Array of errors that occurred during
the transaction, or `null` on success.
@param {Get.Transaction} callback.transaction Transaction object.
@return {Get.Transaction} Transaction object.
@since 3.5.0
@static
**/
js: function (urls, options, callback) {
return this._load('js', urls, options, callback);
},
/**
Loads one or more CSS and/or JavaScript resources in the same transaction.
Use this method when you want to load both CSS and JavaScript in a single
transaction and be notified when all requested URLs have finished loading,
regardless of type.
Behavior and options are the same as for the `css()` and `js()` methods. If
a resource type isn't specified in per-request options or transaction-level
options, Get will guess the file type based on the URL's extension (`.css`
or `.js`, with or without a following query string). If the file type can't
be guessed from the URL, a warning will be logged and Get will assume the
URL is a JavaScript resource.
@example
// Load both CSS and JS files in a single transaction, and log a message
// when all files have finished loading.
Y.Get.load(['foo.css', 'bar.js', 'baz.css'], function (err) {
if (err) {
Y.log('one or more files failed to load!');
} else {
Y.log('all files loaded successfully');
}
});
@method load
@param {String|Object|Array} urls URL string, request object, or array
of URLs and/or request objects to load.
@param {Object} [options] Options for this transaction. See the
`Y.Get.options` property for a complete list of available options.
@param {Function} [callback] Callback function to be called on completion.
This is a general callback and will be called before any more granular
callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options`
object.
@param {Array|null} err Array of errors that occurred during the
transaction, or `null` on success.
@param {Get.Transaction} Transaction object.
@return {Get.Transaction} Transaction object.
@since 3.5.0
@static
**/
load: function (urls, options, callback) {
return this._load(null, urls, options, callback);
},
// -- Protected Methods ----------------------------------------------------
/**
Triggers an automatic purge if the purge threshold has been reached.
@method _autoPurge
@param {Number} threshold Purge threshold to use, in milliseconds.
@protected
@since 3.5.0
@static
**/
_autoPurge: function (threshold) {
if (threshold && this._purgeNodes.length >= threshold) {
Y.log('autopurge triggered after ' + this._purgeNodes.length + ' nodes', 'info', 'get');
this._purge(this._purgeNodes);
}
},
/**
Populates the `_env` property with information about the current
environment.
@method _getEnv
@return {Object} Environment information.
@protected
@since 3.5.0
@static
**/
_getEnv: function () {
var doc = Y.config.doc,
ua = Y.UA;
// Note: some of these checks require browser sniffs since it's not
// feasible to load test files on every pageview just to perform a
// feature test. I'm sorry if this makes you sad.
return (this._env = {
// True if this is a browser that supports disabling async mode on
// dynamically created script nodes. See
// https://developer.mozilla.org/En/HTML/Element/Script#Attributes
// IE10 doesn't return true for the MDN feature test, so setting it explicitly,
// because it is async by default, and allows you to disable async by setting it to false
async: (doc && doc.createElement('script').async === true) || (ua.ie >= 10),
// True if this browser fires an event when a dynamically injected
// link node fails to load. This is currently true for Firefox 9+
// and WebKit 535.24+
cssFail: ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0,
// True if this browser fires an event when a dynamically injected
// link node finishes loading. This is currently true for IE, Opera,
// Firefox 9+, and WebKit 535.24+. Note that IE versions <9 fire the
// DOM 0 "onload" event, but not "load". All versions of IE fire
// "onload".
// davglass: Seems that Chrome on Android needs this to be false.
cssLoad: (
(!ua.gecko && !ua.webkit) || ua.gecko >= 9 ||
ua.compareVersions(ua.webkit, 535.24) >= 0
) && !(ua.chrome && ua.chrome <= 18),
// True if this browser preserves script execution order while
// loading scripts in parallel as long as the script node's `async`
// attribute is set to false to explicitly disable async execution.
preservesScriptOrder: !!(ua.gecko || ua.opera || (ua.ie && ua.ie >= 10))
});
},
_getTransaction: function (urls, options) {
var requests = [],
i, len, req, url;
if (!Lang.isArray(urls)) {
urls = [urls];
}
options = Y.merge(this.options, options);
// Clone the attributes object so we don't end up modifying it by ref.
options.attributes = Y.merge(this.options.attributes,
options.attributes);
for (i = 0, len = urls.length; i < len; ++i) {
url = urls[i];
req = {attributes: {}};
// If `url` is a string, we create a URL object for it, then mix in
// global options and request-specific options. If it's an object
// with a "url" property, we assume it's a request object containing
// URL-specific options.
if (typeof url === 'string') {
req.url = url;
} else if (url.url) {
// URL-specific options override both global defaults and
// request-specific options.
Y.mix(req, url, false, null, 0, true);
url = url.url; // Make url a string so we can use it later.
} else {
Y.log('URL must be a string or an object with a `url` property.', 'error', 'get');
continue;
}
Y.mix(req, options, false, null, 0, true);
// If we didn't get an explicit type for this URL either in the
// request options or the URL-specific options, try to determine
// one from the file extension.
if (!req.type) {
if (this.REGEX_CSS.test(url)) {
req.type = 'css';
} else {
if (!this.REGEX_JS.test(url)) {
Y.log("Can't guess file type from URL. Assuming JS: " + url, 'warn', 'get');
}
req.type = 'js';
}
}
// Mix in type-specific default options, but don't overwrite any
// options that have already been set.
Y.mix(req, req.type === 'js' ? this.jsOptions : this.cssOptions,
false, null, 0, true);
// Give the node an id attribute if it doesn't already have one.
req.attributes.id || (req.attributes.id = Y.guid());
// Backcompat for <3.5.0 behavior.
if (req.win) {
Y.log('The `win` option is deprecated as of 3.5.0. Use `doc` instead.', 'warn', 'get');
req.doc = req.win.document;
} else {
req.win = req.doc.defaultView || req.doc.parentWindow;
}
if (req.charset) {
Y.log('The `charset` option is deprecated as of 3.5.0. Set `attributes.charset` instead.', 'warn', 'get');
req.attributes.charset = req.charset;
}
requests.push(req);
}
return new Transaction(requests, options);
},
_load: function (type, urls, options, callback) {
var transaction;
// Allow callback as third param.
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
options.type = type;
options._onFinish = Get._onTransactionFinish;
if (!this._env) {
this._getEnv();
}
transaction = this._getTransaction(urls, options);
this._queue.push({
callback : callback,
transaction: transaction
});
this._next();
return transaction;
},
_onTransactionFinish : function() {
Get._pending = null;
Get._next();
},
_next: function () {
var item;
if (this._pending) {
return;
}
item = this._queue.shift();
if (item) {
this._pending = item;
item.transaction.execute(item.callback);
}
},
_purge: function (nodes) {
var purgeNodes = this._purgeNodes,
isTransaction = nodes !== purgeNodes,
index, node;
while (node = nodes.pop()) { // assignment
// Don't purge nodes that haven't finished loading (or errored out),
// since this can hang the transaction.
if (!node._yuiget_finished) {
continue;
}
node.parentNode && node.parentNode.removeChild(node);
// If this is a transaction-level purge and this node also exists in
// the Get-level _purgeNodes array, we need to remove it from
// _purgeNodes to avoid creating a memory leak. The indexOf lookup
// sucks, but until we get WeakMaps, this is the least troublesome
// way to do this (we can't just hold onto node ids because they may
// not be in the same document).
if (isTransaction) {
index = Y.Array.indexOf(purgeNodes, node);
if (index > -1) {
purgeNodes.splice(index, 1);
}
}
}
}
};
/**
Alias for `js()`.
@method script
@static
**/
Get.script = Get.js;
/**
Represents a Get transaction, which may contain requests for one or more JS or
CSS files.
This class should not be instantiated manually. Instances will be created and
returned as needed by Y.Get's `css()`, `js()`, and `load()` methods.
@class Get.Transaction
@constructor
@since 3.5.0
**/
Get.Transaction = Transaction = function (requests, options) {
var self = this;
self.id = Transaction._lastId += 1;
self.data = options.data;
self.errors = [];
self.nodes = [];
self.options = options;
self.requests = requests;
self._callbacks = []; // callbacks to call after execution finishes
self._queue = [];
self._reqsWaiting = 0;
// Deprecated pre-3.5.0 properties.
self.tId = self.id; // Use `id` instead.
self.win = options.win || Y.config.win;
};
/**
Arbitrary data object associated with this transaction.
This object comes from the options passed to `Get.css()`, `Get.js()`, or
`Get.load()`, and will be `undefined` if no data object was specified.
@property {Object} data
**/
/**
Array of errors that have occurred during this transaction, if any.
@since 3.5.0
@property {Object[]} errors
@property {String} errors.error Error message.
@property {Object} errors.request Request object related to the error.
**/
/**
Numeric id for this transaction, unique among all transactions within the same
YUI sandbox in the current pageview.
@property {Number} id
@since 3.5.0
**/
/**
HTMLElement nodes (native ones, not YUI Node instances) that have been inserted
during the current transaction.
@property {HTMLElement[]} nodes
**/
/**
Options associated with this transaction.
See `Get.options` for the full list of available options.
@property {Object} options
@since 3.5.0
**/
/**
Request objects contained in this transaction. Each request object represents
one CSS or JS URL that will be (or has been) requested and loaded into the page.
@property {Object} requests
@since 3.5.0
**/
/**
Id of the most recent transaction.
@property _lastId
@type Number
@protected
@static
**/
Transaction._lastId = 0;
Transaction.prototype = {
// -- Public Properties ----------------------------------------------------
/**
Current state of this transaction. One of "new", "executing", or "done".
@property _state
@type String
@protected
**/
_state: 'new', // "new", "executing", or "done"
// -- Public Methods -------------------------------------------------------
/**
Aborts this transaction.
This will cause the transaction's `onFailure` callback to be called and
will prevent any new script and link nodes from being added to the document,
but any resources that have already been requested will continue loading
(there's no safe way to prevent this, unfortunately).
@method abort
@param {String} [msg="Aborted."] Optional message to use in the `errors`
array describing why the transaction was aborted.
**/
abort: function (msg) {
this._pending = null;
this._pendingCSS = null;
this._pollTimer = clearTimeout(this._pollTimer);
this._queue = [];
this._reqsWaiting = 0;
this.errors.push({error: msg || 'Aborted'});
this._finish();
},
/**
Begins execting the transaction.
There's usually no reason to call this manually, since Get will call it
automatically when other pending transactions have finished. If you really
want to execute your transaction before Get does, you can, but be aware that
this transaction's scripts may end up executing before the scripts in other
pending transactions.
If the transaction is already executing, the specified callback (if any)
will be queued and called after execution finishes. If the transaction has
already finished, the callback will be called immediately (the transaction
will not be executed again).
@method execute
@param {Function} callback Callback function to execute after all requests
in the transaction are complete, or after the transaction is aborted.
**/
execute: function (callback) {
var self = this,
requests = self.requests,
state = self._state,
i, len, queue, req;
if (state === 'done') {
callback && callback(self.errors.length ? self.errors : null, self);
return;
} else {
callback && self._callbacks.push(callback);
if (state === 'executing') {
return;
}
}
self._state = 'executing';
self._queue = queue = [];
if (self.options.timeout) {
self._timeout = setTimeout(function () {
self.abort('Timeout');
}, self.options.timeout);
}
self._reqsWaiting = requests.length;
for (i = 0, len = requests.length; i < len; ++i) {
req = requests[i];
if (req.async || req.type === 'css') {
// No need to queue CSS or fully async JS.
self._insert(req);
} else {
queue.push(req);
}
}
self._next();
},
/**
Manually purges any `<script>` or `<link>` nodes this transaction has
created.
Be careful when purging a transaction that contains CSS requests, since
removing `<link>` nodes will also remove any styles they applied.
@method purge
**/
purge: function () {
Get._purge(this.nodes);
},
// -- Protected Methods ----------------------------------------------------
_createNode: function (name, attrs, doc) {
var node = doc.createElement(name),
attr, testEl;
if (!CUSTOM_ATTRS) {
// IE6 and IE7 expect property names rather than attribute names for
// certain attributes. Rather than sniffing, we do a quick feature
// test the first time _createNode() runs to determine whether we
// need to provide a workaround.
testEl = doc.createElement('div');
testEl.setAttribute('class', 'a');
CUSTOM_ATTRS = testEl.className === 'a' ? {} : {
'for' : 'htmlFor',
'class': 'className'
};
}
for (attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
node.setAttribute(CUSTOM_ATTRS[attr] || attr, attrs[attr]);
}
}
return node;
},
_finish: function () {
var errors = this.errors.length ? this.errors : null,
options = this.options,
thisObj = options.context || this,
data, i, len;
if (this._state === 'done') {
return;
}
this._state = 'done';
for (i = 0, len = this._callbacks.length; i < len; ++i) {
this._callbacks[i].call(thisObj, errors, this);
}
data = this._getEventData();
if (errors) {
if (options.onTimeout && errors[errors.length - 1].error === 'Timeout') {
options.onTimeout.call(thisObj, data);
}
if (options.onFailure) {
options.onFailure.call(thisObj, data);
}
} else if (options.onSuccess) {
options.onSuccess.call(thisObj, data);
}
if (options.onEnd) {
options.onEnd.call(thisObj, data);
}
if (options._onFinish) {
options._onFinish();
}
},
_getEventData: function (req) {
if (req) {
// This merge is necessary for backcompat. I hate it.
return Y.merge(this, {
abort : this.abort, // have to copy these because the prototype isn't preserved
purge : this.purge,
request: req,
url : req.url,
win : req.win
});
} else {
return this;
}
},
_getInsertBefore: function (req) {
var doc = req.doc,
el = req.insertBefore,
cache, docStamp;
if (el) {
return typeof el === 'string' ? doc.getElementById(el) : el;
}
cache = Get._insertCache;
docStamp = Y.stamp(doc);
if ((el = cache[docStamp])) { // assignment
return el;
}
// Inserting before a <base> tag apparently works around an IE bug
// (according to a comment from pre-3.5.0 Y.Get), but I'm not sure what
// bug that is, exactly. Better safe than sorry?
if ((el = doc.getElementsByTagName('base')[0])) { // assignment
return (cache[docStamp] = el);
}
// Look for a <head> element.
el = doc.head || doc.getElementsByTagName('head')[0];
if (el) {
// Create a marker node at the end of <head> to use as an insertion
// point. Inserting before this node will ensure that all our CSS
// gets inserted in the correct order, to maintain style precedence.
el.appendChild(doc.createTextNode(''));
return (cache[docStamp] = el.lastChild);
}
// If all else fails, just insert before the first script node on the
// page, which is virtually guaranteed to exist.
return (cache[docStamp] = doc.getElementsByTagName('script')[0]);
},
_insert: function (req) {
var env = Get._env,
insertBefore = this._getInsertBefore(req),
isScript = req.type === 'js',
node = req.node,
self = this,
ua = Y.UA,
cssTimeout, nodeType;
if (!node) {
if (isScript) {
nodeType = 'script';
} else if (!env.cssLoad && ua.gecko) {
nodeType = 'style';
} else {
nodeType = 'link';
}
node = req.node = this._createNode(nodeType, req.attributes,
req.doc);
}
function onError() {
self._progress('Failed to load ' + req.url, req);
}
function onLoad() {
if (cssTimeout) {
clearTimeout(cssTimeout);
}
self._progress(null, req);
}
// Deal with script asynchronicity.
if (isScript) {
node.setAttribute('src', req.url);
if (req.async) {
// Explicitly indicate that we want the browser to execute this
// script asynchronously. This is necessary for older browsers
// like Firefox <4.
node.async = true;
} else {
if (env.async) {
// This browser treats injected scripts as async by default
// (standard HTML5 behavior) but asynchronous loading isn't
// desired, so tell the browser not to mark this script as
// async.
node.async = false;
}
// If this browser doesn't preserve script execution order based
// on insertion order, we'll need to avoid inserting other
// scripts until this one finishes loading.
if (!env.preservesScriptOrder) {
this._pending = req;
}
}
} else {
if (!env.cssLoad && ua.gecko) {
// In Firefox <9, we can import the requested URL into a <style>
// node and poll for the existence of node.sheet.cssRules. This
// gives us a reliable way to determine CSS load completion that
// also works for cross-domain stylesheets.
//
// Props to Zach Leatherman for calling my attention to this
// technique.
node.innerHTML = (req.attributes.charset ?
'@charset "' + req.attributes.charset + '";' : '') +
'@import "' + req.url + '";';
} else {
node.setAttribute('href', req.url);
}
}
// Inject the node.
if (isScript && ua.ie && (ua.ie < 9 || (document.documentMode && document.documentMode < 9))) {
// Script on IE < 9, and IE 9+ when in IE 8 or older modes, including quirks mode.
node.onreadystatechange = function () {
if (/loaded|complete/.test(node.readyState)) {
node.onreadystatechange = null;
onLoad();
}
};
} else if (!isScript && !env.cssLoad) {
// CSS on Firefox <9 or WebKit.
this._poll(req);
} else {
// Script or CSS on everything else. Using DOM 0 events because that
// evens the playing field with older IEs.
if (ua.ie >= 10) {
// We currently need to introduce a timeout for IE10, since it
// calls onerror/onload synchronously for 304s - messing up existing
// program flow.
// Remove this block if the following bug gets fixed by GA
/*jshint maxlen: 1500 */
// https://connect.microsoft.com/IE/feedback/details/763871/dynamically-loaded-scripts-with-304s-responses-interrupt-the-currently-executing-js-thread-onload
node.onerror = function() { setTimeout(onError, 0); };
node.onload = function() { setTimeout(onLoad, 0); };
} else {
node.onerror = onError;
node.onload = onLoad;
}
// If this browser doesn't fire an event when CSS fails to load,
// fail after a timeout to avoid blocking the transaction queue.
if (!env.cssFail && !isScript) {
cssTimeout = setTimeout(onError, req.timeout || 3000);
}
}
this.nodes.push(node);
insertBefore.parentNode.insertBefore(node, insertBefore);
},
_next: function () {
if (this._pending) {
return;
}
// If there are requests in the queue, insert the next queued request.
// Otherwise, if we're waiting on already-inserted requests to finish,
// wait longer. If there are no queued requests and we're not waiting
// for anything to load, then we're done!
if (this._queue.length) {
this._insert(this._queue.shift());
} else if (!this._reqsWaiting) {
this._finish();
}
},
_poll: function (newReq) {
var self = this,
pendingCSS = self._pendingCSS,
isWebKit = Y.UA.webkit,
i, hasRules, j, nodeHref, req, sheets;
if (newReq) {
pendingCSS || (pendingCSS = self._pendingCSS = []);
pendingCSS.push(newReq);
if (self._pollTimer) {
// A poll timeout is already pending, so no need to create a
// new one.
return;
}
}
self._pollTimer = null;
// Note: in both the WebKit and Gecko hacks below, a CSS URL that 404s
// will still be treated as a success. There's no good workaround for
// this.
for (i = 0; i < pendingCSS.length; ++i) {
req = pendingCSS[i];
if (isWebKit) {
// Look for a stylesheet matching the pending URL.
sheets = req.doc.styleSheets;
j = sheets.length;
nodeHref = req.node.href;
while (--j >= 0) {
if (sheets[j].href === nodeHref) {
pendingCSS.splice(i, 1);
i -= 1;
self._progress(null, req);
break;
}
}
} else {
// Many thanks to Zach Leatherman for calling my attention to
// the @import-based cross-domain technique used here, and to
// Oleg Slobodskoi for an earlier same-domain implementation.
//
// See Zach's blog for more details:
// http://www.zachleat.com/web/2010/07/29/load-css-dynamically/
try {
// We don't really need to store this value since we never
// use it again, but if we don't store it, Closure Compiler
// assumes the code is useless and removes it.
hasRules = !!req.node.sheet.cssRules;
// If we get here, the stylesheet has loaded.
pendingCSS.splice(i, 1);
i -= 1;
self._progress(null, req);
} catch (ex) {
// An exception means the stylesheet is still loading.
}
}
}
if (pendingCSS.length) {
self._pollTimer = setTimeout(function () {
self._poll.call(self);
}, self.options.pollInterval);
}
},
_progress: function (err, req) {
var options = this.options;
if (err) {
req.error = err;
this.errors.push({
error : err,
request: req
});
Y.log(err, 'error', 'get');
}
req.node._yuiget_finished = req.finished = true;
if (options.onProgress) {
options.onProgress.call(options.context || this,
this._getEventData(req));
}
if (req.autopurge) {
// Pre-3.5.0 Get always excludes the most recent node from an
// autopurge. I find this odd, but I'm keeping that behavior for
// the sake of backcompat.
Get._autoPurge(this.options.purgethreshold);
Get._purgeNodes.push(req.node);
}
if (this._pending === req) {
this._pending = null;
}
this._reqsWaiting -= 1;
this._next();
}
};
}, '@VERSION@', {"requires": ["yui-base"]});
YUI.add('features', function (Y, NAME) {
var feature_tests = {};
/**
Contains the core of YUI's feature test architecture.
@module features
*/
/**
* Feature detection
* @class Features
* @static
*/
Y.mix(Y.namespace('Features'), {
/**
* Object hash of all registered feature tests
* @property tests
* @type Object
*/
tests: feature_tests,
/**
* Add a test to the system
*
* ```
* Y.Features.add("load", "1", {});
* ```
*
* @method add
* @param {String} cat The category, right now only 'load' is supported
* @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3
* @param {Object} o Object containing test properties
* @param {String} o.name The name of the test
* @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance
* @param {String} o.trigger The module that triggers this test.
*/
add: function(cat, name, o) {
feature_tests[cat] = feature_tests[cat] || {};
feature_tests[cat][name] = o;
},
/**
* Execute all tests of a given category and return the serialized results
*
* ```
* caps=1:1;2:1;3:0
* ```
* @method all
* @param {String} cat The category to execute
* @param {Array} args The arguments to pass to the test function
* @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0
*/
all: function(cat, args) {
var cat_o = feature_tests[cat],
// results = {};
result = [];
if (cat_o) {
Y.Object.each(cat_o, function(v, k) {
result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0));
});
}
return (result.length) ? result.join(';') : '';
},
/**
* Run a sepecific test and return a Boolean response.
*
* ```
* Y.Features.test("load", "1");
* ```
*
* @method test
* @param {String} cat The category of the test to run
* @param {String} name The name of the test to run
* @param {Array} args The arguments to pass to the test function
* @return {Boolean} True or false if the test passed/failed.
*/
test: function(cat, name, args) {
args = args || [];
var result, ua, test,
cat_o = feature_tests[cat],
feature = cat_o && cat_o[name];
if (!feature) {
Y.log('Feature test ' + cat + ', ' + name + ' not found');
} else {
result = feature.result;
if (Y.Lang.isUndefined(result)) {
ua = feature.ua;
if (ua) {
result = (Y.UA[ua]);
}
test = feature.test;
if (test && ((!ua) || result)) {
result = test.apply(Y, args);
}
feature.result = result;
}
}
return result;
}
});
// Y.Features.add("load", "1", {});
// Y.Features.test("load", "1");
// caps=1:1;2:0;3:1;
/* This file is auto-generated by (yogi loader --yes --mix --start ../) */
/*jshint maxlen:900, eqeqeq: false */
var add = Y.Features.add;
// app-transitions-native
add('load', '0', {
"name": "app-transitions-native",
"test": function (Y) {
var doc = Y.config.doc,
node = doc ? doc.documentElement : null;
if (node && node.style) {
return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style);
}
return false;
},
"trigger": "app-transitions"
});
// autocomplete-list-keys
add('load', '1', {
"name": "autocomplete-list-keys",
"test": function (Y) {
// Only add keyboard support to autocomplete-list if this doesn't appear to
// be an iOS or Android-based mobile device.
//
// There's currently no feasible way to actually detect whether a device has
// a hardware keyboard, so this sniff will have to do. It can easily be
// overridden by manually loading the autocomplete-list-keys module.
//
// Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari
// doesn't fire the keyboard events used by AutoCompleteList, so there's
// no point loading the -keys module even when a bluetooth keyboard may be
// available.
return !(Y.UA.ios || Y.UA.android);
},
"trigger": "autocomplete-list"
});
// dd-gestures
add('load', '2', {
"name": "dd-gestures",
"trigger": "dd-drag",
"ua": "touchEnabled"
});
// dom-style-ie
add('load', '3', {
"name": "dom-style-ie",
"test": function (Y) {
var testFeature = Y.Features.test,
addFeature = Y.Features.add,
WINDOW = Y.config.win,
DOCUMENT = Y.config.doc,
DOCUMENT_ELEMENT = 'documentElement',
ret = false;
addFeature('style', 'computedStyle', {
test: function() {
return WINDOW && 'getComputedStyle' in WINDOW;
}
});
addFeature('style', 'opacity', {
test: function() {
return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style;
}
});
ret = (!testFeature('style', 'opacity') &&
!testFeature('style', 'computedStyle'));
return ret;
},
"trigger": "dom-style"
});
// editor-para-ie
add('load', '4', {
"name": "editor-para-ie",
"trigger": "editor-para",
"ua": "ie",
"when": "instead"
});
// event-base-ie
add('load', '5', {
"name": "event-base-ie",
"test": function(Y) {
var imp = Y.config.doc && Y.config.doc.implementation;
return (imp && (!imp.hasFeature('Events', '2.0')));
},
"trigger": "node-base"
});
// graphics-canvas
add('load', '6', {
"name": "graphics-canvas",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas",
canvas = DOCUMENT && DOCUMENT.createElement("canvas"),
svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d"));
},
"trigger": "graphics"
});
// graphics-canvas-default
add('load', '7', {
"name": "graphics-canvas-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas",
canvas = DOCUMENT && DOCUMENT.createElement("canvas"),
svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d"));
},
"trigger": "graphics"
});
// graphics-svg
add('load', '8', {
"name": "graphics-svg",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas",
canvas = DOCUMENT && DOCUMENT.createElement("canvas"),
svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
return svg && (useSVG || !canvas);
},
"trigger": "graphics"
});
// graphics-svg-default
add('load', '9', {
"name": "graphics-svg-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas",
canvas = DOCUMENT && DOCUMENT.createElement("canvas"),
svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
return svg && (useSVG || !canvas);
},
"trigger": "graphics"
});
// graphics-vml
add('load', '10', {
"name": "graphics-vml",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d")));
},
"trigger": "graphics"
});
// graphics-vml-default
add('load', '11', {
"name": "graphics-vml-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d")));
},
"trigger": "graphics"
});
// history-hash-ie
add('load', '12', {
"name": "history-hash-ie",
"test": function (Y) {
var docMode = Y.config.doc && Y.config.doc.documentMode;
return Y.UA.ie && (!('onhashchange' in Y.config.win) ||
!docMode || docMode < 8);
},
"trigger": "history-hash"
});
// io-nodejs
add('load', '13', {
"name": "io-nodejs",
"trigger": "io-base",
"ua": "nodejs"
});
// json-parse-shim
add('load', '14', {
"name": "json-parse-shim",
"test": function (Y) {
var _JSON = Y.config.global.JSON,
Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON,
nativeSupport = Y.config.useNativeJSONParse !== false && !!Native;
function workingNative( k, v ) {
return k === "ok" ? true : v;
}
// Double check basic functionality. This is mainly to catch early broken
// implementations of the JSON API in Firefox 3.1 beta1 and beta2
if ( nativeSupport ) {
try {
nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok;
}
catch ( e ) {
nativeSupport = false;
}
}
return !nativeSupport;
},
"trigger": "json-parse"
});
// json-stringify-shim
add('load', '15', {
"name": "json-stringify-shim",
"test": function (Y) {
var _JSON = Y.config.global.JSON,
Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON,
nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native;
// Double check basic native functionality. This is primarily to catch broken
// early JSON API implementations in Firefox 3.1 beta1 and beta2.
if ( nativeSupport ) {
try {
nativeSupport = ( '0' === Native.stringify(0) );
} catch ( e ) {
nativeSupport = false;
}
}
return !nativeSupport;
},
"trigger": "json-stringify"
});
// scrollview-base-ie
add('load', '16', {
"name": "scrollview-base-ie",
"trigger": "scrollview-base",
"ua": "ie"
});
// selector-css2
add('load', '17', {
"name": "selector-css2",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
ret = DOCUMENT && !('querySelectorAll' in DOCUMENT);
return ret;
},
"trigger": "selector"
});
// transition-timer
add('load', '18', {
"name": "transition-timer",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
node = (DOCUMENT) ? DOCUMENT.documentElement: null,
ret = true;
if (node && node.style) {
ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style);
}
return ret;
},
"trigger": "transition"
});
// widget-base-ie
add('load', '19', {
"name": "widget-base-ie",
"trigger": "widget-base",
"ua": "ie"
});
// yql-jsonp
add('load', '20', {
"name": "yql-jsonp",
"test": function (Y) {
/* Only load the JSONP module when not in nodejs or winjs
TODO Make the winjs module a CORS module
*/
return (!Y.UA.nodejs && !Y.UA.winjs);
},
"trigger": "yql",
"when": "after"
});
// yql-nodejs
add('load', '21', {
"name": "yql-nodejs",
"trigger": "yql",
"ua": "nodejs",
"when": "after"
});
// yql-winjs
add('load', '22', {
"name": "yql-winjs",
"trigger": "yql",
"ua": "winjs",
"when": "after"
});
}, '@VERSION@', {"requires": ["yui-base"]});
YUI.add('intl-base', function (Y, NAME) {
/**
* The Intl utility provides a central location for managing sets of
* localized resources (strings and formatting patterns).
*
* @class Intl
* @uses EventTarget
* @static
*/
var SPLIT_REGEX = /[, ]/;
Y.mix(Y.namespace('Intl'), {
/**
* Returns the language among those available that
* best matches the preferred language list, using the Lookup
* algorithm of BCP 47.
* If none of the available languages meets the user's preferences,
* then "" is returned.
* Extended language ranges are not supported.
*
* @method lookupBestLang
* @param {String[] | String} preferredLanguages The list of preferred
* languages in descending preference order, represented as BCP 47
* language tags. A string array or a comma-separated list.
* @param {String[]} availableLanguages The list of languages
* that the application supports, represented as BCP 47 language
* tags.
*
* @return {String} The available language that best matches the
* preferred language list, or "".
* @since 3.1.0
*/
lookupBestLang: function(preferredLanguages, availableLanguages) {
var i, language, result, index;
// check whether the list of available languages contains language;
// if so return it
function scan(language) {
var i;
for (i = 0; i < availableLanguages.length; i += 1) {
if (language.toLowerCase() ===
availableLanguages[i].toLowerCase()) {
return availableLanguages[i];
}
}
}
if (Y.Lang.isString(preferredLanguages)) {
preferredLanguages = preferredLanguages.split(SPLIT_REGEX);
}
for (i = 0; i < preferredLanguages.length; i += 1) {
language = preferredLanguages[i];
if (!language || language === '*') {
continue;
}
// check the fallback sequence for one language
while (language.length > 0) {
result = scan(language);
if (result) {
return result;
} else {
index = language.lastIndexOf('-');
if (index >= 0) {
language = language.substring(0, index);
// one-character subtags get cut along with the
// following subtag
if (index >= 2 && language.charAt(index - 2) === '-') {
language = language.substring(0, index - 2);
}
} else {
// nothing available for this language
break;
}
}
}
}
return '';
}
});
}, '@VERSION@', {"requires": ["yui-base"]});
YUI.add('yui-log', function (Y, NAME) {
/**
* Provides console log capability and exposes a custom event for
* console implementations. This module is a `core` YUI module,
* <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>.
*
* @module yui
* @submodule yui-log
*/
var INSTANCE = Y,
LOGEVENT = 'yui:log',
UNDEFINED = 'undefined',
LEVELS = { debug: 1,
info: 2,
warn: 4,
error: 8 };
/**
* If the 'debug' config is true, a 'yui:log' event will be
* dispatched, which the Console widget and anything else
* can consume. If the 'useBrowserConsole' config is true, it will
* write to the browser console if available. YUI-specific log
* messages will only be present in the -debug versions of the
* JS files. The build system is supposed to remove log statements
* from the raw and minified versions of the files.
*
* @method log
* @for YUI
* @param {String} msg The message to log.
* @param {String} cat The log category for the message. Default
* categories are "info", "warn", "error", time".
* Custom categories can be used as well. (opt).
* @param {String} src The source of the the message (opt).
* @param {boolean} silent If true, the log event won't fire.
* @return {YUI} YUI instance.
*/
INSTANCE.log = function(msg, cat, src, silent) {
var bail, excl, incl, m, f, minlevel,
Y = INSTANCE,
c = Y.config,
publisher = (Y.fire) ? Y : YUI.Env.globalEvents;
// suppress log message if the config is off or the event stack
// or the event call stack contains a consumer of the yui:log event
if (c.debug) {
// apply source filters
src = src || "";
if (typeof src !== "undefined") {
excl = c.logExclude;
incl = c.logInclude;
if (incl && !(src in incl)) {
bail = 1;
} else if (incl && (src in incl)) {
bail = !incl[src];
} else if (excl && (src in excl)) {
bail = excl[src];
}
// Determine the current minlevel as defined in configuration
Y.config.logLevel = Y.config.logLevel || 'debug';
minlevel = LEVELS[Y.config.logLevel.toLowerCase()];
if (cat in LEVELS && LEVELS[cat] < minlevel) {
// Skip this message if the we don't meet the defined minlevel
bail = 1;
}
}
if (!bail) {
if (c.useBrowserConsole) {
m = (src) ? src + ': ' + msg : msg;
if (Y.Lang.isFunction(c.logFn)) {
c.logFn.call(Y, msg, cat, src);
} else if (typeof console !== UNDEFINED && console.log) {
f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log';
console[f](m);
} else if (typeof opera !== UNDEFINED) {
opera.postError(m);
}
}
if (publisher && !silent) {
if (publisher === Y && (!publisher.getEvent(LOGEVENT))) {
publisher.publish(LOGEVENT, {
broadcast: 2
});
}
publisher.fire(LOGEVENT, {
msg: msg,
cat: cat,
src: src
});
}
}
}
return Y;
};
/**
* Write a system message. This message will be preserved in the
* minified and raw versions of the YUI files, unlike log statements.
* @method message
* @for YUI
* @param {String} msg The message to log.
* @param {String} cat The log category for the message. Default
* categories are "info", "warn", "error", time".
* Custom categories can be used as well. (opt).
* @param {String} src The source of the the message (opt).
* @param {boolean} silent If true, the log event won't fire.
* @return {YUI} YUI instance.
*/
INSTANCE.message = function() {
return INSTANCE.log.apply(INSTANCE, arguments);
};
}, '@VERSION@', {"requires": ["yui-base"]});
YUI.add('yui-later', function (Y, NAME) {
/**
* Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module,
* <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>.
*
* @module yui
* @submodule yui-later
*/
var NO_ARGS = [];
/**
* Executes the supplied function in the context of the supplied
* object 'when' milliseconds later. Executes the function a
* single time unless periodic is set to true.
* @for YUI
* @method later
* @param when {int} the number of milliseconds to wait until the fn
* is executed.
* @param o the context object.
* @param fn {Function|String} the function to execute or the name of
* the method in the 'o' object to execute.
* @param data [Array] data that is provided to the function. This
* accepts either a single item or an array. If an array is provided,
* the function is executed with one parameter for each array item.
* If you need to pass a single array parameter, it needs to be wrapped
* in an array [myarray].
*
* Note: native methods in IE may not have the call and apply methods.
* In this case, it will work, but you are limited to four arguments.
*
* @param periodic {boolean} if true, executes continuously at supplied
* interval until canceled.
* @return {object} a timer object. Call the cancel() method on this
* object to stop the timer.
*/
Y.later = function(when, o, fn, data, periodic) {
when = when || 0;
data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS;
o = o || Y.config.win || Y;
var cancelled = false,
method = (o && Y.Lang.isString(fn)) ? o[fn] : fn,
wrapper = function() {
// IE 8- may execute a setInterval callback one last time
// after clearInterval was called, so in order to preserve
// the cancel() === no more runny-run, we have to jump through
// an extra hoop.
if (!cancelled) {
if (!method.apply) {
method(data[0], data[1], data[2], data[3]);
} else {
method.apply(o, data || NO_ARGS);
}
}
},
id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when);
return {
id: id,
interval: periodic,
cancel: function() {
cancelled = true;
if (this.interval) {
clearInterval(id);
} else {
clearTimeout(id);
}
}
};
};
Y.Lang.later = Y.later;
}, '@VERSION@', {"requires": ["yui-base"]});
YUI.add('yui', function (Y, NAME) {}, '@VERSION@', {"use": ["get", "features", "intl-base", "yui-log", "yui-later"]});
YUI.add('oop', function (Y, NAME) {
/**
Adds object inheritance and manipulation utilities to the YUI instance. This
module is required by most YUI components.
@module oop
**/
var L = Y.Lang,
A = Y.Array,
OP = Object.prototype,
CLONE_MARKER = '_~yuim~_',
hasOwn = OP.hasOwnProperty,
toString = OP.toString;
function dispatch(o, f, c, proto, action) {
if (o && o[action] && o !== Y) {
return o[action].call(o, f, c);
} else {
switch (A.test(o)) {
case 1:
return A[action](o, f, c);
case 2:
return A[action](Y.Array(o, 0, true), f, c);
default:
return Y.Object[action](o, f, c, proto);
}
}
}
/**
Augments the _receiver_ with prototype properties from the _supplier_. The
receiver may be a constructor function or an object. The supplier must be a
constructor function.
If the _receiver_ is an object, then the _supplier_ constructor will be called
immediately after _receiver_ is augmented, with _receiver_ as the `this` object.
If the _receiver_ is a constructor function, then all prototype methods of
_supplier_ that are copied to _receiver_ will be sequestered, and the
_supplier_ constructor will not be called immediately. The first time any
sequestered method is called on the _receiver_'s prototype, all sequestered
methods will be immediately copied to the _receiver_'s prototype, the
_supplier_'s constructor will be executed, and finally the newly unsequestered
method that was called will be executed.
This sequestering logic sounds like a bunch of complicated voodoo, but it makes
it cheap to perform frequent augmentation by ensuring that suppliers'
constructors are only called if a supplied method is actually used. If none of
the supplied methods is ever used, then there's no need to take the performance
hit of calling the _supplier_'s constructor.
@method augment
@param {Function|Object} receiver Object or function to be augmented.
@param {Function} supplier Function that supplies the prototype properties with
which to augment the _receiver_.
@param {Boolean} [overwrite=false] If `true`, properties already on the receiver
will be overwritten if found on the supplier's prototype.
@param {String[]} [whitelist] An array of property names. If specified,
only the whitelisted prototype properties will be applied to the receiver, and
all others will be ignored.
@param {Array|any} [args] Argument or array of arguments to pass to the
supplier's constructor when initializing.
@return {Function} Augmented object.
@for YUI
**/
Y.augment = function (receiver, supplier, overwrite, whitelist, args) {
var rProto = receiver.prototype,
sequester = rProto && supplier,
sProto = supplier.prototype,
to = rProto || receiver,
copy,
newPrototype,
replacements,
sequestered,
unsequester;
args = args ? Y.Array(args) : [];
if (sequester) {
newPrototype = {};
replacements = {};
sequestered = {};
copy = function (value, key) {
if (overwrite || !(key in rProto)) {
if (toString.call(value) === '[object Function]') {
sequestered[key] = value;
newPrototype[key] = replacements[key] = function () {
return unsequester(this, value, arguments);
};
} else {
newPrototype[key] = value;
}
}
};
unsequester = function (instance, fn, fnArgs) {
// Unsequester all sequestered functions.
for (var key in sequestered) {
if (hasOwn.call(sequestered, key)
&& instance[key] === replacements[key]) {
instance[key] = sequestered[key];
}
}
// Execute the supplier constructor.
supplier.apply(instance, args);
// Finally, execute the original sequestered function.
return fn.apply(instance, fnArgs);
};
if (whitelist) {
Y.Array.each(whitelist, function (name) {
if (name in sProto) {
copy(sProto[name], name);
}
});
} else {
Y.Object.each(sProto, copy, null, true);
}
}
Y.mix(to, newPrototype || sProto, overwrite, whitelist);
if (!sequester) {
supplier.apply(to, args);
}
return receiver;
};
/**
* Copies object properties from the supplier to the receiver. If the target has
* the property, and the property is an object, the target object will be
* augmented with the supplier's value.
*
* @method aggregate
* @param {Object} receiver Object to receive the augmentation.
* @param {Object} supplier Object that supplies the properties with which to
* augment the receiver.
* @param {Boolean} [overwrite=false] If `true`, properties already on the receiver
* will be overwritten if found on the supplier.
* @param {String[]} [whitelist] Whitelist. If supplied, only properties in this
* list will be applied to the receiver.
* @return {Object} Augmented object.
*/
Y.aggregate = function(r, s, ov, wl) {
return Y.mix(r, s, ov, wl, 0, true);
};
/**
* Utility to set up the prototype, constructor and superclass properties to
* support an inheritance strategy that can chain constructors and methods.
* Static members will not be inherited.
*
* @method extend
* @param {function} r the object to modify.
* @param {function} s the object to inherit.
* @param {object} px prototype properties to add/override.
* @param {object} sx static properties to add/override.
* @return {object} the extended object.
*/
Y.extend = function(r, s, px, sx) {
if (!s || !r) {
Y.error('extend failed, verify dependencies');
}
var sp = s.prototype, rp = Y.Object(sp);
r.prototype = rp;
rp.constructor = r;
r.superclass = sp;
// assign constructor property
if (s != Object && sp.constructor == OP.constructor) {
sp.constructor = s;
}
// add prototype overrides
if (px) {
Y.mix(rp, px, true);
}
// add object overrides
if (sx) {
Y.mix(r, sx, true);
}
return r;
};
/**
* Executes the supplied function for each item in
* a collection. Supports arrays, objects, and
* NodeLists
* @method each
* @param {object} o the object to iterate.
* @param {function} f the function to execute. This function
* receives the value, key, and object as parameters.
* @param {object} c the execution context for the function.
* @param {boolean} proto if true, prototype properties are
* iterated on objects.
* @return {YUI} the YUI instance.
*/
Y.each = function(o, f, c, proto) {
return dispatch(o, f, c, proto, 'each');
};
/**
* Executes the supplied function for each item in
* a collection. The operation stops if the function
* returns true. Supports arrays, objects, and
* NodeLists.
* @method some
* @param {object} o the object to iterate.
* @param {function} f the function to execute. This function
* receives the value, key, and object as parameters.
* @param {object} c the execution context for the function.
* @param {boolean} proto if true, prototype properties are
* iterated on objects.
* @return {boolean} true if the function ever returns true,
* false otherwise.
*/
Y.some = function(o, f, c, proto) {
return dispatch(o, f, c, proto, 'some');
};
/**
Deep object/array copy. Function clones are actually wrappers around the
original function. Array-like objects are treated as arrays. Primitives are
returned untouched. Optionally, a function can be provided to handle other data
types, filter keys, validate values, etc.
**Note:** Cloning a non-trivial object is a reasonably heavy operation, due to
the need to recursively iterate down non-primitive properties. Clone should be
used only when a deep clone down to leaf level properties is explicitly
required. This method will also
In many cases (for example, when trying to isolate objects used as hashes for
configuration properties), a shallow copy, using `Y.merge()` is normally
sufficient. If more than one level of isolation is required, `Y.merge()` can be
used selectively at each level which needs to be isolated from the original
without going all the way to leaf properties.
@method clone
@param {object} o what to clone.
@param {boolean} safe if true, objects will not have prototype items from the
source. If false, they will. In this case, the original is initially
protected, but the clone is not completely immune from changes to the source
object prototype. Also, cloned prototype items that are deleted from the
clone will result in the value of the source prototype being exposed. If
operating on a non-safe clone, items should be nulled out rather than
deleted.
@param {function} f optional function to apply to each item in a collection; it
will be executed prior to applying the value to the new object.
Return false to prevent the copy.
@param {object} c optional execution context for f.
@param {object} owner Owner object passed when clone is iterating an object.
Used to set up context for cloned functions.
@param {object} cloned hash of previously cloned objects to avoid multiple
clones.
@return {Array|Object} the cloned object.
**/
Y.clone = function(o, safe, f, c, owner, cloned) {
var o2, marked, stamp;
// Does not attempt to clone:
//
// * Non-typeof-object values, "primitive" values don't need cloning.
//
// * YUI instances, cloning complex object like YUI instances is not
// advised, this is like cloning the world.
//
// * DOM nodes (#2528250), common host objects like DOM nodes cannot be
// "subclassed" in Firefox and old versions of IE. Trying to use
// `Object.create()` or `Y.extend()` on a DOM node will throw an error in
// these browsers.
//
// Instad, the passed-in `o` will be return as-is when it matches one of the
// above criteria.
if (!L.isObject(o) ||
Y.instanceOf(o, YUI) ||
(o.addEventListener || o.attachEvent)) {
return o;
}
marked = cloned || {};
switch (L.type(o)) {
case 'date':
return new Date(o);
case 'regexp':
// if we do this we need to set the flags too
// return new RegExp(o.source);
return o;
case 'function':
// o2 = Y.bind(o, owner);
// break;
return o;
case 'array':
o2 = [];
break;
default:
// #2528250 only one clone of a given object should be created.
if (o[CLONE_MARKER]) {
return marked[o[CLONE_MARKER]];
}
stamp = Y.guid();
o2 = (safe) ? {} : Y.Object(o);
o[CLONE_MARKER] = stamp;
marked[stamp] = o;
}
Y.each(o, function(v, k) {
if ((k || k === 0) && (!f || (f.call(c || this, v, k, this, o) !== false))) {
if (k !== CLONE_MARKER) {
if (k == 'prototype') {
// skip the prototype
// } else if (o[k] === o) {
// this[k] = this;
} else {
this[k] =
Y.clone(v, safe, f, c, owner || o, marked);
}
}
}
}, o2);
if (!cloned) {
Y.Object.each(marked, function(v, k) {
if (v[CLONE_MARKER]) {
try {
delete v[CLONE_MARKER];
} catch (e) {
v[CLONE_MARKER] = null;
}
}
}, this);
marked = null;
}
return o2;
};
/**
* Returns a function that will execute the supplied function in the
* supplied object's context, optionally adding any additional
* supplied parameters to the beginning of the arguments collection the
* supplied to the function.
*
* @method bind
* @param {Function|String} f the function to bind, or a function name
* to execute on the context object.
* @param {object} c the execution context.
* @param {any} args* 0..n arguments to include before the arguments the
* function is executed with.
* @return {function} the wrapped function.
*/
Y.bind = function(f, c) {
var xargs = arguments.length > 2 ?
Y.Array(arguments, 2, true) : null;
return function() {
var fn = L.isString(f) ? c[f] : f,
args = (xargs) ?
xargs.concat(Y.Array(arguments, 0, true)) : arguments;
return fn.apply(c || fn, args);
};
};
/**
* Returns a function that will execute the supplied function in the
* supplied object's context, optionally adding any additional
* supplied parameters to the end of the arguments the function
* is executed with.
*
* @method rbind
* @param {Function|String} f the function to bind, or a function name
* to execute on the context object.
* @param {object} c the execution context.
* @param {any} args* 0..n arguments to append to the end of
* arguments collection supplied to the function.
* @return {function} the wrapped function.
*/
Y.rbind = function(f, c) {
var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null;
return function() {
var fn = L.isString(f) ? c[f] : f,
args = (xargs) ?
Y.Array(arguments, 0, true).concat(xargs) : arguments;
return fn.apply(c || fn, args);
};
};
}, '@VERSION@', {"requires": ["yui-base"]});
YUI.add('features', function (Y, NAME) {
var feature_tests = {};
/**
Contains the core of YUI's feature test architecture.
@module features
*/
/**
* Feature detection
* @class Features
* @static
*/
Y.mix(Y.namespace('Features'), {
/**
* Object hash of all registered feature tests
* @property tests
* @type Object
*/
tests: feature_tests,
/**
* Add a test to the system
*
* ```
* Y.Features.add("load", "1", {});
* ```
*
* @method add
* @param {String} cat The category, right now only 'load' is supported
* @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3
* @param {Object} o Object containing test properties
* @param {String} o.name The name of the test
* @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance
* @param {String} o.trigger The module that triggers this test.
*/
add: function(cat, name, o) {
feature_tests[cat] = feature_tests[cat] || {};
feature_tests[cat][name] = o;
},
/**
* Execute all tests of a given category and return the serialized results
*
* ```
* caps=1:1;2:1;3:0
* ```
* @method all
* @param {String} cat The category to execute
* @param {Array} args The arguments to pass to the test function
* @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0
*/
all: function(cat, args) {
var cat_o = feature_tests[cat],
// results = {};
result = [];
if (cat_o) {
Y.Object.each(cat_o, function(v, k) {
result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0));
});
}
return (result.length) ? result.join(';') : '';
},
/**
* Run a sepecific test and return a Boolean response.
*
* ```
* Y.Features.test("load", "1");
* ```
*
* @method test
* @param {String} cat The category of the test to run
* @param {String} name The name of the test to run
* @param {Array} args The arguments to pass to the test function
* @return {Boolean} True or false if the test passed/failed.
*/
test: function(cat, name, args) {
args = args || [];
var result, ua, test,
cat_o = feature_tests[cat],
feature = cat_o && cat_o[name];
if (!feature) {
Y.log('Feature test ' + cat + ', ' + name + ' not found');
} else {
result = feature.result;
if (Y.Lang.isUndefined(result)) {
ua = feature.ua;
if (ua) {
result = (Y.UA[ua]);
}
test = feature.test;
if (test && ((!ua) || result)) {
result = test.apply(Y, args);
}
feature.result = result;
}
}
return result;
}
});
// Y.Features.add("load", "1", {});
// Y.Features.test("load", "1");
// caps=1:1;2:0;3:1;
/* This file is auto-generated by (yogi loader --yes --mix --start ../) */
/*jshint maxlen:900, eqeqeq: false */
var add = Y.Features.add;
// app-transitions-native
add('load', '0', {
"name": "app-transitions-native",
"test": function (Y) {
var doc = Y.config.doc,
node = doc ? doc.documentElement : null;
if (node && node.style) {
return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style);
}
return false;
},
"trigger": "app-transitions"
});
// autocomplete-list-keys
add('load', '1', {
"name": "autocomplete-list-keys",
"test": function (Y) {
// Only add keyboard support to autocomplete-list if this doesn't appear to
// be an iOS or Android-based mobile device.
//
// There's currently no feasible way to actually detect whether a device has
// a hardware keyboard, so this sniff will have to do. It can easily be
// overridden by manually loading the autocomplete-list-keys module.
//
// Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari
// doesn't fire the keyboard events used by AutoCompleteList, so there's
// no point loading the -keys module even when a bluetooth keyboard may be
// available.
return !(Y.UA.ios || Y.UA.android);
},
"trigger": "autocomplete-list"
});
// dd-gestures
add('load', '2', {
"name": "dd-gestures",
"trigger": "dd-drag",
"ua": "touchEnabled"
});
// dom-style-ie
add('load', '3', {
"name": "dom-style-ie",
"test": function (Y) {
var testFeature = Y.Features.test,
addFeature = Y.Features.add,
WINDOW = Y.config.win,
DOCUMENT = Y.config.doc,
DOCUMENT_ELEMENT = 'documentElement',
ret = false;
addFeature('style', 'computedStyle', {
test: function() {
return WINDOW && 'getComputedStyle' in WINDOW;
}
});
addFeature('style', 'opacity', {
test: function() {
return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style;
}
});
ret = (!testFeature('style', 'opacity') &&
!testFeature('style', 'computedStyle'));
return ret;
},
"trigger": "dom-style"
});
// editor-para-ie
add('load', '4', {
"name": "editor-para-ie",
"trigger": "editor-para",
"ua": "ie",
"when": "instead"
});
// event-base-ie
add('load', '5', {
"name": "event-base-ie",
"test": function(Y) {
var imp = Y.config.doc && Y.config.doc.implementation;
return (imp && (!imp.hasFeature('Events', '2.0')));
},
"trigger": "node-base"
});
// graphics-canvas
add('load', '6', {
"name": "graphics-canvas",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas",
canvas = DOCUMENT && DOCUMENT.createElement("canvas"),
svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d"));
},
"trigger": "graphics"
});
// graphics-canvas-default
add('load', '7', {
"name": "graphics-canvas-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas",
canvas = DOCUMENT && DOCUMENT.createElement("canvas"),
svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d"));
},
"trigger": "graphics"
});
// graphics-svg
add('load', '8', {
"name": "graphics-svg",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas",
canvas = DOCUMENT && DOCUMENT.createElement("canvas"),
svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
return svg && (useSVG || !canvas);
},
"trigger": "graphics"
});
// graphics-svg-default
add('load', '9', {
"name": "graphics-svg-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas",
canvas = DOCUMENT && DOCUMENT.createElement("canvas"),
svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
return svg && (useSVG || !canvas);
},
"trigger": "graphics"
});
// graphics-vml
add('load', '10', {
"name": "graphics-vml",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d")));
},
"trigger": "graphics"
});
// graphics-vml-default
add('load', '11', {
"name": "graphics-vml-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d")));
},
"trigger": "graphics"
});
// history-hash-ie
add('load', '12', {
"name": "history-hash-ie",
"test": function (Y) {
var docMode = Y.config.doc && Y.config.doc.documentMode;
return Y.UA.ie && (!('onhashchange' in Y.config.win) ||
!docMode || docMode < 8);
},
"trigger": "history-hash"
});
// io-nodejs
add('load', '13', {
"name": "io-nodejs",
"trigger": "io-base",
"ua": "nodejs"
});
// json-parse-shim
add('load', '14', {
"name": "json-parse-shim",
"test": function (Y) {
var _JSON = Y.config.global.JSON,
Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON,
nativeSupport = Y.config.useNativeJSONParse !== false && !!Native;
function workingNative( k, v ) {
return k === "ok" ? true : v;
}
// Double check basic functionality. This is mainly to catch early broken
// implementations of the JSON API in Firefox 3.1 beta1 and beta2
if ( nativeSupport ) {
try {
nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok;
}
catch ( e ) {
nativeSupport = false;
}
}
return !nativeSupport;
},
"trigger": "json-parse"
});
// json-stringify-shim
add('load', '15', {
"name": "json-stringify-shim",
"test": function (Y) {
var _JSON = Y.config.global.JSON,
Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON,
nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native;
// Double check basic native functionality. This is primarily to catch broken
// early JSON API implementations in Firefox 3.1 beta1 and beta2.
if ( nativeSupport ) {
try {
nativeSupport = ( '0' === Native.stringify(0) );
} catch ( e ) {
nativeSupport = false;
}
}
return !nativeSupport;
},
"trigger": "json-stringify"
});
// scrollview-base-ie
add('load', '16', {
"name": "scrollview-base-ie",
"trigger": "scrollview-base",
"ua": "ie"
});
// selector-css2
add('load', '17', {
"name": "selector-css2",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
ret = DOCUMENT && !('querySelectorAll' in DOCUMENT);
return ret;
},
"trigger": "selector"
});
// transition-timer
add('load', '18', {
"name": "transition-timer",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
node = (DOCUMENT) ? DOCUMENT.documentElement: null,
ret = true;
if (node && node.style) {
ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style);
}
return ret;
},
"trigger": "transition"
});
// widget-base-ie
add('load', '19', {
"name": "widget-base-ie",
"trigger": "widget-base",
"ua": "ie"
});
// yql-jsonp
add('load', '20', {
"name": "yql-jsonp",
"test": function (Y) {
/* Only load the JSONP module when not in nodejs or winjs
TODO Make the winjs module a CORS module
*/
return (!Y.UA.nodejs && !Y.UA.winjs);
},
"trigger": "yql",
"when": "after"
});
// yql-nodejs
add('load', '21', {
"name": "yql-nodejs",
"trigger": "yql",
"ua": "nodejs",
"when": "after"
});
// yql-winjs
add('load', '22', {
"name": "yql-winjs",
"trigger": "yql",
"ua": "winjs",
"when": "after"
});
}, '@VERSION@', {"requires": ["yui-base"]});
YUI.add('dom-core', function (Y, NAME) {
var NODE_TYPE = 'nodeType',
OWNER_DOCUMENT = 'ownerDocument',
DOCUMENT_ELEMENT = 'documentElement',
DEFAULT_VIEW = 'defaultView',
PARENT_WINDOW = 'parentWindow',
TAG_NAME = 'tagName',
PARENT_NODE = 'parentNode',
PREVIOUS_SIBLING = 'previousSibling',
NEXT_SIBLING = 'nextSibling',
CONTAINS = 'contains',
COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition',
EMPTY_ARRAY = [],
// IE < 8 throws on node.contains(textNode)
supportsContainsTextNode = (function() {
var node = Y.config.doc.createElement('div'),
textNode = node.appendChild(Y.config.doc.createTextNode('')),
result = false;
try {
result = node.contains(textNode);
} catch(e) {}
return result;
})(),
/**
* The DOM utility provides a cross-browser abtraction layer
* normalizing DOM tasks, and adds extra helper functionality
* for other common tasks.
* @module dom
* @main dom
* @submodule dom-base
* @for DOM
*
*/
/**
* Provides DOM helper methods.
* @class DOM
*
*/
Y_DOM = {
/**
* Returns the HTMLElement with the given ID (Wrapper for document.getElementById).
* @method byId
* @param {String} id the id attribute
* @param {Object} doc optional The document to search. Defaults to current document
* @return {HTMLElement | null} The HTMLElement with the id, or null if none found.
*/
byId: function(id, doc) {
// handle dupe IDs and IE name collision
return Y_DOM.allById(id, doc)[0] || null;
},
getId: function(node) {
var id;
// HTMLElement returned from FORM when INPUT name === "id"
// IE < 8: HTMLCollection returned when INPUT id === "id"
// via both getAttribute and form.id
if (node.id && !node.id.tagName && !node.id.item) {
id = node.id;
} else if (node.attributes && node.attributes.id) {
id = node.attributes.id.value;
}
return id;
},
setId: function(node, id) {
if (node.setAttribute) {
node.setAttribute('id', id);
} else {
node.id = id;
}
},
/*
* Finds the ancestor of the element.
* @method ancestor
* @param {HTMLElement} element The html element.
* @param {Function} fn optional An optional boolean test to apply.
* The optional function is passed the current DOM node being tested as its only argument.
* If no function is given, the parentNode is returned.
* @param {Boolean} testSelf optional Whether or not to include the element in the scan
* @return {HTMLElement | null} The matching DOM node or null if none found.
*/
ancestor: function(element, fn, testSelf, stopFn) {
var ret = null;
if (testSelf) {
ret = (!fn || fn(element)) ? element : null;
}
return ret || Y_DOM.elementByAxis(element, PARENT_NODE, fn, null, stopFn);
},
/*
* Finds the ancestors of the element.
* @method ancestors
* @param {HTMLElement} element The html element.
* @param {Function} fn optional An optional boolean test to apply.
* The optional function is passed the current DOM node being tested as its only argument.
* If no function is given, all ancestors are returned.
* @param {Boolean} testSelf optional Whether or not to include the element in the scan
* @return {Array} An array containing all matching DOM nodes.
*/
ancestors: function(element, fn, testSelf, stopFn) {
var ancestor = element,
ret = [];
while ((ancestor = Y_DOM.ancestor(ancestor, fn, testSelf, stopFn))) {
testSelf = false;
if (ancestor) {
ret.unshift(ancestor);
if (stopFn && stopFn(ancestor)) {
return ret;
}
}
}
return ret;
},
/**
* Searches the element by the given axis for the first matching element.
* @method elementByAxis
* @param {HTMLElement} element The html element.
* @param {String} axis The axis to search (parentNode, nextSibling, previousSibling).
* @param {Function} fn optional An optional boolean test to apply.
* @param {Boolean} all optional Whether all node types should be returned, or just element nodes.
* The optional function is passed the current HTMLElement being tested as its only argument.
* If no function is given, the first element is returned.
* @return {HTMLElement | null} The matching element or null if none found.
*/
elementByAxis: function(element, axis, fn, all, stopAt) {
while (element && (element = element[axis])) { // NOTE: assignment
if ( (all || element[TAG_NAME]) && (!fn || fn(element)) ) {
return element;
}
if (stopAt && stopAt(element)) {
return null;
}
}
return null;
},
/**
* Determines whether or not one HTMLElement is or contains another HTMLElement.
* @method contains
* @param {HTMLElement} element The containing html element.
* @param {HTMLElement} needle The html element that may be contained.
* @return {Boolean} Whether or not the element is or contains the needle.
*/
contains: function(element, needle) {
var ret = false;
if ( !needle || !element || !needle[NODE_TYPE] || !element[NODE_TYPE]) {
ret = false;
} else if (element[CONTAINS] &&
// IE < 8 throws on node.contains(textNode) so fall back to brute.
// Falling back for other nodeTypes as well.
(needle[NODE_TYPE] === 1 || supportsContainsTextNode)) {
ret = element[CONTAINS](needle);
} else if (element[COMPARE_DOCUMENT_POSITION]) {
// Match contains behavior (node.contains(node) === true).
// Needed for Firefox < 4.
if (element === needle || !!(element[COMPARE_DOCUMENT_POSITION](needle) & 16)) {
ret = true;
}
} else {
ret = Y_DOM._bruteContains(element, needle);
}
return ret;
},
/**
* Determines whether or not the HTMLElement is part of the document.
* @method inDoc
* @param {HTMLElement} element The containing html element.
* @param {HTMLElement} doc optional The document to check.
* @return {Boolean} Whether or not the element is attached to the document.
*/
inDoc: function(element, doc) {
var ret = false,
rootNode;
if (element && element.nodeType) {
(doc) || (doc = element[OWNER_DOCUMENT]);
rootNode = doc[DOCUMENT_ELEMENT];
// contains only works with HTML_ELEMENT
if (rootNode && rootNode.contains && element.tagName) {
ret = rootNode.contains(element);
} else {
ret = Y_DOM.contains(rootNode, element);
}
}
return ret;
},
allById: function(id, root) {
root = root || Y.config.doc;
var nodes = [],
ret = [],
i,
node;
if (root.querySelectorAll) {
ret = root.querySelectorAll('[id="' + id + '"]');
} else if (root.all) {
nodes = root.all(id);
if (nodes) {
// root.all may return HTMLElement or HTMLCollection.
// some elements are also HTMLCollection (FORM, SELECT).
if (nodes.nodeName) {
if (nodes.id === id) { // avoid false positive on name
ret.push(nodes);
nodes = EMPTY_ARRAY; // done, no need to filter
} else { // prep for filtering
nodes = [nodes];
}
}
if (nodes.length) {
// filter out matches on node.name
// and element.id as reference to element with id === 'id'
for (i = 0; node = nodes[i++];) {
if (node.id === id ||
(node.attributes && node.attributes.id &&
node.attributes.id.value === id)) {
ret.push(node);
}
}
}
}
} else {
ret = [Y_DOM._getDoc(root).getElementById(id)];
}
return ret;
},
isWindow: function(obj) {
return !!(obj && obj.scrollTo && obj.document);
},
_removeChildNodes: function(node) {
while (node.firstChild) {
node.removeChild(node.firstChild);
}
},
siblings: function(node, fn) {
var nodes = [],
sibling = node;
while ((sibling = sibling[PREVIOUS_SIBLING])) {
if (sibling[TAG_NAME] && (!fn || fn(sibling))) {
nodes.unshift(sibling);
}
}
sibling = node;
while ((sibling = sibling[NEXT_SIBLING])) {
if (sibling[TAG_NAME] && (!fn || fn(sibling))) {
nodes.push(sibling);
}
}
return nodes;
},
/**
* Brute force version of contains.
* Used for browsers without contains support for non-HTMLElement Nodes (textNodes, etc).
* @method _bruteContains
* @private
* @param {HTMLElement} element The containing html element.
* @param {HTMLElement} needle The html element that may be contained.
* @return {Boolean} Whether or not the element is or contains the needle.
*/
_bruteContains: function(element, needle) {
while (needle) {
if (element === needle) {
return true;
}
needle = needle.parentNode;
}
return false;
},
// TODO: move to Lang?
/**
* Memoizes dynamic regular expressions to boost runtime performance.
* @method _getRegExp
* @private
* @param {String} str The string to convert to a regular expression.
* @param {String} flags optional An optinal string of flags.
* @return {RegExp} An instance of RegExp
*/
_getRegExp: function(str, flags) {
flags = flags || '';
Y_DOM._regexCache = Y_DOM._regexCache || {};
if (!Y_DOM._regexCache[str + flags]) {
Y_DOM._regexCache[str + flags] = new RegExp(str, flags);
}
return Y_DOM._regexCache[str + flags];
},
// TODO: make getDoc/Win true privates?
/**
* returns the appropriate document.
* @method _getDoc
* @private
* @param {HTMLElement} element optional Target element.
* @return {Object} The document for the given element or the default document.
*/
_getDoc: function(element) {
var doc = Y.config.doc;
if (element) {
doc = (element[NODE_TYPE] === 9) ? element : // element === document
element[OWNER_DOCUMENT] || // element === DOM node
element.document || // element === window
Y.config.doc; // default
}
return doc;
},
/**
* returns the appropriate window.
* @method _getWin
* @private
* @param {HTMLElement} element optional Target element.
* @return {Object} The window for the given element or the default window.
*/
_getWin: function(element) {
var doc = Y_DOM._getDoc(element);
return doc[DEFAULT_VIEW] || doc[PARENT_WINDOW] || Y.config.win;
},
_batch: function(nodes, fn, arg1, arg2, arg3, etc) {
fn = (typeof fn === 'string') ? Y_DOM[fn] : fn;
var result,
i = 0,
node,
ret;
if (fn && nodes) {
while ((node = nodes[i++])) {
result = result = fn.call(Y_DOM, node, arg1, arg2, arg3, etc);
if (typeof result !== 'undefined') {
(ret) || (ret = []);
ret.push(result);
}
}
}
return (typeof ret !== 'undefined') ? ret : nodes;
},
generateID: function(el) {
var id = el.id;
if (!id) {
id = Y.stamp(el);
el.id = id;
}
return id;
}
};
Y.DOM = Y_DOM;
}, '@VERSION@', {"requires": ["oop", "features"]});
YUI.add('dom-base', function (Y, NAME) {
/**
* @for DOM
* @module dom
*/
var documentElement = Y.config.doc.documentElement,
Y_DOM = Y.DOM,
TAG_NAME = 'tagName',
OWNER_DOCUMENT = 'ownerDocument',
EMPTY_STRING = '',
addFeature = Y.Features.add,
testFeature = Y.Features.test;
Y.mix(Y_DOM, {
/**
* Returns the text content of the HTMLElement.
* @method getText
* @param {HTMLElement} element The html element.
* @return {String} The text content of the element (includes text of any descending elements).
*/
getText: (documentElement.textContent !== undefined) ?
function(element) {
var ret = '';
if (element) {
ret = element.textContent;
}
return ret || '';
} : function(element) {
var ret = '';
if (element) {
ret = element.innerText || element.nodeValue; // might be a textNode
}
return ret || '';
},
/**
* Sets the text content of the HTMLElement.
* @method setText
* @param {HTMLElement} element The html element.
* @param {String} content The content to add.
*/
setText: (documentElement.textContent !== undefined) ?
function(element, content) {
if (element) {
element.textContent = content;
}
} : function(element, content) {
if ('innerText' in element) {
element.innerText = content;
} else if ('nodeValue' in element) {
element.nodeValue = content;
}
},
CUSTOM_ATTRIBUTES: (!documentElement.hasAttribute) ? { // IE < 8
'for': 'htmlFor',
'class': 'className'
} : { // w3c
'htmlFor': 'for',
'className': 'class'
},
/**
* Provides a normalized attribute interface.
* @method setAttribute
* @param {HTMLElement} el The target element for the attribute.
* @param {String} attr The attribute to set.
* @param {String} val The value of the attribute.
*/
setAttribute: function(el, attr, val, ieAttr) {
if (el && attr && el.setAttribute) {
attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr;
el.setAttribute(attr, val, ieAttr);
}
else { Y.log('bad input to setAttribute', 'warn', 'dom'); }
},
/**
* Provides a normalized attribute interface.
* @method getAttribute
* @param {HTMLElement} el The target element for the attribute.
* @param {String} attr The attribute to get.
* @return {String} The current value of the attribute.
*/
getAttribute: function(el, attr, ieAttr) {
ieAttr = (ieAttr !== undefined) ? ieAttr : 2;
var ret = '';
if (el && attr && el.getAttribute) {
attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr;
ret = el.getAttribute(attr, ieAttr);
if (ret === null) {
ret = ''; // per DOM spec
}
}
else { Y.log('bad input to getAttribute', 'warn', 'dom'); }
return ret;
},
VALUE_SETTERS: {},
VALUE_GETTERS: {},
getValue: function(node) {
var ret = '', // TODO: return null?
getter;
if (node && node[TAG_NAME]) {
getter = Y_DOM.VALUE_GETTERS[node[TAG_NAME].toLowerCase()];
if (getter) {
ret = getter(node);
} else {
ret = node.value;
}
}
// workaround for IE8 JSON stringify bug
// which converts empty string values to null
if (ret === EMPTY_STRING) {
ret = EMPTY_STRING; // for real
}
return (typeof ret === 'string') ? ret : '';
},
setValue: function(node, val) {
var setter;
if (node && node[TAG_NAME]) {
setter = Y_DOM.VALUE_SETTERS[node[TAG_NAME].toLowerCase()];
if (setter) {
setter(node, val);
} else {
node.value = val;
}
}
},
creators: {}
});
addFeature('value-set', 'select', {
test: function() {
var node = Y.config.doc.createElement('select');
node.innerHTML = '<option>1</option><option>2</option>';
node.value = '2';
return (node.value && node.value === '2');
}
});
if (!testFeature('value-set', 'select')) {
Y_DOM.VALUE_SETTERS.select = function(node, val) {
for (var i = 0, options = node.getElementsByTagName('option'), option;
option = options[i++];) {
if (Y_DOM.getValue(option) === val) {
option.selected = true;
//Y_DOM.setAttribute(option, 'selected', 'selected');
break;
}
}
};
}
Y.mix(Y_DOM.VALUE_GETTERS, {
button: function(node) {
return (node.attributes && node.attributes.value) ? node.attributes.value.value : '';
}
});
Y.mix(Y_DOM.VALUE_SETTERS, {
// IE: node.value changes the button text, which should be handled via innerHTML
button: function(node, val) {
var attr = node.attributes.value;
if (!attr) {
attr = node[OWNER_DOCUMENT].createAttribute('value');
node.setAttributeNode(attr);
}
attr.value = val;
}
});
Y.mix(Y_DOM.VALUE_GETTERS, {
option: function(node) {
var attrs = node.attributes;
return (attrs.value && attrs.value.specified) ? node.value : node.text;
},
select: function(node) {
var val = node.value,
options = node.options;
if (options && options.length) {
// TODO: implement multipe select
if (node.multiple) {
Y.log('multiple select normalization not implemented', 'warn', 'DOM');
} else if (node.selectedIndex > -1) {
val = Y_DOM.getValue(options[node.selectedIndex]);
}
}
return val;
}
});
var addClass, hasClass, removeClass;
Y.mix(Y.DOM, {
/**
* Determines whether a DOM element has the given className.
* @method hasClass
* @for DOM
* @param {HTMLElement} element The DOM element.
* @param {String} className the class name to search for
* @return {Boolean} Whether or not the element has the given class.
*/
hasClass: function(node, className) {
var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
return re.test(node.className);
},
/**
* Adds a class name to a given DOM element.
* @method addClass
* @for DOM
* @param {HTMLElement} element The DOM element.
* @param {String} className the class name to add to the class attribute
*/
addClass: function(node, className) {
if (!Y.DOM.hasClass(node, className)) { // skip if already present
node.className = Y.Lang.trim([node.className, className].join(' '));
}
},
/**
* Removes a class name from a given element.
* @method removeClass
* @for DOM
* @param {HTMLElement} element The DOM element.
* @param {String} className the class name to remove from the class attribute
*/
removeClass: function(node, className) {
if (className && hasClass(node, className)) {
node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' +
className + '(?:\\s+|$)'), ' '));
if ( hasClass(node, className) ) { // in case of multiple adjacent
removeClass(node, className);
}
}
},
/**
* Replace a class with another class for a given element.
* If no oldClassName is present, the newClassName is simply added.
* @method replaceClass
* @for DOM
* @param {HTMLElement} element The DOM element
* @param {String} oldClassName the class name to be replaced
* @param {String} newClassName the class name that will be replacing the old class name
*/
replaceClass: function(node, oldC, newC) {
//Y.log('replaceClass replacing ' + oldC + ' with ' + newC, 'info', 'Node');
removeClass(node, oldC); // remove first in case oldC === newC
addClass(node, newC);
},
/**
* If the className exists on the node it is removed, if it doesn't exist it is added.
* @method toggleClass
* @for DOM
* @param {HTMLElement} element The DOM element
* @param {String} className the class name to be toggled
* @param {Boolean} addClass optional boolean to indicate whether class
* should be added or removed regardless of current state
*/
toggleClass: function(node, className, force) {
var add = (force !== undefined) ? force :
!(hasClass(node, className));
if (add) {
addClass(node, className);
} else {
removeClass(node, className);
}
}
});
hasClass = Y.DOM.hasClass;
removeClass = Y.DOM.removeClass;
addClass = Y.DOM.addClass;
var re_tag = /<([a-z]+)/i,
Y_DOM = Y.DOM,
addFeature = Y.Features.add,
testFeature = Y.Features.test,
creators = {},
createFromDIV = function(html, tag) {
var div = Y.config.doc.createElement('div'),
ret = true;
div.innerHTML = html;
if (!div.firstChild || div.firstChild.tagName !== tag.toUpperCase()) {
ret = false;
}
return ret;
},
re_tbody = /(?:\/(?:thead|tfoot|tbody|caption|col|colgroup)>)+\s*<tbody/,
TABLE_OPEN = '<table>',
TABLE_CLOSE = '</table>';
Y.mix(Y.DOM, {
_fragClones: {},
_create: function(html, doc, tag) {
tag = tag || 'div';
var frag = Y_DOM._fragClones[tag];
if (frag) {
frag = frag.cloneNode(false);
} else {
frag = Y_DOM._fragClones[tag] = doc.createElement(tag);
}
frag.innerHTML = html;
return frag;
},
_children: function(node, tag) {
var i = 0,
children = node.children,
childNodes,
hasComments,
child;
if (children && children.tags) { // use tags filter when possible
if (tag) {
children = node.children.tags(tag);
} else { // IE leaks comments into children
hasComments = children.tags('!').length;
}
}
if (!children || (!children.tags && tag) || hasComments) {
childNodes = children || node.childNodes;
children = [];
while ((child = childNodes[i++])) {
if (child.nodeType === 1) {
if (!tag || tag === child.tagName) {
children.push(child);
}
}
}
}
return children || [];
},
/**
* Creates a new dom node using the provided markup string.
* @method create
* @param {String} html The markup used to create the element
* @param {HTMLDocument} doc An optional document context
* @return {HTMLElement|DocumentFragment} returns a single HTMLElement
* when creating one node, and a documentFragment when creating
* multiple nodes.
*/
create: function(html, doc) {
if (typeof html === 'string') {
html = Y.Lang.trim(html); // match IE which trims whitespace from innerHTML
}
doc = doc || Y.config.doc;
var m = re_tag.exec(html),
create = Y_DOM._create,
custom = creators,
ret = null,
creator,
tag, nodes;
if (html != undefined) { // not undefined or null
if (m && m[1]) {
creator = custom[m[1].toLowerCase()];
if (typeof creator === 'function') {
create = creator;
} else {
tag = creator;
}
}
nodes = create(html, doc, tag).childNodes;
if (nodes.length === 1) { // return single node, breaking parentNode ref from "fragment"
ret = nodes[0].parentNode.removeChild(nodes[0]);
} else if (nodes[0] && nodes[0].className === 'yui3-big-dummy') { // using dummy node to preserve some attributes (e.g. OPTION not selected)
if (nodes.length === 2) {
ret = nodes[0].nextSibling;
} else {
nodes[0].parentNode.removeChild(nodes[0]);
ret = Y_DOM._nl2frag(nodes, doc);
}
} else { // return multiple nodes as a fragment
ret = Y_DOM._nl2frag(nodes, doc);
}
}
return ret;
},
_nl2frag: function(nodes, doc) {
var ret = null,
i, len;
if (nodes && (nodes.push || nodes.item) && nodes[0]) {
doc = doc || nodes[0].ownerDocument;
ret = doc.createDocumentFragment();
if (nodes.item) { // convert live list to static array
nodes = Y.Array(nodes, 0, true);
}
for (i = 0, len = nodes.length; i < len; i++) {
ret.appendChild(nodes[i]);
}
} // else inline with log for minification
return ret;
},
/**
* Inserts content in a node at the given location
* @method addHTML
* @param {HTMLElement} node The node to insert into
* @param {HTMLElement | Array | HTMLCollection} content The content to be inserted
* @param {HTMLElement} where Where to insert the content
* If no "where" is given, content is appended to the node
* Possible values for "where"
* <dl>
* <dt>HTMLElement</dt>
* <dd>The element to insert before</dd>
* <dt>"replace"</dt>
* <dd>Replaces the existing HTML</dd>
* <dt>"before"</dt>
* <dd>Inserts before the existing HTML</dd>
* <dt>"before"</dt>
* <dd>Inserts content before the node</dd>
* <dt>"after"</dt>
* <dd>Inserts content after the node</dd>
* </dl>
*/
addHTML: function(node, content, where) {
var nodeParent = node.parentNode,
i = 0,
item,
ret = content,
newNode;
if (content != undefined) { // not null or undefined (maybe 0)
if (content.nodeType) { // DOM node, just add it
newNode = content;
} else if (typeof content == 'string' || typeof content == 'number') {
ret = newNode = Y_DOM.create(content);
} else if (content[0] && content[0].nodeType) { // array or collection
newNode = Y.config.doc.createDocumentFragment();
while ((item = content[i++])) {
newNode.appendChild(item); // append to fragment for insertion
}
}
}
if (where) {
if (newNode && where.parentNode) { // insert regardless of relationship to node
where.parentNode.insertBefore(newNode, where);
} else {
switch (where) {
case 'replace':
while (node.firstChild) {
node.removeChild(node.firstChild);
}
if (newNode) { // allow empty content to clear node
node.appendChild(newNode);
}
break;
case 'before':
if (newNode) {
nodeParent.insertBefore(newNode, node);
}
break;
case 'after':
if (newNode) {
if (node.nextSibling) { // IE errors if refNode is null
nodeParent.insertBefore(newNode, node.nextSibling);
} else {
nodeParent.appendChild(newNode);
}
}
break;
default:
if (newNode) {
node.appendChild(newNode);
}
}
}
} else if (newNode) {
node.appendChild(newNode);
}
return ret;
},
wrap: function(node, html) {
var parent = (html && html.nodeType) ? html : Y.DOM.create(html),
nodes = parent.getElementsByTagName('*');
if (nodes.length) {
parent = nodes[nodes.length - 1];
}
if (node.parentNode) {
node.parentNode.replaceChild(parent, node);
}
parent.appendChild(node);
},
unwrap: function(node) {
var parent = node.parentNode,
lastChild = parent.lastChild,
next = node,
grandparent;
if (parent) {
grandparent = parent.parentNode;
if (grandparent) {
node = parent.firstChild;
while (node !== lastChild) {
next = node.nextSibling;
grandparent.insertBefore(node, parent);
node = next;
}
grandparent.replaceChild(lastChild, parent);
} else {
parent.removeChild(node);
}
}
}
});
addFeature('innerhtml', 'table', {
test: function() {
var node = Y.config.doc.createElement('table');
try {
node.innerHTML = '<tbody></tbody>';
} catch(e) {
return false;
}
return (node.firstChild && node.firstChild.nodeName === 'TBODY');
}
});
addFeature('innerhtml-div', 'tr', {
test: function() {
return createFromDIV('<tr></tr>', 'tr');
}
});
addFeature('innerhtml-div', 'script', {
test: function() {
return createFromDIV('<script></script>', 'script');
}
});
if (!testFeature('innerhtml', 'table')) {
// TODO: thead/tfoot with nested tbody
// IE adds TBODY when creating TABLE elements (which may share this impl)
creators.tbody = function(html, doc) {
var frag = Y_DOM.create(TABLE_OPEN + html + TABLE_CLOSE, doc),
tb = Y.DOM._children(frag, 'tbody')[0];
if (frag.children.length > 1 && tb && !re_tbody.test(html)) {
tb.parentNode.removeChild(tb); // strip extraneous tbody
}
return frag;
};
}
if (!testFeature('innerhtml-div', 'script')) {
creators.script = function(html, doc) {
var frag = doc.createElement('div');
frag.innerHTML = '-' + html;
frag.removeChild(frag.firstChild);
return frag;
};
creators.link = creators.style = creators.script;
}
if (!testFeature('innerhtml-div', 'tr')) {
Y.mix(creators, {
option: function(html, doc) {
return Y_DOM.create('<select><option class="yui3-big-dummy" selected></option>' + html + '</select>', doc);
},
tr: function(html, doc) {
return Y_DOM.create('<tbody>' + html + '</tbody>', doc);
},
td: function(html, doc) {
return Y_DOM.create('<tr>' + html + '</tr>', doc);
},
col: function(html, doc) {
return Y_DOM.create('<colgroup>' + html + '</colgroup>', doc);
},
tbody: 'table'
});
Y.mix(creators, {
legend: 'fieldset',
th: creators.td,
thead: creators.tbody,
tfoot: creators.tbody,
caption: creators.tbody,
colgroup: creators.tbody,
optgroup: creators.option
});
}
Y_DOM.creators = creators;
Y.mix(Y.DOM, {
/**
* Sets the width of the element to the given size, regardless
* of box model, border, padding, etc.
* @method setWidth
* @param {HTMLElement} element The DOM element.
* @param {String|Number} size The pixel height to size to
*/
setWidth: function(node, size) {
Y.DOM._setSize(node, 'width', size);
},
/**
* Sets the height of the element to the given size, regardless
* of box model, border, padding, etc.
* @method setHeight
* @param {HTMLElement} element The DOM element.
* @param {String|Number} size The pixel height to size to
*/
setHeight: function(node, size) {
Y.DOM._setSize(node, 'height', size);
},
_setSize: function(node, prop, val) {
val = (val > 0) ? val : 0;
var size = 0;
node.style[prop] = val + 'px';
size = (prop === 'height') ? node.offsetHeight : node.offsetWidth;
if (size > val) {
val = val - (size - val);
if (val < 0) {
val = 0;
}
node.style[prop] = val + 'px';
}
}
});
}, '@VERSION@', {"requires": ["dom-core"]});
YUI.add('color-base', function (Y, NAME) {
/**
Color provides static methods for color conversion.
Y.Color.toRGB('f00'); // rgb(255, 0, 0)
Y.Color.toHex('rgb(255, 255, 0)'); // #ffff00
@module color
@submodule color-base
@class Color
@since 3.8.0
**/
var REGEX_HEX = /^#?([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})(\ufffe)?/,
REGEX_HEX3 = /^#?([\da-fA-F]{1})([\da-fA-F]{1})([\da-fA-F]{1})(\ufffe)?/,
REGEX_RGB = /rgba?\(([\d]{1,3}), ?([\d]{1,3}), ?([\d]{1,3}),? ?([.\d]*)?\)/,
TYPES = { 'HEX': 'hex', 'RGB': 'rgb', 'RGBA': 'rgba' },
CONVERTS = { 'hex': 'toHex', 'rgb': 'toRGB', 'rgba': 'toRGBA' };
Y.Color = {
/**
@static
@property KEYWORDS
@type Object
@since 3.8.0
**/
KEYWORDS: {
'black': '000', 'silver': 'c0c0c0', 'gray': '808080', 'white': 'fff',
'maroon': '800000', 'red': 'f00', 'purple': '800080', 'fuchsia': 'f0f',
'green': '008000', 'lime': '0f0', 'olive': '808000', 'yellow': 'ff0',
'navy': '000080', 'blue': '00f', 'teal': '008080', 'aqua': '0ff'
},
/**
NOTE: `(\ufffe)?` is added to the Regular Expression to carve out a
place for the alpha channel that is returned from toArray
without compromising any usage of the Regular Expression
@static
@property REGEX_HEX
@type RegExp
@default /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})(\ufffe)?/
@since 3.8.0
**/
REGEX_HEX: REGEX_HEX,
/**
NOTE: `(\ufffe)?` is added to the Regular Expression to carve out a
place for the alpha channel that is returned from toArray
without compromising any usage of the Regular Expression
@static
@property REGEX_HEX3
@type RegExp
@default /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})(\ufffe)?/
@since 3.8.0
**/
REGEX_HEX3: REGEX_HEX3,
/**
@static
@property REGEX_RGB
@type RegExp
@default /rgba?\(([0-9]{1,3}), ?([0-9]{1,3}), ?([0-9]{1,3}),? ?([.0-9]{1,3})?\)/
@since 3.8.0
**/
REGEX_RGB: REGEX_RGB,
re_RGB: REGEX_RGB,
re_hex: REGEX_HEX,
re_hex3: REGEX_HEX3,
/**
@static
@property STR_HEX
@type String
@default #{*}{*}{*}
@since 3.8.0
**/
STR_HEX: '#{*}{*}{*}',
/**
@static
@property STR_RGB
@type String
@default rgb({*}, {*}, {*})
@since 3.8.0
**/
STR_RGB: 'rgb({*}, {*}, {*})',
/**
@static
@property STR_RGBA
@type String
@default rgba({*}, {*}, {*}, {*})
@since 3.8.0
**/
STR_RGBA: 'rgba({*}, {*}, {*}, {*})',
/**
@static
@property TYPES
@type Object
@default {'rgb':'rgb', 'rgba':'rgba'}
@since 3.8.0
**/
TYPES: TYPES,
/**
@static
@property CONVERTS
@type Object
@default {}
@since 3.8.0
**/
CONVERTS: CONVERTS,
/**
Converts the provided string to the provided type.
You can use the `Y.Color.TYPES` to get a valid `to` type.
If the color cannot be converted, the original color will be returned.
@public
@method convert
@param {String} str
@param {String} to
@return {String}
@since 3.8.0
**/
convert: function (str, to) {
var convert = Y.Color.CONVERTS[to.toLowerCase()],
clr = str;
if (convert && Y.Color[convert]) {
clr = Y.Color[convert](str);
}
return clr;
},
/**
Converts provided color value to a hex value string
@public
@method toHex
@param {String} str Hex or RGB value string
@return {String} returns array of values or CSS string if options.css is true
@since 3.8.0
**/
toHex: function (str) {
var clr = Y.Color._convertTo(str, 'hex'),
isTransparent = clr.toLowerCase() === 'transparent';
if (clr.charAt(0) !== '#' && !isTransparent) {
clr = '#' + clr;
}
return isTransparent ? clr.toLowerCase() : clr.toUpperCase();
},
/**
Converts provided color value to an RGB value string
@public
@method toRGB
@param {String} str Hex or RGB value string
@return {String}
@since 3.8.0
**/
toRGB: function (str) {
var clr = Y.Color._convertTo(str, 'rgb');
return clr.toLowerCase();
},
/**
Converts provided color value to an RGB value string
@public
@method toRGBA
@param {String} str Hex or RGB value string
@return {String}
@since 3.8.0
**/
toRGBA: function (str) {
var clr = Y.Color._convertTo(str, 'rgba' );
return clr.toLowerCase();
},
/**
Converts the provided color string to an array of values where the
last value is the alpha value. Will return an empty array if
the provided string is not able to be parsed.
NOTE: `(\ufffe)?` is added to `HEX` and `HEX3` Regular Expressions to
carve out a place for the alpha channel that is returned from
toArray without compromising any usage of the Regular Expression
Y.Color.toArray('fff'); // ['ff', 'ff', 'ff', 1]
Y.Color.toArray('rgb(0, 0, 0)'); // ['0', '0', '0', 1]
Y.Color.toArray('rgba(0, 0, 0, 0)'); // ['0', '0', '0', 1]
@public
@method toArray
@param {String} str
@return {Array}
@since 3.8.0
**/
toArray: function(str) {
// parse with regex and return "matches" array
var type = Y.Color.findType(str).toUpperCase(),
regex,
arr,
length,
lastItem;
if (type === 'HEX' && str.length < 5) {
type = 'HEX3';
}
if (type.charAt(type.length - 1) === 'A') {
type = type.slice(0, -1);
}
regex = Y.Color['REGEX_' + type];
if (regex) {
arr = regex.exec(str) || [];
length = arr.length;
if (length) {
arr.shift();
length--;
if (type === 'HEX3') {
arr[0] += arr[0];
arr[1] += arr[1];
arr[2] += arr[2];
}
lastItem = arr[length - 1];
if (!lastItem) {
arr[length - 1] = 1;
}
}
}
return arr;
},
/**
Converts the array of values to a string based on the provided template.
@public
@method fromArray
@param {Array} arr
@param {String} template
@return {String}
@since 3.8.0
**/
fromArray: function(arr, template) {
arr = arr.concat();
if (typeof template === 'undefined') {
return arr.join(', ');
}
var replace = '{*}';
template = Y.Color['STR_' + template.toUpperCase()];
if (arr.length === 3 && template.match(/\{\*\}/g).length === 4) {
arr.push(1);
}
while ( template.indexOf(replace) >= 0 && arr.length > 0) {
template = template.replace(replace, arr.shift());
}
return template;
},
/**
Finds the value type based on the str value provided.
@public
@method findType
@param {String} str
@return {String}
@since 3.8.0
**/
findType: function (str) {
if (Y.Color.KEYWORDS[str]) {
return 'keyword';
}
var index = str.indexOf('('),
key;
if (index > 0) {
key = str.substr(0, index);
}
if (key && Y.Color.TYPES[key.toUpperCase()]) {
return Y.Color.TYPES[key.toUpperCase()];
}
return 'hex';
}, // return 'keyword', 'hex', 'rgb'
/**
Retrives the alpha channel from the provided string. If no alpha
channel is present, `1` will be returned.
@protected
@method _getAlpha
@param {String} clr
@return {Number}
@since 3.8.0
**/
_getAlpha: function (clr) {
var alpha,
arr = Y.Color.toArray(clr);
if (arr.length > 3) {
alpha = arr.pop();
}
return +alpha || 1;
},
/**
Returns the hex value string if found in the KEYWORDS object
@protected
@method _keywordToHex
@param {String} clr
@return {String}
@since 3.8.0
**/
_keywordToHex: function (clr) {
var keyword = Y.Color.KEYWORDS[clr];
if (keyword) {
return keyword;
}
},
/**
Converts the provided color string to the value type provided as `to`
@protected
@method _convertTo
@param {String} clr
@param {String} to
@return {String}
@since 3.8.0
**/
_convertTo: function(clr, to) {
if (clr === 'transparent') {
return clr;
}
var from = Y.Color.findType(clr),
originalTo = to,
needsAlpha,
alpha,
method,
ucTo;
if (from === 'keyword') {
clr = Y.Color._keywordToHex(clr);
from = 'hex';
}
if (from === 'hex' && clr.length < 5) {
if (clr.charAt(0) === '#') {
clr = clr.substr(1);
}
clr = '#' + clr.charAt(0) + clr.charAt(0) +
clr.charAt(1) + clr.charAt(1) +
clr.charAt(2) + clr.charAt(2);
}
if (from === to) {
return clr;
}
if (from.charAt(from.length - 1) === 'a') {
from = from.slice(0, -1);
}
needsAlpha = (to.charAt(to.length - 1) === 'a');
if (needsAlpha) {
to = to.slice(0, -1);
alpha = Y.Color._getAlpha(clr);
}
ucTo = to.charAt(0).toUpperCase() + to.substr(1).toLowerCase();
method = Y.Color['_' + from + 'To' + ucTo ];
// check to see if need conversion to rgb first
// check to see if there is a direct conversion method
// convertions are: hex <-> rgb <-> hsl
if (!method) {
if (from !== 'rgb' && to !== 'rgb') {
clr = Y.Color['_' + from + 'ToRgb'](clr);
from = 'rgb';
method = Y.Color['_' + from + 'To' + ucTo ];
}
}
if (method) {
clr = ((method)(clr, needsAlpha));
}
// process clr from arrays to strings after conversions if alpha is needed
if (needsAlpha) {
if (!Y.Lang.isArray(clr)) {
clr = Y.Color.toArray(clr);
}
clr.push(alpha);
clr = Y.Color.fromArray(clr, originalTo.toUpperCase());
}
return clr;
},
/**
Processes the hex string into r, g, b values. Will return values as
an array, or as an rgb string.
@protected
@method _hexToRgb
@param {String} str
@param {Boolean} [toArray]
@return {String|Array}
@since 3.8.0
**/
_hexToRgb: function (str, toArray) {
var r, g, b;
/*jshint bitwise:false*/
if (str.charAt(0) === '#') {
str = str.substr(1);
}
str = parseInt(str, 16);
r = str >> 16;
g = str >> 8 & 0xFF;
b = str & 0xFF;
if (toArray) {
return [r, g, b];
}
return 'rgb(' + r + ', ' + g + ', ' + b + ')';
},
/**
Processes the rgb string into r, g, b values. Will return values as
an array, or as a hex string.
@protected
@method _rgbToHex
@param {String} str
@param {Boolean} [toArray]
@return {String|Array}
@since 3.8.0
**/
_rgbToHex: function (str) {
/*jshint bitwise:false*/
var rgb = Y.Color.toArray(str),
hex = rgb[2] | (rgb[1] << 8) | (rgb[0] << 16);
hex = (+hex).toString(16);
while (hex.length < 6) {
hex = '0' + hex;
}
return '#' + hex;
}
};
}, '@VERSION@', {"requires": ["yui-base"]});
YUI.add('dom-style', function (Y, NAME) {
(function(Y) {
/**
* Add style management functionality to DOM.
* @module dom
* @submodule dom-style
* @for DOM
*/
var DOCUMENT_ELEMENT = 'documentElement',
DEFAULT_VIEW = 'defaultView',
OWNER_DOCUMENT = 'ownerDocument',
STYLE = 'style',
FLOAT = 'float',
CSS_FLOAT = 'cssFloat',
STYLE_FLOAT = 'styleFloat',
TRANSPARENT = 'transparent',
GET_COMPUTED_STYLE = 'getComputedStyle',
GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect',
WINDOW = Y.config.win,
DOCUMENT = Y.config.doc,
UNDEFINED = undefined,
Y_DOM = Y.DOM,
TRANSFORM = 'transform',
TRANSFORMORIGIN = 'transformOrigin',
VENDOR_TRANSFORM = [
'WebkitTransform',
'MozTransform',
'OTransform',
'msTransform'
],
re_color = /color$/i,
re_unit = /width|height|top|left|right|bottom|margin|padding/i;
Y.Array.each(VENDOR_TRANSFORM, function(val) {
if (val in DOCUMENT[DOCUMENT_ELEMENT].style) {
TRANSFORM = val;
TRANSFORMORIGIN = val + "Origin";
}
});
Y.mix(Y_DOM, {
DEFAULT_UNIT: 'px',
CUSTOM_STYLES: {
},
/**
* Sets a style property for a given element.
* @method setStyle
* @param {HTMLElement} An HTMLElement to apply the style to.
* @param {String} att The style property to set.
* @param {String|Number} val The value.
*/
setStyle: function(node, att, val, style) {
style = style || node.style;
var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES;
if (style) {
if (val === null || val === '') { // normalize unsetting
val = '';
} else if (!isNaN(new Number(val)) && re_unit.test(att)) { // number values may need a unit
val += Y_DOM.DEFAULT_UNIT;
}
if (att in CUSTOM_STYLES) {
if (CUSTOM_STYLES[att].set) {
CUSTOM_STYLES[att].set(node, val, style);
return; // NOTE: return
} else if (typeof CUSTOM_STYLES[att] === 'string') {
att = CUSTOM_STYLES[att];
}
} else if (att === '') { // unset inline styles
att = 'cssText';
val = '';
}
style[att] = val;
}
},
/**
* Returns the current style value for the given property.
* @method getStyle
* @param {HTMLElement} An HTMLElement to get the style from.
* @param {String} att The style property to get.
*/
getStyle: function(node, att, style) {
style = style || node.style;
var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES,
val = '';
if (style) {
if (att in CUSTOM_STYLES) {
if (CUSTOM_STYLES[att].get) {
return CUSTOM_STYLES[att].get(node, att, style); // NOTE: return
} else if (typeof CUSTOM_STYLES[att] === 'string') {
att = CUSTOM_STYLES[att];
}
}
val = style[att];
if (val === '') { // TODO: is empty string sufficient?
val = Y_DOM[GET_COMPUTED_STYLE](node, att);
}
}
return val;
},
/**
* Sets multiple style properties.
* @method setStyles
* @param {HTMLElement} node An HTMLElement to apply the styles to.
* @param {Object} hash An object literal of property:value pairs.
*/
setStyles: function(node, hash) {
var style = node.style;
Y.each(hash, function(v, n) {
Y_DOM.setStyle(node, n, v, style);
}, Y_DOM);
},
/**
* Returns the computed style for the given node.
* @method getComputedStyle
* @param {HTMLElement} An HTMLElement to get the style from.
* @param {String} att The style property to get.
* @return {String} The computed value of the style property.
*/
getComputedStyle: function(node, att) {
var val = '',
doc = node[OWNER_DOCUMENT],
computed;
if (node[STYLE] && doc[DEFAULT_VIEW] && doc[DEFAULT_VIEW][GET_COMPUTED_STYLE]) {
computed = doc[DEFAULT_VIEW][GET_COMPUTED_STYLE](node, null);
if (computed) { // FF may be null in some cases (ticket #2530548)
val = computed[att];
}
}
return val;
}
});
// normalize reserved word float alternatives ("cssFloat" or "styleFloat")
if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][CSS_FLOAT] !== UNDEFINED) {
Y_DOM.CUSTOM_STYLES[FLOAT] = CSS_FLOAT;
} else if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][STYLE_FLOAT] !== UNDEFINED) {
Y_DOM.CUSTOM_STYLES[FLOAT] = STYLE_FLOAT;
}
// fix opera computedStyle default color unit (convert to rgb)
if (Y.UA.opera) {
Y_DOM[GET_COMPUTED_STYLE] = function(node, att) {
var view = node[OWNER_DOCUMENT][DEFAULT_VIEW],
val = view[GET_COMPUTED_STYLE](node, '')[att];
if (re_color.test(att)) {
val = Y.Color.toRGB(val);
}
return val;
};
}
// safari converts transparent to rgba(), others use "transparent"
if (Y.UA.webkit) {
Y_DOM[GET_COMPUTED_STYLE] = function(node, att) {
var view = node[OWNER_DOCUMENT][DEFAULT_VIEW],
val = view[GET_COMPUTED_STYLE](node, '')[att];
if (val === 'rgba(0, 0, 0, 0)') {
val = TRANSPARENT;
}
return val;
};
}
Y.DOM._getAttrOffset = function(node, attr) {
var val = Y.DOM[GET_COMPUTED_STYLE](node, attr),
offsetParent = node.offsetParent,
position,
parentOffset,
offset;
if (val === 'auto') {
position = Y.DOM.getStyle(node, 'position');
if (position === 'static' || position === 'relative') {
val = 0;
} else if (offsetParent && offsetParent[GET_BOUNDING_CLIENT_RECT]) {
parentOffset = offsetParent[GET_BOUNDING_CLIENT_RECT]()[attr];
offset = node[GET_BOUNDING_CLIENT_RECT]()[attr];
if (attr === 'left' || attr === 'top') {
val = offset - parentOffset;
} else {
val = parentOffset - node[GET_BOUNDING_CLIENT_RECT]()[attr];
}
}
}
return val;
};
Y.DOM._getOffset = function(node) {
var pos,
xy = null;
if (node) {
pos = Y_DOM.getStyle(node, 'position');
xy = [
parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'left'), 10),
parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'top'), 10)
];
if ( isNaN(xy[0]) ) { // in case of 'auto'
xy[0] = parseInt(Y_DOM.getStyle(node, 'left'), 10); // try inline
if ( isNaN(xy[0]) ) { // default to offset value
xy[0] = (pos === 'relative') ? 0 : node.offsetLeft || 0;
}
}
if ( isNaN(xy[1]) ) { // in case of 'auto'
xy[1] = parseInt(Y_DOM.getStyle(node, 'top'), 10); // try inline
if ( isNaN(xy[1]) ) { // default to offset value
xy[1] = (pos === 'relative') ? 0 : node.offsetTop || 0;
}
}
}
return xy;
};
Y_DOM.CUSTOM_STYLES.transform = {
set: function(node, val, style) {
style[TRANSFORM] = val;
},
get: function(node, style) {
return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORM);
}
};
Y_DOM.CUSTOM_STYLES.transformOrigin = {
set: function(node, val, style) {
style[TRANSFORMORIGIN] = val;
},
get: function(node, style) {
return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORMORIGIN);
}
};
})(Y);
}, '@VERSION@', {"requires": ["dom-base", "color-base"]});
YUI.add('dom-style-ie', function (Y, NAME) {
(function(Y) {
var HAS_LAYOUT = 'hasLayout',
PX = 'px',
FILTER = 'filter',
FILTERS = 'filters',
OPACITY = 'opacity',
AUTO = 'auto',
BORDER_WIDTH = 'borderWidth',
BORDER_TOP_WIDTH = 'borderTopWidth',
BORDER_RIGHT_WIDTH = 'borderRightWidth',
BORDER_BOTTOM_WIDTH = 'borderBottomWidth',
BORDER_LEFT_WIDTH = 'borderLeftWidth',
WIDTH = 'width',
HEIGHT = 'height',
TRANSPARENT = 'transparent',
VISIBLE = 'visible',
GET_COMPUTED_STYLE = 'getComputedStyle',
UNDEFINED = undefined,
documentElement = Y.config.doc.documentElement,
testFeature = Y.Features.test,
addFeature = Y.Features.add,
// TODO: unit-less lineHeight (e.g. 1.22)
re_unit = /^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i,
isIE8 = (Y.UA.ie >= 8),
_getStyleObj = function(node) {
return node.currentStyle || node.style;
},
ComputedStyle = {
CUSTOM_STYLES: {},
get: function(el, property) {
var value = '',
current;
if (el) {
current = _getStyleObj(el)[property];
if (property === OPACITY && Y.DOM.CUSTOM_STYLES[OPACITY]) {
value = Y.DOM.CUSTOM_STYLES[OPACITY].get(el);
} else if (!current || (current.indexOf && current.indexOf(PX) > -1)) { // no need to convert
value = current;
} else if (Y.DOM.IE.COMPUTED[property]) { // use compute function
value = Y.DOM.IE.COMPUTED[property](el, property);
} else if (re_unit.test(current)) { // convert to pixel
value = ComputedStyle.getPixel(el, property) + PX;
} else {
value = current;
}
}
return value;
},
sizeOffsets: {
width: ['Left', 'Right'],
height: ['Top', 'Bottom'],
top: ['Top'],
bottom: ['Bottom']
},
getOffset: function(el, prop) {
var current = _getStyleObj(el)[prop], // value of "width", "top", etc.
capped = prop.charAt(0).toUpperCase() + prop.substr(1), // "Width", "Top", etc.
offset = 'offset' + capped, // "offsetWidth", "offsetTop", etc.
pixel = 'pixel' + capped, // "pixelWidth", "pixelTop", etc.
sizeOffsets = ComputedStyle.sizeOffsets[prop],
mode = el.ownerDocument.compatMode,
value = '';
// IE pixelWidth incorrect for percent
// manually compute by subtracting padding and border from offset size
// NOTE: clientWidth/Height (size minus border) is 0 when current === AUTO so offsetHeight is used
// reverting to auto from auto causes position stacking issues (old impl)
if (current === AUTO || current.indexOf('%') > -1) {
value = el['offset' + capped];
if (mode !== 'BackCompat') {
if (sizeOffsets[0]) {
value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[0]);
value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[0] + 'Width', 1);
}
if (sizeOffsets[1]) {
value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[1]);
value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[1] + 'Width', 1);
}
}
} else { // use style.pixelWidth, etc. to convert to pixels
// need to map style.width to currentStyle (no currentStyle.pixelWidth)
if (!el.style[pixel] && !el.style[prop]) {
el.style[prop] = current;
}
value = el.style[pixel];
}
return value + PX;
},
borderMap: {
thin: (isIE8) ? '1px' : '2px',
medium: (isIE8) ? '3px': '4px',
thick: (isIE8) ? '5px' : '6px'
},
getBorderWidth: function(el, property, omitUnit) {
var unit = omitUnit ? '' : PX,
current = el.currentStyle[property];
if (current.indexOf(PX) < 0) { // look up keywords if a border exists
if (ComputedStyle.borderMap[current] &&
el.currentStyle.borderStyle !== 'none') {
current = ComputedStyle.borderMap[current];
} else { // otherwise no border (default is "medium")
current = 0;
}
}
return (omitUnit) ? parseFloat(current) : current;
},
getPixel: function(node, att) {
// use pixelRight to convert to px
var val = null,
style = _getStyleObj(node),
styleRight = style.right,
current = style[att];
node.style.right = current;
val = node.style.pixelRight;
node.style.right = styleRight; // revert
return val;
},
getMargin: function(node, att) {
var val,
style = _getStyleObj(node);
if (style[att] == AUTO) {
val = 0;
} else {
val = ComputedStyle.getPixel(node, att);
}
return val + PX;
},
getVisibility: function(node, att) {
var current;
while ( (current = node.currentStyle) && current[att] == 'inherit') { // NOTE: assignment in test
node = node.parentNode;
}
return (current) ? current[att] : VISIBLE;
},
getColor: function(node, att) {
var current = _getStyleObj(node)[att];
if (!current || current === TRANSPARENT) {
Y.DOM.elementByAxis(node, 'parentNode', null, function(parent) {
current = _getStyleObj(parent)[att];
if (current && current !== TRANSPARENT) {
node = parent;
return true;
}
});
}
return Y.Color.toRGB(current);
},
getBorderColor: function(node, att) {
var current = _getStyleObj(node),
val = current[att] || current.color;
return Y.Color.toRGB(Y.Color.toHex(val));
}
},
//fontSize: getPixelFont,
IEComputed = {};
addFeature('style', 'computedStyle', {
test: function() {
return 'getComputedStyle' in Y.config.win;
}
});
addFeature('style', 'opacity', {
test: function() {
return 'opacity' in documentElement.style;
}
});
addFeature('style', 'filter', {
test: function() {
return 'filters' in documentElement;
}
});
// use alpha filter for IE opacity
if (!testFeature('style', 'opacity') && testFeature('style', 'filter')) {
Y.DOM.CUSTOM_STYLES[OPACITY] = {
get: function(node) {
var val = 100;
try { // will error if no DXImageTransform
val = node[FILTERS]['DXImageTransform.Microsoft.Alpha'][OPACITY];
} catch(e) {
try { // make sure its in the document
val = node[FILTERS]('alpha')[OPACITY];
} catch(err) {
Y.log('getStyle: IE opacity filter not found; returning 1', 'warn', 'dom-style');
}
}
return val / 100;
},
set: function(node, val, style) {
var current,
styleObj = _getStyleObj(node),
currentFilter = styleObj[FILTER];
style = style || node.style;
if (val === '') { // normalize inline style behavior
current = (OPACITY in styleObj) ? styleObj[OPACITY] : 1; // revert to original opacity
val = current;
}
if (typeof currentFilter == 'string') { // in case not appended
style[FILTER] = currentFilter.replace(/alpha([^)]*\))/gi, '') +
((val < 1) ? 'alpha(' + OPACITY + '=' + val * 100 + ')' : '');
if (!style[FILTER]) {
style.removeAttribute(FILTER);
}
if (!styleObj[HAS_LAYOUT]) {
style.zoom = 1; // needs layout
}
}
}
};
}
try {
Y.config.doc.createElement('div').style.height = '-1px';
} catch(e) { // IE throws error on invalid style set; trap common cases
Y.DOM.CUSTOM_STYLES.height = {
set: function(node, val, style) {
var floatVal = parseFloat(val);
if (floatVal >= 0 || val === 'auto' || val === '') {
style.height = val;
} else {
Y.log('invalid style value for height: ' + val, 'warn', 'dom-style');
}
}
};
Y.DOM.CUSTOM_STYLES.width = {
set: function(node, val, style) {
var floatVal = parseFloat(val);
if (floatVal >= 0 || val === 'auto' || val === '') {
style.width = val;
} else {
Y.log('invalid style value for width: ' + val, 'warn', 'dom-style');
}
}
};
}
if (!testFeature('style', 'computedStyle')) {
// TODO: top, right, bottom, left
IEComputed[WIDTH] = IEComputed[HEIGHT] = ComputedStyle.getOffset;
IEComputed.color = IEComputed.backgroundColor = ComputedStyle.getColor;
IEComputed[BORDER_WIDTH] = IEComputed[BORDER_TOP_WIDTH] = IEComputed[BORDER_RIGHT_WIDTH] =
IEComputed[BORDER_BOTTOM_WIDTH] = IEComputed[BORDER_LEFT_WIDTH] =
ComputedStyle.getBorderWidth;
IEComputed.marginTop = IEComputed.marginRight = IEComputed.marginBottom =
IEComputed.marginLeft = ComputedStyle.getMargin;
IEComputed.visibility = ComputedStyle.getVisibility;
IEComputed.borderColor = IEComputed.borderTopColor =
IEComputed.borderRightColor = IEComputed.borderBottomColor =
IEComputed.borderLeftColor = ComputedStyle.getBorderColor;
Y.DOM[GET_COMPUTED_STYLE] = ComputedStyle.get;
Y.namespace('DOM.IE');
Y.DOM.IE.COMPUTED = IEComputed;
Y.DOM.IE.ComputedStyle = ComputedStyle;
}
})(Y);
}, '@VERSION@', {"requires": ["dom-style"]});
YUI.add('dom-screen', function (Y, NAME) {
(function(Y) {
/**
* Adds position and region management functionality to DOM.
* @module dom
* @submodule dom-screen
* @for DOM
*/
var DOCUMENT_ELEMENT = 'documentElement',
COMPAT_MODE = 'compatMode',
POSITION = 'position',
FIXED = 'fixed',
RELATIVE = 'relative',
LEFT = 'left',
TOP = 'top',
_BACK_COMPAT = 'BackCompat',
MEDIUM = 'medium',
BORDER_LEFT_WIDTH = 'borderLeftWidth',
BORDER_TOP_WIDTH = 'borderTopWidth',
GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect',
GET_COMPUTED_STYLE = 'getComputedStyle',
Y_DOM = Y.DOM,
// TODO: how about thead/tbody/tfoot/tr?
// TODO: does caption matter?
RE_TABLE = /^t(?:able|d|h)$/i,
SCROLL_NODE;
if (Y.UA.ie) {
if (Y.config.doc[COMPAT_MODE] !== 'BackCompat') {
SCROLL_NODE = DOCUMENT_ELEMENT;
} else {
SCROLL_NODE = 'body';
}
}
Y.mix(Y_DOM, {
/**
* Returns the inner height of the viewport (exludes scrollbar).
* @method winHeight
* @return {Number} The current height of the viewport.
*/
winHeight: function(node) {
var h = Y_DOM._getWinSize(node).height;
Y.log('winHeight returning ' + h, 'info', 'dom-screen');
return h;
},
/**
* Returns the inner width of the viewport (exludes scrollbar).
* @method winWidth
* @return {Number} The current width of the viewport.
*/
winWidth: function(node) {
var w = Y_DOM._getWinSize(node).width;
Y.log('winWidth returning ' + w, 'info', 'dom-screen');
return w;
},
/**
* Document height
* @method docHeight
* @return {Number} The current height of the document.
*/
docHeight: function(node) {
var h = Y_DOM._getDocSize(node).height;
Y.log('docHeight returning ' + h, 'info', 'dom-screen');
return Math.max(h, Y_DOM._getWinSize(node).height);
},
/**
* Document width
* @method docWidth
* @return {Number} The current width of the document.
*/
docWidth: function(node) {
var w = Y_DOM._getDocSize(node).width;
Y.log('docWidth returning ' + w, 'info', 'dom-screen');
return Math.max(w, Y_DOM._getWinSize(node).width);
},
/**
* Amount page has been scroll horizontally
* @method docScrollX
* @return {Number} The current amount the screen is scrolled horizontally.
*/
docScrollX: function(node, doc) {
doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization
var dv = doc.defaultView,
pageOffset = (dv) ? dv.pageXOffset : 0;
return Math.max(doc[DOCUMENT_ELEMENT].scrollLeft, doc.body.scrollLeft, pageOffset);
},
/**
* Amount page has been scroll vertically
* @method docScrollY
* @return {Number} The current amount the screen is scrolled vertically.
*/
docScrollY: function(node, doc) {
doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization
var dv = doc.defaultView,
pageOffset = (dv) ? dv.pageYOffset : 0;
return Math.max(doc[DOCUMENT_ELEMENT].scrollTop, doc.body.scrollTop, pageOffset);
},
/**
* Gets the current position of an element based on page coordinates.
* Element must be part of the DOM tree to have page coordinates
* (display:none or elements not appended return false).
* @method getXY
* @param element The target element
* @return {Array} The XY position of the element
TODO: test inDocument/display?
*/
getXY: function() {
if (Y.config.doc[DOCUMENT_ELEMENT][GET_BOUNDING_CLIENT_RECT]) {
return function(node) {
var xy = null,
scrollLeft,
scrollTop,
mode,
box,
offX,
offY,
doc,
win,
inDoc,
rootNode;
if (node && node.tagName) {
doc = node.ownerDocument;
mode = doc[COMPAT_MODE];
if (mode !== _BACK_COMPAT) {
rootNode = doc[DOCUMENT_ELEMENT];
} else {
rootNode = doc.body;
}
// inline inDoc check for perf
if (rootNode.contains) {
inDoc = rootNode.contains(node);
} else {
inDoc = Y.DOM.contains(rootNode, node);
}
if (inDoc) {
win = doc.defaultView;
// inline scroll calc for perf
if (win && 'pageXOffset' in win) {
scrollLeft = win.pageXOffset;
scrollTop = win.pageYOffset;
} else {
scrollLeft = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollLeft : Y_DOM.docScrollX(node, doc);
scrollTop = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollTop : Y_DOM.docScrollY(node, doc);
}
if (Y.UA.ie) { // IE < 8, quirks, or compatMode
if (!doc.documentMode || doc.documentMode < 8 || mode === _BACK_COMPAT) {
offX = rootNode.clientLeft;
offY = rootNode.clientTop;
}
}
box = node[GET_BOUNDING_CLIENT_RECT]();
xy = [box.left, box.top];
if (offX || offY) {
xy[0] -= offX;
xy[1] -= offY;
}
if ((scrollTop || scrollLeft)) {
if (!Y.UA.ios || (Y.UA.ios >= 4.2)) {
xy[0] += scrollLeft;
xy[1] += scrollTop;
}
}
} else {
xy = Y_DOM._getOffset(node);
}
}
return xy;
};
} else {
return function(node) { // manually calculate by crawling up offsetParents
//Calculate the Top and Left border sizes (assumes pixels)
var xy = null,
doc,
parentNode,
bCheck,
scrollTop,
scrollLeft;
if (node) {
if (Y_DOM.inDoc(node)) {
xy = [node.offsetLeft, node.offsetTop];
doc = node.ownerDocument;
parentNode = node;
// TODO: refactor with !! or just falsey
bCheck = ((Y.UA.gecko || Y.UA.webkit > 519) ? true : false);
// TODO: worth refactoring for TOP/LEFT only?
while ((parentNode = parentNode.offsetParent)) {
xy[0] += parentNode.offsetLeft;
xy[1] += parentNode.offsetTop;
if (bCheck) {
xy = Y_DOM._calcBorders(parentNode, xy);
}
}
// account for any scrolled ancestors
if (Y_DOM.getStyle(node, POSITION) != FIXED) {
parentNode = node;
while ((parentNode = parentNode.parentNode)) {
scrollTop = parentNode.scrollTop;
scrollLeft = parentNode.scrollLeft;
//Firefox does something funky with borders when overflow is not visible.
if (Y.UA.gecko && (Y_DOM.getStyle(parentNode, 'overflow') !== 'visible')) {
xy = Y_DOM._calcBorders(parentNode, xy);
}
if (scrollTop || scrollLeft) {
xy[0] -= scrollLeft;
xy[1] -= scrollTop;
}
}
xy[0] += Y_DOM.docScrollX(node, doc);
xy[1] += Y_DOM.docScrollY(node, doc);
} else {
//Fix FIXED position -- add scrollbars
xy[0] += Y_DOM.docScrollX(node, doc);
xy[1] += Y_DOM.docScrollY(node, doc);
}
} else {
xy = Y_DOM._getOffset(node);
}
}
return xy;
};
}
}(),// NOTE: Executing for loadtime branching
/**
Gets the width of vertical scrollbars on overflowed containers in the body
content.
@method getScrollbarWidth
@return {Number} Pixel width of a scrollbar in the current browser
**/
getScrollbarWidth: Y.cached(function () {
var doc = Y.config.doc,
testNode = doc.createElement('div'),
body = doc.getElementsByTagName('body')[0],
// 0.1 because cached doesn't support falsy refetch values
width = 0.1;
if (body) {
testNode.style.cssText = "position:absolute;visibility:hidden;overflow:scroll;width:20px;";
testNode.appendChild(doc.createElement('p')).style.height = '1px';
body.insertBefore(testNode, body.firstChild);
width = testNode.offsetWidth - testNode.clientWidth;
body.removeChild(testNode);
}
return width;
}, null, 0.1),
/**
* Gets the current X position of an element based on page coordinates.
* Element must be part of the DOM tree to have page coordinates
* (display:none or elements not appended return false).
* @method getX
* @param element The target element
* @return {Number} The X position of the element
*/
getX: function(node) {
return Y_DOM.getXY(node)[0];
},
/**
* Gets the current Y position of an element based on page coordinates.
* Element must be part of the DOM tree to have page coordinates
* (display:none or elements not appended return false).
* @method getY
* @param element The target element
* @return {Number} The Y position of the element
*/
getY: function(node) {
return Y_DOM.getXY(node)[1];
},
/**
* Set the position of an html element in page coordinates.
* The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @method setXY
* @param element The target element
* @param {Array} xy Contains X & Y values for new position (coordinates are page-based)
* @param {Boolean} noRetry By default we try and set the position a second time if the first fails
*/
setXY: function(node, xy, noRetry) {
var setStyle = Y_DOM.setStyle,
pos,
delta,
newXY,
currentXY;
if (node && xy) {
pos = Y_DOM.getStyle(node, POSITION);
delta = Y_DOM._getOffset(node);
if (pos == 'static') { // default to relative
pos = RELATIVE;
setStyle(node, POSITION, pos);
}
currentXY = Y_DOM.getXY(node);
if (xy[0] !== null) {
setStyle(node, LEFT, xy[0] - currentXY[0] + delta[0] + 'px');
}
if (xy[1] !== null) {
setStyle(node, TOP, xy[1] - currentXY[1] + delta[1] + 'px');
}
if (!noRetry) {
newXY = Y_DOM.getXY(node);
if (newXY[0] !== xy[0] || newXY[1] !== xy[1]) {
Y_DOM.setXY(node, xy, true);
}
}
Y.log('setXY setting position to ' + xy, 'info', 'dom-screen');
} else {
Y.log('setXY failed to set ' + node + ' to ' + xy, 'info', 'dom-screen');
}
},
/**
* Set the X position of an html element in page coordinates, regardless of how the element is positioned.
* The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @method setX
* @param element The target element
* @param {Number} x The X values for new position (coordinates are page-based)
*/
setX: function(node, x) {
return Y_DOM.setXY(node, [x, null]);
},
/**
* Set the Y position of an html element in page coordinates, regardless of how the element is positioned.
* The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @method setY
* @param element The target element
* @param {Number} y The Y values for new position (coordinates are page-based)
*/
setY: function(node, y) {
return Y_DOM.setXY(node, [null, y]);
},
/**
* @method swapXY
* @description Swap the xy position with another node
* @param {Node} node The node to swap with
* @param {Node} otherNode The other node to swap with
* @return {Node}
*/
swapXY: function(node, otherNode) {
var xy = Y_DOM.getXY(node);
Y_DOM.setXY(node, Y_DOM.getXY(otherNode));
Y_DOM.setXY(otherNode, xy);
},
_calcBorders: function(node, xy2) {
var t = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_TOP_WIDTH), 10) || 0,
l = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_LEFT_WIDTH), 10) || 0;
if (Y.UA.gecko) {
if (RE_TABLE.test(node.tagName)) {
t = 0;
l = 0;
}
}
xy2[0] += l;
xy2[1] += t;
return xy2;
},
_getWinSize: function(node, doc) {
doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc;
var win = doc.defaultView || doc.parentWindow,
mode = doc[COMPAT_MODE],
h = win.innerHeight,
w = win.innerWidth,
root = doc[DOCUMENT_ELEMENT];
if ( mode && !Y.UA.opera ) { // IE, Gecko
if (mode != 'CSS1Compat') { // Quirks
root = doc.body;
}
h = root.clientHeight;
w = root.clientWidth;
}
return { height: h, width: w };
},
_getDocSize: function(node) {
var doc = (node) ? Y_DOM._getDoc(node) : Y.config.doc,
root = doc[DOCUMENT_ELEMENT];
if (doc[COMPAT_MODE] != 'CSS1Compat') {
root = doc.body;
}
return { height: root.scrollHeight, width: root.scrollWidth };
}
});
})(Y);
(function(Y) {
var TOP = 'top',
RIGHT = 'right',
BOTTOM = 'bottom',
LEFT = 'left',
getOffsets = function(r1, r2) {
var t = Math.max(r1[TOP], r2[TOP]),
r = Math.min(r1[RIGHT], r2[RIGHT]),
b = Math.min(r1[BOTTOM], r2[BOTTOM]),
l = Math.max(r1[LEFT], r2[LEFT]),
ret = {};
ret[TOP] = t;
ret[RIGHT] = r;
ret[BOTTOM] = b;
ret[LEFT] = l;
return ret;
},
DOM = Y.DOM;
Y.mix(DOM, {
/**
* Returns an Object literal containing the following about this element: (top, right, bottom, left)
* @for DOM
* @method region
* @param {HTMLElement} element The DOM element.
* @return {Object} Object literal containing the following about this element: (top, right, bottom, left)
*/
region: function(node) {
var xy = DOM.getXY(node),
ret = false;
if (node && xy) {
ret = DOM._getRegion(
xy[1], // top
xy[0] + node.offsetWidth, // right
xy[1] + node.offsetHeight, // bottom
xy[0] // left
);
}
return ret;
},
/**
* Find the intersect information for the passed nodes.
* @method intersect
* @for DOM
* @param {HTMLElement} element The first element
* @param {HTMLElement | Object} element2 The element or region to check the interect with
* @param {Object} altRegion An object literal containing the region for the first element if we already have the data (for performance e.g. DragDrop)
* @return {Object} Object literal containing the following intersection data: (top, right, bottom, left, area, yoff, xoff, inRegion)
*/
intersect: function(node, node2, altRegion) {
var r = altRegion || DOM.region(node), region = {},
n = node2,
off;
if (n.tagName) {
region = DOM.region(n);
} else if (Y.Lang.isObject(node2)) {
region = node2;
} else {
return false;
}
off = getOffsets(region, r);
return {
top: off[TOP],
right: off[RIGHT],
bottom: off[BOTTOM],
left: off[LEFT],
area: ((off[BOTTOM] - off[TOP]) * (off[RIGHT] - off[LEFT])),
yoff: ((off[BOTTOM] - off[TOP])),
xoff: (off[RIGHT] - off[LEFT]),
inRegion: DOM.inRegion(node, node2, false, altRegion)
};
},
/**
* Check if any part of this node is in the passed region
* @method inRegion
* @for DOM
* @param {Object} node The node to get the region from
* @param {Object} node2 The second node to get the region from or an Object literal of the region
* @param {Boolean} all Should all of the node be inside the region
* @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop)
* @return {Boolean} True if in region, false if not.
*/
inRegion: function(node, node2, all, altRegion) {
var region = {},
r = altRegion || DOM.region(node),
n = node2,
off;
if (n.tagName) {
region = DOM.region(n);
} else if (Y.Lang.isObject(node2)) {
region = node2;
} else {
return false;
}
if (all) {
return (
r[LEFT] >= region[LEFT] &&
r[RIGHT] <= region[RIGHT] &&
r[TOP] >= region[TOP] &&
r[BOTTOM] <= region[BOTTOM] );
} else {
off = getOffsets(region, r);
if (off[BOTTOM] >= off[TOP] && off[RIGHT] >= off[LEFT]) {
return true;
} else {
return false;
}
}
},
/**
* Check if any part of this element is in the viewport
* @method inViewportRegion
* @for DOM
* @param {HTMLElement} element The DOM element.
* @param {Boolean} all Should all of the node be inside the region
* @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop)
* @return {Boolean} True if in region, false if not.
*/
inViewportRegion: function(node, all, altRegion) {
return DOM.inRegion(node, DOM.viewportRegion(node), all, altRegion);
},
_getRegion: function(t, r, b, l) {
var region = {};
region[TOP] = region[1] = t;
region[LEFT] = region[0] = l;
region[BOTTOM] = b;
region[RIGHT] = r;
region.width = region[RIGHT] - region[LEFT];
region.height = region[BOTTOM] - region[TOP];
return region;
},
/**
* Returns an Object literal containing the following about the visible region of viewport: (top, right, bottom, left)
* @method viewportRegion
* @for DOM
* @return {Object} Object literal containing the following about the visible region of the viewport: (top, right, bottom, left)
*/
viewportRegion: function(node) {
node = node || Y.config.doc.documentElement;
var ret = false,
scrollX,
scrollY;
if (node) {
scrollX = DOM.docScrollX(node);
scrollY = DOM.docScrollY(node);
ret = DOM._getRegion(scrollY, // top
DOM.winWidth(node) + scrollX, // right
scrollY + DOM.winHeight(node), // bottom
scrollX); // left
}
return ret;
}
});
})(Y);
}, '@VERSION@', {"requires": ["dom-base", "dom-style"]});
YUI.add('selector-native', function (Y, NAME) {
(function(Y) {
/**
* The selector-native module provides support for native querySelector
* @module dom
* @submodule selector-native
* @for Selector
*/
/**
* Provides support for using CSS selectors to query the DOM
* @class Selector
* @static
* @for Selector
*/
Y.namespace('Selector'); // allow native module to standalone
var COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition',
OWNER_DOCUMENT = 'ownerDocument';
var Selector = {
_types: {
esc: {
token: '\uE000',
re: /\\[:\[\]\(\)#\.\'\>+~"]/gi
},
attr: {
token: '\uE001',
re: /(\[[^\]]*\])/g
},
pseudo: {
token: '\uE002',
re: /(\([^\)]*\))/g
}
},
useNative: true,
_escapeId: function(id) {
if (id) {
id = id.replace(/([:\[\]\(\)#\.'<>+~"])/g,'\\$1');
}
return id;
},
_compare: ('sourceIndex' in Y.config.doc.documentElement) ?
function(nodeA, nodeB) {
var a = nodeA.sourceIndex,
b = nodeB.sourceIndex;
if (a === b) {
return 0;
} else if (a > b) {
return 1;
}
return -1;
} : (Y.config.doc.documentElement[COMPARE_DOCUMENT_POSITION] ?
function(nodeA, nodeB) {
if (nodeA[COMPARE_DOCUMENT_POSITION](nodeB) & 4) {
return -1;
} else {
return 1;
}
} :
function(nodeA, nodeB) {
var rangeA, rangeB, compare;
if (nodeA && nodeB) {
rangeA = nodeA[OWNER_DOCUMENT].createRange();
rangeA.setStart(nodeA, 0);
rangeB = nodeB[OWNER_DOCUMENT].createRange();
rangeB.setStart(nodeB, 0);
compare = rangeA.compareBoundaryPoints(1, rangeB); // 1 === Range.START_TO_END
}
return compare;
}),
_sort: function(nodes) {
if (nodes) {
nodes = Y.Array(nodes, 0, true);
if (nodes.sort) {
nodes.sort(Selector._compare);
}
}
return nodes;
},
_deDupe: function(nodes) {
var ret = [],
i, node;
for (i = 0; (node = nodes[i++]);) {
if (!node._found) {
ret[ret.length] = node;
node._found = true;
}
}
for (i = 0; (node = ret[i++]);) {
node._found = null;
node.removeAttribute('_found');
}
return ret;
},
/**
* Retrieves a set of nodes based on a given CSS selector.
* @method query
*
* @param {string} selector The CSS Selector to test the node against.
* @param {HTMLElement} root optional An HTMLElement to start the query from. Defaults to Y.config.doc
* @param {Boolean} firstOnly optional Whether or not to return only the first match.
* @return {Array} An array of nodes that match the given selector.
* @static
*/
query: function(selector, root, firstOnly, skipNative) {
root = root || Y.config.doc;
var ret = [],
useNative = (Y.Selector.useNative && Y.config.doc.querySelector && !skipNative),
queries = [[selector, root]],
query,
result,
i,
fn = (useNative) ? Y.Selector._nativeQuery : Y.Selector._bruteQuery;
if (selector && fn) {
// split group into seperate queries
if (!skipNative && // already done if skipping
(!useNative || root.tagName)) { // split native when element scoping is needed
queries = Selector._splitQueries(selector, root);
}
for (i = 0; (query = queries[i++]);) {
result = fn(query[0], query[1], firstOnly);
if (!firstOnly) { // coerce DOM Collection to Array
result = Y.Array(result, 0, true);
}
if (result) {
ret = ret.concat(result);
}
}
if (queries.length > 1) { // remove dupes and sort by doc order
ret = Selector._sort(Selector._deDupe(ret));
}
}
Y.log('query: ' + selector + ' returning: ' + ret.length, 'info', 'Selector');
return (firstOnly) ? (ret[0] || null) : ret;
},
_replaceSelector: function(selector) {
var esc = Y.Selector._parse('esc', selector), // pull escaped colon, brackets, etc.
attrs,
pseudos;
// first replace escaped chars, which could be present in attrs or pseudos
selector = Y.Selector._replace('esc', selector);
// then replace pseudos before attrs to avoid replacing :not([foo])
pseudos = Y.Selector._parse('pseudo', selector);
selector = Selector._replace('pseudo', selector);
attrs = Y.Selector._parse('attr', selector);
selector = Y.Selector._replace('attr', selector);
return {
esc: esc,
attrs: attrs,
pseudos: pseudos,
selector: selector
};
},
_restoreSelector: function(replaced) {
var selector = replaced.selector;
selector = Y.Selector._restore('attr', selector, replaced.attrs);
selector = Y.Selector._restore('pseudo', selector, replaced.pseudos);
selector = Y.Selector._restore('esc', selector, replaced.esc);
return selector;
},
_replaceCommas: function(selector) {
var replaced = Y.Selector._replaceSelector(selector),
selector = replaced.selector;
if (selector) {
selector = selector.replace(/,/g, '\uE007');
replaced.selector = selector;
selector = Y.Selector._restoreSelector(replaced);
}
return selector;
},
// allows element scoped queries to begin with combinator
// e.g. query('> p', document.body) === query('body > p')
_splitQueries: function(selector, node) {
if (selector.indexOf(',') > -1) {
selector = Y.Selector._replaceCommas(selector);
}
var groups = selector.split('\uE007'), // split on replaced comma token
queries = [],
prefix = '',
id,
i,
len;
if (node) {
// enforce for element scoping
if (node.nodeType === 1) { // Elements only
id = Y.Selector._escapeId(Y.DOM.getId(node));
if (!id) {
id = Y.guid();
Y.DOM.setId(node, id);
}
prefix = '[id="' + id + '"] ';
}
for (i = 0, len = groups.length; i < len; ++i) {
selector = prefix + groups[i];
queries.push([selector, node]);
}
}
return queries;
},
_nativeQuery: function(selector, root, one) {
if (Y.UA.webkit && selector.indexOf(':checked') > -1 &&
(Y.Selector.pseudos && Y.Selector.pseudos.checked)) { // webkit (chrome, safari) fails to pick up "selected" with "checked"
return Y.Selector.query(selector, root, one, true); // redo with skipNative true to try brute query
}
try {
//Y.log('trying native query with: ' + selector, 'info', 'selector-native');
return root['querySelector' + (one ? '' : 'All')](selector);
} catch(e) { // fallback to brute if available
//Y.log('native query error; reverting to brute query with: ' + selector, 'info', 'selector-native');
return Y.Selector.query(selector, root, one, true); // redo with skipNative true
}
},
filter: function(nodes, selector) {
var ret = [],
i, node;
if (nodes && selector) {
for (i = 0; (node = nodes[i++]);) {
if (Y.Selector.test(node, selector)) {
ret[ret.length] = node;
}
}
} else {
Y.log('invalid filter input (nodes: ' + nodes +
', selector: ' + selector + ')', 'warn', 'Selector');
}
return ret;
},
test: function(node, selector, root) {
var ret = false,
useFrag = false,
groups,
parent,
item,
items,
frag,
id,
i, j, group;
if (node && node.tagName) { // only test HTMLElements
if (typeof selector == 'function') { // test with function
ret = selector.call(node, node);
} else { // test with query
// we need a root if off-doc
groups = selector.split(',');
if (!root && !Y.DOM.inDoc(node)) {
parent = node.parentNode;
if (parent) {
root = parent;
} else { // only use frag when no parent to query
frag = node[OWNER_DOCUMENT].createDocumentFragment();
frag.appendChild(node);
root = frag;
useFrag = true;
}
}
root = root || node[OWNER_DOCUMENT];
id = Y.Selector._escapeId(Y.DOM.getId(node));
if (!id) {
id = Y.guid();
Y.DOM.setId(node, id);
}
for (i = 0; (group = groups[i++]);) { // TODO: off-dom test
group += '[id="' + id + '"]';
items = Y.Selector.query(group, root);
for (j = 0; item = items[j++];) {
if (item === node) {
ret = true;
break;
}
}
if (ret) {
break;
}
}
if (useFrag) { // cleanup
frag.removeChild(node);
}
};
}
return ret;
},
/**
* A convenience function to emulate Y.Node's aNode.ancestor(selector).
* @param {HTMLElement} element An HTMLElement to start the query from.
* @param {String} selector The CSS selector to test the node against.
* @return {HTMLElement} The ancestor node matching the selector, or null.
* @param {Boolean} testSelf optional Whether or not to include the element in the scan
* @static
* @method ancestor
*/
ancestor: function (element, selector, testSelf) {
return Y.DOM.ancestor(element, function(n) {
return Y.Selector.test(n, selector);
}, testSelf);
},
_parse: function(name, selector) {
return selector.match(Y.Selector._types[name].re);
},
_replace: function(name, selector) {
var o = Y.Selector._types[name];
return selector.replace(o.re, o.token);
},
_restore: function(name, selector, items) {
if (items) {
var token = Y.Selector._types[name].token,
i, len;
for (i = 0, len = items.length; i < len; ++i) {
selector = selector.replace(token, items[i]);
}
}
return selector;
}
};
Y.mix(Y.Selector, Selector, true);
})(Y);
}, '@VERSION@', {"requires": ["dom-base"]});
YUI.add('selector', function (Y, NAME) {
}, '@VERSION@', {"requires": ["selector-native"]});
YUI.add('event-custom-base', function (Y, NAME) {
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
*/
Y.Env.evt = {
handles: {},
plugins: {}
};
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
/**
* Allows for the insertion of methods that are executed before or after
* a specified method
* @class Do
* @static
*/
var DO_BEFORE = 0,
DO_AFTER = 1,
DO = {
/**
* Cache of objects touched by the utility
* @property objs
* @static
* @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object
* replaces the role of this property, but is considered to be private, and
* is only mentioned to provide a migration path.
*
* If you have a use case which warrants migration to the _yuiaop property,
* please file a ticket to let us know what it's used for and we can see if
* we need to expose hooks for that functionality more formally.
*/
objs: null,
/**
* <p>Execute the supplied method before the specified function. Wrapping
* function may optionally return an instance of the following classes to
* further alter runtime behavior:</p>
* <dl>
* <dt></code>Y.Do.Halt(message, returnValue)</code></dt>
* <dd>Immediatly stop execution and return
* <code>returnValue</code>. No other wrapping functions will be
* executed.</dd>
* <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt>
* <dd>Replace the arguments that the original function will be
* called with.</dd>
* <dt></code>Y.Do.Prevent(message)</code></dt>
* <dd>Don't execute the wrapped function. Other before phase
* wrappers will be executed.</dd>
* </dl>
*
* @method before
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {string} handle for the subscription
* @static
*/
before: function(fn, obj, sFn, c) {
// Y.log('Do before: ' + sFn, 'info', 'event');
var f = fn, a;
if (c) {
a = [fn, c].concat(Y.Array(arguments, 4, true));
f = Y.rbind.apply(Y, a);
}
return this._inject(DO_BEFORE, f, obj, sFn);
},
/**
* <p>Execute the supplied method after the specified function. Wrapping
* function may optionally return an instance of the following classes to
* further alter runtime behavior:</p>
* <dl>
* <dt></code>Y.Do.Halt(message, returnValue)</code></dt>
* <dd>Immediatly stop execution and return
* <code>returnValue</code>. No other wrapping functions will be
* executed.</dd>
* <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt>
* <dd>Return <code>returnValue</code> instead of the wrapped
* method's original return value. This can be further altered by
* other after phase wrappers.</dd>
* </dl>
*
* <p>The static properties <code>Y.Do.originalRetVal</code> and
* <code>Y.Do.currentRetVal</code> will be populated for reference.</p>
*
* @method after
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* @return {string} handle for the subscription
* @static
*/
after: function(fn, obj, sFn, c) {
var f = fn, a;
if (c) {
a = [fn, c].concat(Y.Array(arguments, 4, true));
f = Y.rbind.apply(Y, a);
}
return this._inject(DO_AFTER, f, obj, sFn);
},
/**
* Execute the supplied method before or after the specified function.
* Used by <code>before</code> and <code>after</code>.
*
* @method _inject
* @param when {string} before or after
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @return {string} handle for the subscription
* @private
* @static
*/
_inject: function(when, fn, obj, sFn) {
// object id
var id = Y.stamp(obj), o, sid;
if (!obj._yuiaop) {
// create a map entry for the obj if it doesn't exist, to hold overridden methods
obj._yuiaop = {};
}
o = obj._yuiaop;
if (!o[sFn]) {
// create a map entry for the method if it doesn't exist
o[sFn] = new Y.Do.Method(obj, sFn);
// re-route the method to our wrapper
obj[sFn] = function() {
return o[sFn].exec.apply(o[sFn], arguments);
};
}
// subscriber id
sid = id + Y.stamp(fn) + sFn;
// register the callback
o[sFn].register(sid, fn, when);
return new Y.EventHandle(o[sFn], sid);
},
/**
* Detach a before or after subscription.
*
* @method detach
* @param handle {string} the subscription handle
* @static
*/
detach: function(handle) {
if (handle.detach) {
handle.detach();
}
}
};
Y.Do = DO;
//////////////////////////////////////////////////////////////////////////
/**
* Contains the return value from the wrapped method, accessible
* by 'after' event listeners.
*
* @property originalRetVal
* @static
* @since 3.2.0
*/
/**
* Contains the current state of the return value, consumable by
* 'after' event listeners, and updated if an after subscriber
* changes the return value generated by the wrapped function.
*
* @property currentRetVal
* @static
* @since 3.2.0
*/
//////////////////////////////////////////////////////////////////////////
/**
* Wrapper for a displaced method with aop enabled
* @class Do.Method
* @constructor
* @param obj The object to operate on
* @param sFn The name of the method to displace
*/
DO.Method = function(obj, sFn) {
this.obj = obj;
this.methodName = sFn;
this.method = obj[sFn];
this.before = {};
this.after = {};
};
/**
* Register a aop subscriber
* @method register
* @param sid {string} the subscriber id
* @param fn {Function} the function to execute
* @param when {string} when to execute the function
*/
DO.Method.prototype.register = function (sid, fn, when) {
if (when) {
this.after[sid] = fn;
} else {
this.before[sid] = fn;
}
};
/**
* Unregister a aop subscriber
* @method delete
* @param sid {string} the subscriber id
* @param fn {Function} the function to execute
* @param when {string} when to execute the function
*/
DO.Method.prototype._delete = function (sid) {
// Y.log('Y.Do._delete: ' + sid, 'info', 'Event');
delete this.before[sid];
delete this.after[sid];
};
/**
* <p>Execute the wrapped method. All arguments are passed into the wrapping
* functions. If any of the before wrappers return an instance of
* <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped
* function nor any after phase subscribers will be executed.</p>
*
* <p>The return value will be the return value of the wrapped function or one
* provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or
* <code>Y.Do.AlterReturn</code>.
*
* @method exec
* @param arg* {any} Arguments are passed to the wrapping and wrapped functions
* @return {any} Return value of wrapped function unless overwritten (see above)
*/
DO.Method.prototype.exec = function () {
var args = Y.Array(arguments, 0, true),
i, ret, newRet,
bf = this.before,
af = this.after,
prevented = false;
// execute before
for (i in bf) {
if (bf.hasOwnProperty(i)) {
ret = bf[i].apply(this.obj, args);
if (ret) {
switch (ret.constructor) {
case DO.Halt:
return ret.retVal;
case DO.AlterArgs:
args = ret.newArgs;
break;
case DO.Prevent:
prevented = true;
break;
default:
}
}
}
}
// execute method
if (!prevented) {
ret = this.method.apply(this.obj, args);
}
DO.originalRetVal = ret;
DO.currentRetVal = ret;
// execute after methods.
for (i in af) {
if (af.hasOwnProperty(i)) {
newRet = af[i].apply(this.obj, args);
// Stop processing if a Halt object is returned
if (newRet && newRet.constructor === DO.Halt) {
return newRet.retVal;
// Check for a new return value
} else if (newRet && newRet.constructor === DO.AlterReturn) {
ret = newRet.newRetVal;
// Update the static retval state
DO.currentRetVal = ret;
}
}
}
return ret;
};
//////////////////////////////////////////////////////////////////////////
/**
* Return an AlterArgs object when you want to change the arguments that
* were passed into the function. Useful for Do.before subscribers. An
* example would be a service that scrubs out illegal characters prior to
* executing the core business logic.
* @class Do.AlterArgs
* @constructor
* @param msg {String} (optional) Explanation of the altered return value
* @param newArgs {Array} Call parameters to be used for the original method
* instead of the arguments originally passed in.
*/
DO.AlterArgs = function(msg, newArgs) {
this.msg = msg;
this.newArgs = newArgs;
};
/**
* Return an AlterReturn object when you want to change the result returned
* from the core method to the caller. Useful for Do.after subscribers.
* @class Do.AlterReturn
* @constructor
* @param msg {String} (optional) Explanation of the altered return value
* @param newRetVal {any} Return value passed to code that invoked the wrapped
* function.
*/
DO.AlterReturn = function(msg, newRetVal) {
this.msg = msg;
this.newRetVal = newRetVal;
};
/**
* Return a Halt object when you want to terminate the execution
* of all subsequent subscribers as well as the wrapped method
* if it has not exectued yet. Useful for Do.before subscribers.
* @class Do.Halt
* @constructor
* @param msg {String} (optional) Explanation of why the termination was done
* @param retVal {any} Return value passed to code that invoked the wrapped
* function.
*/
DO.Halt = function(msg, retVal) {
this.msg = msg;
this.retVal = retVal;
};
/**
* Return a Prevent object when you want to prevent the wrapped function
* from executing, but want the remaining listeners to execute. Useful
* for Do.before subscribers.
* @class Do.Prevent
* @constructor
* @param msg {String} (optional) Explanation of why the termination was done
*/
DO.Prevent = function(msg) {
this.msg = msg;
};
/**
* Return an Error object when you want to terminate the execution
* of all subsequent method calls.
* @class Do.Error
* @constructor
* @param msg {String} (optional) Explanation of the altered return value
* @param retVal {any} Return value passed to code that invoked the wrapped
* function.
* @deprecated use Y.Do.Halt or Y.Do.Prevent
*/
DO.Error = DO.Halt;
//////////////////////////////////////////////////////////////////////////
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
// var onsubscribeType = "_event:onsub",
var YArray = Y.Array,
AFTER = 'after',
CONFIGS = [
'broadcast',
'monitored',
'bubbles',
'context',
'contextFn',
'currentTarget',
'defaultFn',
'defaultTargetOnly',
'details',
'emitFacade',
'fireOnce',
'async',
'host',
'preventable',
'preventedFn',
'queuable',
'silent',
'stoppedFn',
'target',
'type'
],
CONFIGS_HASH = YArray.hash(CONFIGS),
nativeSlice = Array.prototype.slice,
YUI3_SIGNATURE = 9,
YUI_LOG = 'yui:log',
mixConfigs = function(r, s, ov) {
var p;
for (p in s) {
if (CONFIGS_HASH[p] && (ov || !(p in r))) {
r[p] = s[p];
}
}
return r;
};
/**
* The CustomEvent class lets you define events for your application
* that can be subscribed to by one or more independent component.
*
* @param {String} type The type of event, which is passed to the callback
* when the event fires.
* @param {object} defaults configuration object.
* @class CustomEvent
* @constructor
*/
/**
* The type of event, returned to subscribers when the event fires
* @property type
* @type string
*/
/**
* By default all custom events are logged in the debug build, set silent
* to true to disable debug outpu for this event.
* @property silent
* @type boolean
*/
Y.CustomEvent = function(type, defaults) {
this._kds = Y.CustomEvent.keepDeprecatedSubs;
this.id = Y.guid();
this.type = type;
this.silent = this.logSystem = (type === YUI_LOG);
if (this._kds) {
/**
* The subscribers to this event
* @property subscribers
* @type Subscriber {}
* @deprecated
*/
/**
* 'After' subscribers
* @property afters
* @type Subscriber {}
* @deprecated
*/
this.subscribers = {};
this.afters = {};
}
if (defaults) {
mixConfigs(this, defaults, true);
}
};
/**
* Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a>
* and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance.
*
* These properties were changed to private properties (`_subscribers` and `_afters`), and
* converted from objects to arrays for performance reasons.
*
* Setting this property to true will populate the deprecated `subscribers` and `afters`
* properties for people who may be using them (which is expected to be rare). There will
* be a performance hit, compared to the new array based implementation.
*
* If you are using these deprecated properties for a use case which the public API
* does not support, please file an enhancement request, and we can provide an alternate
* public implementation which doesn't have the performance cost required to maintiain the
* properties as objects.
*
* @property keepDeprecatedSubs
* @static
* @for CustomEvent
* @type boolean
* @default false
* @deprecated
*/
Y.CustomEvent.keepDeprecatedSubs = false;
Y.CustomEvent.mixConfigs = mixConfigs;
Y.CustomEvent.prototype = {
constructor: Y.CustomEvent,
/**
* Monitor when an event is attached or detached.
*
* @property monitored
* @type boolean
*/
/**
* If 0, this event does not broadcast. If 1, the YUI instance is notified
* every time this event fires. If 2, the YUI instance and the YUI global
* (if event is enabled on the global) are notified every time this event
* fires.
* @property broadcast
* @type int
*/
/**
* Specifies whether this event should be queued when the host is actively
* processing an event. This will effect exectution order of the callbacks
* for the various events.
* @property queuable
* @type boolean
* @default false
*/
/**
* This event has fired if true
*
* @property fired
* @type boolean
* @default false;
*/
/**
* An array containing the arguments the custom event
* was last fired with.
* @property firedWith
* @type Array
*/
/**
* This event should only fire one time if true, and if
* it has fired, any new subscribers should be notified
* immediately.
*
* @property fireOnce
* @type boolean
* @default false;
*/
/**
* fireOnce listeners will fire syncronously unless async
* is set to true
* @property async
* @type boolean
* @default false
*/
/**
* Flag for stopPropagation that is modified during fire()
* 1 means to stop propagation to bubble targets. 2 means
* to also stop additional subscribers on this target.
* @property stopped
* @type int
*/
/**
* Flag for preventDefault that is modified during fire().
* if it is not 0, the default behavior for this event
* @property prevented
* @type int
*/
/**
* Specifies the host for this custom event. This is used
* to enable event bubbling
* @property host
* @type EventTarget
*/
/**
* The default function to execute after event listeners
* have fire, but only if the default action was not
* prevented.
* @property defaultFn
* @type Function
*/
/**
* The function to execute if a subscriber calls
* stopPropagation or stopImmediatePropagation
* @property stoppedFn
* @type Function
*/
/**
* The function to execute if a subscriber calls
* preventDefault
* @property preventedFn
* @type Function
*/
/**
* The subscribers to this event
* @property _subscribers
* @type Subscriber []
* @private
*/
/**
* 'After' subscribers
* @property _afters
* @type Subscriber []
* @private
*/
/**
* If set to true, the custom event will deliver an EventFacade object
* that is similar to a DOM event object.
* @property emitFacade
* @type boolean
* @default false
*/
/**
* Supports multiple options for listener signatures in order to
* port YUI 2 apps.
* @property signature
* @type int
* @default 9
*/
signature : YUI3_SIGNATURE,
/**
* The context the the event will fire from by default. Defaults to the YUI
* instance.
* @property context
* @type object
*/
context : Y,
/**
* Specifies whether or not this event's default function
* can be cancelled by a subscriber by executing preventDefault()
* on the event facade
* @property preventable
* @type boolean
* @default true
*/
preventable : true,
/**
* Specifies whether or not a subscriber can stop the event propagation
* via stopPropagation(), stopImmediatePropagation(), or halt()
*
* Events can only bubble if emitFacade is true.
*
* @property bubbles
* @type boolean
* @default true
*/
bubbles : true,
/**
* Returns the number of subscribers for this event as the sum of the on()
* subscribers and after() subscribers.
*
* @method hasSubs
* @return Number
*/
hasSubs: function(when) {
var s = 0,
a = 0,
subs = this._subscribers,
afters = this._afters,
sib = this.sibling;
if (subs) {
s = subs.length;
}
if (afters) {
a = afters.length;
}
if (sib) {
subs = sib._subscribers;
afters = sib._afters;
if (subs) {
s += subs.length;
}
if (afters) {
a += afters.length;
}
}
if (when) {
return (when === 'after') ? a : s;
}
return (s + a);
},
/**
* Monitor the event state for the subscribed event. The first parameter
* is what should be monitored, the rest are the normal parameters when
* subscribing to an event.
* @method monitor
* @param what {string} what to monitor ('detach', 'attach', 'publish').
* @return {EventHandle} return value from the monitor event subscription.
*/
monitor: function(what) {
this.monitored = true;
var type = this.id + '|' + this.type + '_' + what,
args = nativeSlice.call(arguments, 0);
args[0] = type;
return this.host.on.apply(this.host, args);
},
/**
* Get all of the subscribers to this event and any sibling event
* @method getSubs
* @return {Array} first item is the on subscribers, second the after.
*/
getSubs: function() {
var sibling = this.sibling,
subs = this._subscribers,
afters = this._afters,
siblingSubs,
siblingAfters;
if (sibling) {
siblingSubs = sibling._subscribers;
siblingAfters = sibling._afters;
}
if (siblingSubs) {
if (subs) {
subs = subs.concat(siblingSubs);
} else {
subs = siblingSubs.concat();
}
} else {
if (subs) {
subs = subs.concat();
} else {
subs = [];
}
}
if (siblingAfters) {
if (afters) {
afters = afters.concat(siblingAfters);
} else {
afters = siblingAfters.concat();
}
} else {
if (afters) {
afters = afters.concat();
} else {
afters = [];
}
}
return [subs, afters];
},
/**
* Apply configuration properties. Only applies the CONFIG whitelist
* @method applyConfig
* @param o hash of properties to apply.
* @param force {boolean} if true, properties that exist on the event
* will be overwritten.
*/
applyConfig: function(o, force) {
mixConfigs(this, o, force);
},
/**
* Create the Subscription for subscribing function, context, and bound
* arguments. If this is a fireOnce event, the subscriber is immediately
* notified.
*
* @method _on
* @param fn {Function} Subscription callback
* @param [context] {Object} Override `this` in the callback
* @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire()
* @param [when] {String} "after" to slot into after subscribers
* @return {EventHandle}
* @protected
*/
_on: function(fn, context, args, when) {
if (!fn) { this.log('Invalid callback for CE: ' + this.type); }
var s = new Y.Subscriber(fn, context, args, when);
if (this.fireOnce && this.fired) {
if (this.async) {
setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0);
} else {
this._notify(s, this.firedWith);
}
}
if (when === AFTER) {
if (!this._afters) {
this._afters = [];
this._hasAfters = true;
}
this._afters.push(s);
} else {
if (!this._subscribers) {
this._subscribers = [];
this._hasSubs = true;
}
this._subscribers.push(s);
}
if (this._kds) {
if (when === AFTER) {
this.afters[s.id] = s;
} else {
this.subscribers[s.id] = s;
}
}
return new Y.EventHandle(this, s);
},
/**
* Listen for this event
* @method subscribe
* @param {Function} fn The function to execute.
* @return {EventHandle} Unsubscribe handle.
* @deprecated use on.
*/
subscribe: function(fn, context) {
Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated');
var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;
return this._on(fn, context, a, true);
},
/**
* Listen for this event
* @method on
* @param {Function} fn The function to execute.
* @param {object} context optional execution context.
* @param {mixed} arg* 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {EventHandle} An object with a detach method to detch the handler(s).
*/
on: function(fn, context) {
var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;
if (this.monitored && this.host) {
this.host._monitor('attach', this, {
args: arguments
});
}
return this._on(fn, context, a, true);
},
/**
* Listen for this event after the normal subscribers have been notified and
* the default behavior has been applied. If a normal subscriber prevents the
* default behavior, it also prevents after listeners from firing.
* @method after
* @param {Function} fn The function to execute.
* @param {object} context optional execution context.
* @param {mixed} arg* 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {EventHandle} handle Unsubscribe handle.
*/
after: function(fn, context) {
var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;
return this._on(fn, context, a, AFTER);
},
/**
* Detach listeners.
* @method detach
* @param {Function} fn The subscribed function to remove, if not supplied
* all will be removed.
* @param {Object} context The context object passed to subscribe.
* @return {int} returns the number of subscribers unsubscribed.
*/
detach: function(fn, context) {
// unsubscribe handle
if (fn && fn.detach) {
return fn.detach();
}
var i, s,
found = 0,
subs = this._subscribers,
afters = this._afters;
if (subs) {
for (i = subs.length; i >= 0; i--) {
s = subs[i];
if (s && (!fn || fn === s.fn)) {
this._delete(s, subs, i);
found++;
}
}
}
if (afters) {
for (i = afters.length; i >= 0; i--) {
s = afters[i];
if (s && (!fn || fn === s.fn)) {
this._delete(s, afters, i);
found++;
}
}
}
return found;
},
/**
* Detach listeners.
* @method unsubscribe
* @param {Function} fn The subscribed function to remove, if not supplied
* all will be removed.
* @param {Object} context The context object passed to subscribe.
* @return {int|undefined} returns the number of subscribers unsubscribed.
* @deprecated use detach.
*/
unsubscribe: function() {
return this.detach.apply(this, arguments);
},
/**
* Notify a single subscriber
* @method _notify
* @param {Subscriber} s the subscriber.
* @param {Array} args the arguments array to apply to the listener.
* @protected
*/
_notify: function(s, args, ef) {
this.log(this.type + '->' + 'sub: ' + s.id);
var ret;
ret = s.notify(args, this);
if (false === ret || this.stopped > 1) {
this.log(this.type + ' cancelled by subscriber');
return false;
}
return true;
},
/**
* Logger abstraction to centralize the application of the silent flag
* @method log
* @param {string} msg message to log.
* @param {string} cat log category.
*/
log: function(msg, cat) {
if (!this.silent) { Y.log(this.id + ': ' + msg, cat || 'info', 'event'); }
},
/**
* Notifies the subscribers. The callback functions will be executed
* from the context specified when the event was created, and with the
* following parameters:
* <ul>
* <li>The type of event</li>
* <li>All of the arguments fire() was executed with as an array</li>
* <li>The custom object (if any) that was passed into the subscribe()
* method</li>
* </ul>
* @method fire
* @param {Object*} arguments an arbitrary set of parameters to pass to
* the handler.
* @return {boolean} false if one of the subscribers returned false,
* true otherwise.
*
*/
fire: function() {
// push is the fastest way to go from arguments to arrays
// for most browsers currently
// http://jsperf.com/push-vs-concat-vs-slice/2
var args = [];
args.push.apply(args, arguments);
return this._fire(args);
},
/**
* Private internal implementation for `fire`, which is can be used directly by
* `EventTarget` and other event module classes which have already converted from
* an `arguments` list to an array, to avoid the repeated overhead.
*
* @method _fire
* @private
* @param {Array} args The array of arguments passed to be passed to handlers.
* @return {boolean} false if one of the subscribers returned false, true otherwise.
*/
_fire: function(args) {
if (this.fireOnce && this.fired) {
this.log('fireOnce event: ' + this.type + ' already fired');
return true;
} else {
// this doesn't happen if the event isn't published
// this.host._monitor('fire', this.type, args);
this.fired = true;
if (this.fireOnce) {
this.firedWith = args;
}
if (this.emitFacade) {
return this.fireComplex(args);
} else {
return this.fireSimple(args);
}
}
},
/**
* Set up for notifying subscribers of non-emitFacade events.
*
* @method fireSimple
* @param args {Array} Arguments passed to fire()
* @return Boolean false if a subscriber returned false
* @protected
*/
fireSimple: function(args) {
this.stopped = 0;
this.prevented = 0;
if (this.hasSubs()) {
var subs = this.getSubs();
this._procSubs(subs[0], args);
this._procSubs(subs[1], args);
}
if (this.broadcast) {
this._broadcast(args);
}
return this.stopped ? false : true;
},
// Requires the event-custom-complex module for full funcitonality.
fireComplex: function(args) {
this.log('Missing event-custom-complex needed to emit a facade for: ' + this.type);
args[0] = args[0] || {};
return this.fireSimple(args);
},
/**
* Notifies a list of subscribers.
*
* @method _procSubs
* @param subs {Array} List of subscribers
* @param args {Array} Arguments passed to fire()
* @param ef {}
* @return Boolean false if a subscriber returns false or stops the event
* propagation via e.stopPropagation(),
* e.stopImmediatePropagation(), or e.halt()
* @private
*/
_procSubs: function(subs, args, ef) {
var s, i, l;
for (i = 0, l = subs.length; i < l; i++) {
s = subs[i];
if (s && s.fn) {
if (false === this._notify(s, args, ef)) {
this.stopped = 2;
}
if (this.stopped === 2) {
return false;
}
}
}
return true;
},
/**
* Notifies the YUI instance if the event is configured with broadcast = 1,
* and both the YUI instance and Y.Global if configured with broadcast = 2.
*
* @method _broadcast
* @param args {Array} Arguments sent to fire()
* @private
*/
_broadcast: function(args) {
if (!this.stopped && this.broadcast) {
var a = args.concat();
a.unshift(this.type);
if (this.host !== Y) {
Y.fire.apply(Y, a);
}
if (this.broadcast === 2) {
Y.Global.fire.apply(Y.Global, a);
}
}
},
/**
* Removes all listeners
* @method unsubscribeAll
* @return {int} The number of listeners unsubscribed.
* @deprecated use detachAll.
*/
unsubscribeAll: function() {
return this.detachAll.apply(this, arguments);
},
/**
* Removes all listeners
* @method detachAll
* @return {int} The number of listeners unsubscribed.
*/
detachAll: function() {
return this.detach();
},
/**
* Deletes the subscriber from the internal store of on() and after()
* subscribers.
*
* @method _delete
* @param s subscriber object.
* @param subs (optional) on or after subscriber array
* @param index (optional) The index found.
* @private
*/
_delete: function(s, subs, i) {
var when = s._when;
if (!subs) {
subs = (when === AFTER) ? this._afters : this._subscribers;
}
if (subs) {
i = YArray.indexOf(subs, s, 0);
if (s && subs[i] === s) {
subs.splice(i, 1);
if (subs.length === 0) {
if (when === AFTER) {
this._hasAfters = false;
} else {
this._hasSubs = false;
}
}
}
}
if (this._kds) {
if (when === AFTER) {
delete this.afters[s.id];
} else {
delete this.subscribers[s.id];
}
}
if (this.monitored && this.host) {
this.host._monitor('detach', this, {
ce: this,
sub: s
});
}
if (s) {
s.deleted = true;
}
}
};
/**
* Stores the subscriber information to be used when the event fires.
* @param {Function} fn The wrapped function to execute.
* @param {Object} context The value of the keyword 'this' in the listener.
* @param {Array} args* 0..n additional arguments to supply the listener.
*
* @class Subscriber
* @constructor
*/
Y.Subscriber = function(fn, context, args, when) {
/**
* The callback that will be execute when the event fires
* This is wrapped by Y.rbind if obj was supplied.
* @property fn
* @type Function
*/
this.fn = fn;
/**
* Optional 'this' keyword for the listener
* @property context
* @type Object
*/
this.context = context;
/**
* Unique subscriber id
* @property id
* @type String
*/
this.id = Y.guid();
/**
* Additional arguments to propagate to the subscriber
* @property args
* @type Array
*/
this.args = args;
this._when = when;
/**
* Custom events for a given fire transaction.
* @property events
* @type {EventTarget}
*/
// this.events = null;
/**
* This listener only reacts to the event once
* @property once
*/
// this.once = false;
};
Y.Subscriber.prototype = {
constructor: Y.Subscriber,
_notify: function(c, args, ce) {
if (this.deleted && !this.postponed) {
if (this.postponed) {
delete this.fn;
delete this.context;
} else {
delete this.postponed;
return null;
}
}
var a = this.args, ret;
switch (ce.signature) {
case 0:
ret = this.fn.call(c, ce.type, args, c);
break;
case 1:
ret = this.fn.call(c, args[0] || null, c);
break;
default:
if (a || args) {
args = args || [];
a = (a) ? args.concat(a) : args;
ret = this.fn.apply(c, a);
} else {
ret = this.fn.call(c);
}
}
if (this.once) {
ce._delete(this);
}
return ret;
},
/**
* Executes the subscriber.
* @method notify
* @param args {Array} Arguments array for the subscriber.
* @param ce {CustomEvent} The custom event that sent the notification.
*/
notify: function(args, ce) {
var c = this.context,
ret = true;
if (!c) {
c = (ce.contextFn) ? ce.contextFn() : ce.context;
}
// only catch errors if we will not re-throw them.
if (Y.config && Y.config.throwFail) {
ret = this._notify(c, args, ce);
} else {
try {
ret = this._notify(c, args, ce);
} catch (e) {
Y.error(this + ' failed: ' + e.message, e);
}
}
return ret;
},
/**
* Returns true if the fn and obj match this objects properties.
* Used by the unsubscribe method to match the right subscriber.
*
* @method contains
* @param {Function} fn the function to execute.
* @param {Object} context optional 'this' keyword for the listener.
* @return {boolean} true if the supplied arguments match this
* subscriber's signature.
*/
contains: function(fn, context) {
if (context) {
return ((this.fn === fn) && this.context === context);
} else {
return (this.fn === fn);
}
},
valueOf : function() {
return this.id;
}
};
/**
* Return value from all subscribe operations
* @class EventHandle
* @constructor
* @param {CustomEvent} evt the custom event.
* @param {Subscriber} sub the subscriber.
*/
Y.EventHandle = function(evt, sub) {
/**
* The custom event
*
* @property evt
* @type CustomEvent
*/
this.evt = evt;
/**
* The subscriber object
*
* @property sub
* @type Subscriber
*/
this.sub = sub;
};
Y.EventHandle.prototype = {
batch: function(f, c) {
f.call(c || this, this);
if (Y.Lang.isArray(this.evt)) {
Y.Array.each(this.evt, function(h) {
h.batch.call(c || h, f);
});
}
},
/**
* Detaches this subscriber
* @method detach
* @return {int} the number of detached listeners
*/
detach: function() {
var evt = this.evt, detached = 0, i;
if (evt) {
// Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event');
if (Y.Lang.isArray(evt)) {
for (i = 0; i < evt.length; i++) {
detached += evt[i].detach();
}
} else {
evt._delete(this.sub);
detached = 1;
}
}
return detached;
},
/**
* Monitor the event state for the subscribed event. The first parameter
* is what should be monitored, the rest are the normal parameters when
* subscribing to an event.
* @method monitor
* @param what {string} what to monitor ('attach', 'detach', 'publish').
* @return {EventHandle} return value from the monitor event subscription.
*/
monitor: function(what) {
return this.evt.monitor.apply(this.evt, arguments);
}
};
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
/**
* EventTarget provides the implementation for any object to
* publish, subscribe and fire to custom events, and also
* alows other EventTargets to target the object with events
* sourced from the other object.
* EventTarget is designed to be used with Y.augment to wrap
* EventCustom in an interface that allows events to be listened to
* and fired by name. This makes it possible for implementing code to
* subscribe to an event that either has not been created yet, or will
* not be created at all.
* @class EventTarget
* @param opts a configuration object
* @config emitFacade {boolean} if true, all events will emit event
* facade payloads by default (default false)
* @config prefix {String} the prefix to apply to non-prefixed event names
*/
var L = Y.Lang,
PREFIX_DELIMITER = ':',
CATEGORY_DELIMITER = '|',
AFTER_PREFIX = '~AFTER~',
WILD_TYPE_RE = /(.*?)(:)(.*?)/,
_wildType = Y.cached(function(type) {
return type.replace(WILD_TYPE_RE, "*$2$3");
}),
/**
* If the instance has a prefix attribute and the
* event type is not prefixed, the instance prefix is
* applied to the supplied type.
* @method _getType
* @private
*/
_getType = function(type, pre) {
if (!pre || type.indexOf(PREFIX_DELIMITER) > -1) {
return type;
}
return pre + PREFIX_DELIMITER + type;
},
/**
* Returns an array with the detach key (if provided),
* and the prefixed event name from _getType
* Y.on('detachcategory| menu:click', fn)
* @method _parseType
* @private
*/
_parseType = Y.cached(function(type, pre) {
var t = type, detachcategory, after, i;
if (!L.isString(t)) {
return t;
}
i = t.indexOf(AFTER_PREFIX);
if (i > -1) {
after = true;
t = t.substr(AFTER_PREFIX.length);
}
i = t.indexOf(CATEGORY_DELIMITER);
if (i > -1) {
detachcategory = t.substr(0, (i));
t = t.substr(i+1);
if (t === '*') {
t = null;
}
}
// detach category, full type with instance prefix, is this an after listener, short type
return [detachcategory, (pre) ? _getType(t, pre) : t, after, t];
}),
ET = function(opts) {
var etState = this._yuievt,
etConfig;
if (!etState) {
etState = this._yuievt = {
events: {}, // PERF: Not much point instantiating lazily. We're bound to have events
targets: null, // PERF: Instantiate lazily, if user actually adds target,
config: {
host: this,
context: this
},
chain: Y.config.chain
};
}
etConfig = etState.config;
if (opts) {
mixConfigs(etConfig, opts, true);
if (opts.chain !== undefined) {
etState.chain = opts.chain;
}
if (opts.prefix) {
etConfig.prefix = opts.prefix;
}
}
};
ET.prototype = {
constructor: ET,
/**
* Listen to a custom event hosted by this object one time.
* This is the equivalent to <code>on</code> except the
* listener is immediatelly detached when it is executed.
* @method once
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching the
* subscription
*/
once: function() {
var handle = this.on.apply(this, arguments);
handle.batch(function(hand) {
if (hand.sub) {
hand.sub.once = true;
}
});
return handle;
},
/**
* Listen to a custom event hosted by this object one time.
* This is the equivalent to <code>after</code> except the
* listener is immediatelly detached when it is executed.
* @method onceAfter
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
*/
onceAfter: function() {
var handle = this.after.apply(this, arguments);
handle.batch(function(hand) {
if (hand.sub) {
hand.sub.once = true;
}
});
return handle;
},
/**
* Takes the type parameter passed to 'on' and parses out the
* various pieces that could be included in the type. If the
* event type is passed without a prefix, it will be expanded
* to include the prefix one is supplied or the event target
* is configured with a default prefix.
* @method parseType
* @param {String} type the type
* @param {String} [pre=this._yuievt.config.prefix] the prefix
* @since 3.3.0
* @return {Array} an array containing:
* * the detach category, if supplied,
* * the prefixed event type,
* * whether or not this is an after listener,
* * the supplied event type
*/
parseType: function(type, pre) {
return _parseType(type, pre || this._yuievt.config.prefix);
},
/**
* Subscribe a callback function to a custom event fired by this object or
* from an object that bubbles its events to this object.
*
* Callback functions for events published with `emitFacade = true` will
* receive an `EventFacade` as the first argument (typically named "e").
* These callbacks can then call `e.preventDefault()` to disable the
* behavior published to that event's `defaultFn`. See the `EventFacade`
* API for all available properties and methods. Subscribers to
* non-`emitFacade` events will receive the arguments passed to `fire()`
* after the event name.
*
* To subscribe to multiple events at once, pass an object as the first
* argument, where the key:value pairs correspond to the eventName:callback,
* or pass an array of event names as the first argument to subscribe to
* all listed events with the same callback.
*
* Returning `false` from a callback is supported as an alternative to
* calling `e.preventDefault(); e.stopPropagation();`. However, it is
* recommended to use the event methods whenever possible.
*
* @method on
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
*/
on: function(type, fn, context) {
var yuievt = this._yuievt,
parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce,
detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype,
Node = Y.Node, n, domevent, isArr;
// full name, args, detachcategory, after
this._monitor('attach', parts[1], {
args: arguments,
category: parts[0],
after: parts[2]
});
if (L.isObject(type)) {
if (L.isFunction(type)) {
return Y.Do.before.apply(Y.Do, arguments);
}
f = fn;
c = context;
args = nativeSlice.call(arguments, 0);
ret = [];
if (L.isArray(type)) {
isArr = true;
}
after = type._after;
delete type._after;
Y.each(type, function(v, k) {
if (L.isObject(v)) {
f = v.fn || ((L.isFunction(v)) ? v : f);
c = v.context || c;
}
var nv = (after) ? AFTER_PREFIX : '';
args[0] = nv + ((isArr) ? v : k);
args[1] = f;
args[2] = c;
ret.push(this.on.apply(this, args));
}, this);
return (yuievt.chain) ? this : new Y.EventHandle(ret);
}
detachcategory = parts[0];
after = parts[2];
shorttype = parts[3];
// extra redirection so we catch adaptor events too. take a look at this.
if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) {
args = nativeSlice.call(arguments, 0);
args.splice(2, 0, Node.getDOMNode(this));
// Y.log("Node detected, redirecting with these args: " + args);
return Y.on.apply(Y, args);
}
type = parts[1];
if (Y.instanceOf(this, YUI)) {
adapt = Y.Env.evt.plugins[type];
args = nativeSlice.call(arguments, 0);
args[0] = shorttype;
if (Node) {
n = args[2];
if (Y.instanceOf(n, Y.NodeList)) {
n = Y.NodeList.getDOMNodes(n);
} else if (Y.instanceOf(n, Node)) {
n = Node.getDOMNode(n);
}
domevent = (shorttype in Node.DOM_EVENTS);
// Captures both DOM events and event plugins.
if (domevent) {
args[2] = n;
}
}
// check for the existance of an event adaptor
if (adapt) {
Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event');
handle = adapt.on.apply(Y, args);
} else if ((!type) || domevent) {
handle = Y.Event._attach(args);
}
}
if (!handle) {
ce = yuievt.events[type] || this.publish(type);
handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true);
// TODO: More robust regex, accounting for category
if (type.indexOf("*:") !== -1) {
this._hasSiblings = true;
}
}
if (detachcategory) {
store[detachcategory] = store[detachcategory] || {};
store[detachcategory][type] = store[detachcategory][type] || [];
store[detachcategory][type].push(handle);
}
return (yuievt.chain) ? this : handle;
},
/**
* subscribe to an event
* @method subscribe
* @deprecated use on
*/
subscribe: function() {
Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated');
return this.on.apply(this, arguments);
},
/**
* Detach one or more listeners the from the specified event
* @method detach
* @param type {string|Object} Either the handle to the subscriber or the
* type of event. If the type
* is not specified, it will attempt to remove
* the listener from all hosted events.
* @param fn {Function} The subscribed function to unsubscribe, if not
* supplied, all subscribers will be removed.
* @param context {Object} The custom object passed to subscribe. This is
* optional, but if supplied will be used to
* disambiguate multiple listeners that are the same
* (e.g., you subscribe many object using a function
* that lives on the prototype)
* @return {EventTarget} the host
*/
detach: function(type, fn, context) {
var evts = this._yuievt.events,
i,
Node = Y.Node,
isNode = Node && (Y.instanceOf(this, Node));
// detachAll disabled on the Y instance.
if (!type && (this !== Y)) {
for (i in evts) {
if (evts.hasOwnProperty(i)) {
evts[i].detach(fn, context);
}
}
if (isNode) {
Y.Event.purgeElement(Node.getDOMNode(this));
}
return this;
}
var parts = _parseType(type, this._yuievt.config.prefix),
detachcategory = L.isArray(parts) ? parts[0] : null,
shorttype = (parts) ? parts[3] : null,
adapt, store = Y.Env.evt.handles, detachhost, cat, args,
ce,
keyDetacher = function(lcat, ltype, host) {
var handles = lcat[ltype], ce, i;
if (handles) {
for (i = handles.length - 1; i >= 0; --i) {
ce = handles[i].evt;
if (ce.host === host || ce.el === host) {
handles[i].detach();
}
}
}
};
if (detachcategory) {
cat = store[detachcategory];
type = parts[1];
detachhost = (isNode) ? Y.Node.getDOMNode(this) : this;
if (cat) {
if (type) {
keyDetacher(cat, type, detachhost);
} else {
for (i in cat) {
if (cat.hasOwnProperty(i)) {
keyDetacher(cat, i, detachhost);
}
}
}
return this;
}
// If this is an event handle, use it to detach
} else if (L.isObject(type) && type.detach) {
type.detach();
return this;
// extra redirection so we catch adaptor events too. take a look at this.
} else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) {
args = nativeSlice.call(arguments, 0);
args[2] = Node.getDOMNode(this);
Y.detach.apply(Y, args);
return this;
}
adapt = Y.Env.evt.plugins[shorttype];
// The YUI instance handles DOM events and adaptors
if (Y.instanceOf(this, YUI)) {
args = nativeSlice.call(arguments, 0);
// use the adaptor specific detach code if
if (adapt && adapt.detach) {
adapt.detach.apply(Y, args);
return this;
// DOM event fork
} else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) {
args[0] = type;
Y.Event.detach.apply(Y.Event, args);
return this;
}
}
// ce = evts[type];
ce = evts[parts[1]];
if (ce) {
ce.detach(fn, context);
}
return this;
},
/**
* detach a listener
* @method unsubscribe
* @deprecated use detach
*/
unsubscribe: function() {
Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated');
return this.detach.apply(this, arguments);
},
/**
* Removes all listeners from the specified event. If the event type
* is not specified, all listeners from all hosted custom events will
* be removed.
* @method detachAll
* @param type {String} The type, or name of the event
*/
detachAll: function(type) {
return this.detach(type);
},
/**
* Removes all listeners from the specified event. If the event type
* is not specified, all listeners from all hosted custom events will
* be removed.
* @method unsubscribeAll
* @param type {String} The type, or name of the event
* @deprecated use detachAll
*/
unsubscribeAll: function() {
Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated');
return this.detachAll.apply(this, arguments);
},
/**
* Creates a new custom event of the specified type. If a custom event
* by that name already exists, it will not be re-created. In either
* case the custom event is returned.
*
* @method publish
*
* @param type {String} the type, or name of the event
* @param opts {object} optional config params. Valid properties are:
*
* <ul>
* <li>
* 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false)
* </li>
* <li>
* 'bubbles': whether or not this event bubbles (true)
* Events can only bubble if emitFacade is true.
* </li>
* <li>
* 'context': the default execution context for the listeners (this)
* </li>
* <li>
* 'defaultFn': the default function to execute when this event fires if preventDefault was not called
* </li>
* <li>
* 'emitFacade': whether or not this event emits a facade (false)
* </li>
* <li>
* 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click'
* </li>
* <li>
* 'fireOnce': if an event is configured to fire once, new subscribers after
* the fire will be notified immediately.
* </li>
* <li>
* 'async': fireOnce event listeners will fire synchronously if the event has already
* fired unless async is true.
* </li>
* <li>
* 'preventable': whether or not preventDefault() has an effect (true)
* </li>
* <li>
* 'preventedFn': a function that is executed when preventDefault is called
* </li>
* <li>
* 'queuable': whether or not this event can be queued during bubbling (false)
* </li>
* <li>
* 'silent': if silent is true, debug messages are not provided for this event.
* </li>
* <li>
* 'stoppedFn': a function that is executed when stopPropagation is called
* </li>
*
* <li>
* 'monitored': specifies whether or not this event should send notifications about
* when the event has been attached, detached, or published.
* </li>
* <li>
* 'type': the event type (valid option if not provided as the first parameter to publish)
* </li>
* </ul>
*
* @return {CustomEvent} the custom event
*
*/
publish: function(type, opts) {
var ret,
etState = this._yuievt,
etConfig = etState.config,
pre = etConfig.prefix;
if (typeof type === "string") {
if (pre) {
type = _getType(type, pre);
}
ret = this._publish(type, etConfig, opts);
} else {
ret = {};
Y.each(type, function(v, k) {
if (pre) {
k = _getType(k, pre);
}
ret[k] = this._publish(k, etConfig, v || opts);
}, this);
}
return ret;
},
/**
* Returns the fully qualified type, given a short type string.
* That is, returns "foo:bar" when given "bar" if "foo" is the configured prefix.
*
* NOTE: This method, unlike _getType, does no checking of the value passed in, and
* is designed to be used with the low level _publish() method, for critical path
* implementations which need to fast-track publish for performance reasons.
*
* @method _getFullType
* @private
* @param {String} type The short type to prefix
* @return {String} The prefixed type, if a prefix is set, otherwise the type passed in
*/
_getFullType : function(type) {
var pre = this._yuievt.config.prefix;
if (pre) {
return pre + PREFIX_DELIMITER + type;
} else {
return type;
}
},
/**
* The low level event publish implementation. It expects all the massaging to have been done
* outside of this method. e.g. the `type` to `fullType` conversion. It's designed to be a fast
* path publish, which can be used by critical code paths to improve performance.
*
* @method _publish
* @private
* @param {String} fullType The prefixed type of the event to publish.
* @param {Object} etOpts The EventTarget specific configuration to mix into the published event.
* @param {Object} ceOpts The publish specific configuration to mix into the published event.
* @return {CustomEvent} The published event. If called without `etOpts` or `ceOpts`, this will
* be the default `CustomEvent` instance, and can be configured independently.
*/
_publish : function(fullType, etOpts, ceOpts) {
var ce,
etState = this._yuievt,
etConfig = etState.config,
host = etConfig.host,
context = etConfig.context,
events = etState.events;
ce = events[fullType];
// PERF: Hate to pull the check out of monitor, but trying to keep critical path tight.
if ((etConfig.monitored && !ce) || (ce && ce.monitored)) {
this._monitor('publish', fullType, {
args: arguments
});
}
if (!ce) {
// Publish event
ce = events[fullType] = new Y.CustomEvent(fullType, etOpts);
if (!etOpts) {
ce.host = host;
ce.context = context;
}
}
if (ceOpts) {
mixConfigs(ce, ceOpts, true);
}
return ce;
},
/**
* This is the entry point for the event monitoring system.
* You can monitor 'attach', 'detach', 'fire', and 'publish'.
* When configured, these events generate an event. click ->
* click_attach, click_detach, click_publish -- these can
* be subscribed to like other events to monitor the event
* system. Inividual published events can have monitoring
* turned on or off (publish can't be turned off before it
* it published) by setting the events 'monitor' config.
*
* @method _monitor
* @param what {String} 'attach', 'detach', 'fire', or 'publish'
* @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object.
* @param o {Object} Information about the event interaction, such as
* fire() args, subscription category, publish config
* @private
*/
_monitor: function(what, eventType, o) {
var monitorevt, ce, type;
if (eventType) {
if (typeof eventType === "string") {
type = eventType;
ce = this.getEvent(eventType, true);
} else {
ce = eventType;
type = eventType.type;
}
if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) {
monitorevt = type + '_' + what;
o.monitored = what;
this.fire.call(this, monitorevt, o);
}
}
},
/**
* Fire a custom event by name. The callback functions will be executed
* from the context specified when the event was created, and with the
* following parameters.
*
* If the custom event object hasn't been created, then the event hasn't
* been published and it has no subscribers. For performance sake, we
* immediate exit in this case. This means the event won't bubble, so
* if the intention is that a bubble target be notified, the event must
* be published on this object first.
*
* The first argument is the event type, and any additional arguments are
* passed to the listeners as parameters. If the first of these is an
* object literal, and the event is configured to emit an event facade,
* that object is mixed into the event facade and the facade is provided
* in place of the original object.
*
* @method fire
* @param type {String|Object} The type of the event, or an object that contains
* a 'type' property.
* @param arguments {Object*} an arbitrary set of parameters to pass to
* the handler. If the first of these is an object literal and the event is
* configured to emit an event facade, the event facade will replace that
* parameter after the properties the object literal contains are copied to
* the event facade.
* @return {EventTarget} the event host
*/
fire: function(type) {
var typeIncluded = (typeof type === "string"),
argCount = arguments.length,
t = type,
yuievt = this._yuievt,
etConfig = yuievt.config,
pre = etConfig.prefix,
ret,
ce,
ce2,
args;
if (typeIncluded && argCount <= 3) {
// PERF: Try to avoid slice/iteration for the common signatures
// Most common
if (argCount === 2) {
args = [arguments[1]]; // fire("foo", {})
} else if (argCount === 3) {
args = [arguments[1], arguments[2]]; // fire("foo", {}, opts)
} else {
args = []; // fire("foo")
}
} else {
args = nativeSlice.call(arguments, ((typeIncluded) ? 1 : 0));
}
if (!typeIncluded) {
t = (type && type.type);
}
if (pre) {
t = _getType(t, pre);
}
ce = yuievt.events[t];
if (this._hasSiblings) {
ce2 = this.getSibling(t, ce);
if (ce2 && !ce) {
ce = this.publish(t);
}
}
// PERF: trying to avoid function call, since this is a critical path
if ((etConfig.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) {
this._monitor('fire', (ce || t), {
args: args
});
}
// this event has not been published or subscribed to
if (!ce) {
if (yuievt.hasTargets) {
return this.bubble({ type: t }, args, this);
}
// otherwise there is nothing to be done
ret = true;
} else {
if (ce2) {
ce.sibling = ce2;
}
ret = ce._fire(args);
}
return (yuievt.chain) ? this : ret;
},
getSibling: function(type, ce) {
var ce2;
// delegate to *:type events if there are subscribers
if (type.indexOf(PREFIX_DELIMITER) > -1) {
type = _wildType(type);
ce2 = this.getEvent(type, true);
if (ce2) {
ce2.applyConfig(ce);
ce2.bubbles = false;
ce2.broadcast = 0;
}
}
return ce2;
},
/**
* Returns the custom event of the provided type has been created, a
* falsy value otherwise
* @method getEvent
* @param type {String} the type, or name of the event
* @param prefixed {String} if true, the type is prefixed already
* @return {CustomEvent} the custom event or null
*/
getEvent: function(type, prefixed) {
var pre, e;
if (!prefixed) {
pre = this._yuievt.config.prefix;
type = (pre) ? _getType(type, pre) : type;
}
e = this._yuievt.events;
return e[type] || null;
},
/**
* Subscribe to a custom event hosted by this object. The
* supplied callback will execute after any listeners add
* via the subscribe method, and after the default function,
* if configured for the event, has executed.
*
* @method after
* @param {String} type The name of the event
* @param {Function} fn The callback to execute in response to the event
* @param {Object} [context] Override `this` object in callback
* @param {Any} [arg*] 0..n additional arguments to supply to the subscriber
* @return {EventHandle} A subscription handle capable of detaching the
* subscription
*/
after: function(type, fn) {
var a = nativeSlice.call(arguments, 0);
switch (L.type(type)) {
case 'function':
return Y.Do.after.apply(Y.Do, arguments);
case 'array':
// YArray.each(a[0], function(v) {
// v = AFTER_PREFIX + v;
// });
// break;
case 'object':
a[0]._after = true;
break;
default:
a[0] = AFTER_PREFIX + type;
}
return this.on.apply(this, a);
},
/**
* Executes the callback before a DOM event, custom event
* or method. If the first argument is a function, it
* is assumed the target is a method. For DOM and custom
* events, this is an alias for Y.on.
*
* For DOM and custom events:
* type, callback, context, 0-n arguments
*
* For methods:
* callback, object (method host), methodName, context, 0-n arguments
*
* @method before
* @return detach handle
*/
before: function() {
return this.on.apply(this, arguments);
}
};
Y.EventTarget = ET;
// make Y an event target
Y.mix(Y, ET.prototype);
ET.call(Y, { bubbles: false });
YUI.Env.globalEvents = YUI.Env.globalEvents || new ET();
/**
* Hosts YUI page level events. This is where events bubble to
* when the broadcast config is set to 2. This property is
* only available if the custom event module is loaded.
* @property Global
* @type EventTarget
* @for YUI
*/
Y.Global = YUI.Env.globalEvents;
// @TODO implement a global namespace function on Y.Global?
/**
`Y.on()` can do many things:
<ul>
<li>Subscribe to custom events `publish`ed and `fire`d from Y</li>
<li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and
`fire`d from any object in the YUI instance sandbox</li>
<li>Subscribe to DOM events</li>
<li>Subscribe to the execution of a method on any object, effectively
treating that method as an event</li>
</ul>
For custom event subscriptions, pass the custom event name as the first argument
and callback as the second. The `this` object in the callback will be `Y` unless
an override is passed as the third argument.
Y.on('io:complete', function () {
Y.MyApp.updateStatus('Transaction complete');
});
To subscribe to DOM events, pass the name of a DOM event as the first argument
and a CSS selector string as the third argument after the callback function.
Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`,
array, or simply omitted (the default is the `window` object).
Y.on('click', function (e) {
e.preventDefault();
// proceed with ajax form submission
var url = this.get('action');
...
}, '#my-form');
The `this` object in DOM event callbacks will be the `Node` targeted by the CSS
selector or other identifier.
`on()` subscribers for DOM events or custom events `publish`ed with a
`defaultFn` can prevent the default behavior with `e.preventDefault()` from the
event object passed as the first parameter to the subscription callback.
To subscribe to the execution of an object method, pass arguments corresponding to the call signature for
<a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>.
NOTE: The formal parameter list below is for events, not for function
injection. See `Y.Do.before` for that signature.
@method on
@param {String} type DOM or custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@see Do.before
@for YUI
**/
/**
Listen for an event one time. Equivalent to `on()`, except that
the listener is immediately detached when executed.
See the <a href="#methods_on">`on()` method</a> for additional subscription
options.
@see on
@method once
@param {String} type DOM or custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@for YUI
**/
/**
Listen for an event one time. Equivalent to `once()`, except, like `after()`,
the subscription callback executes after all `on()` subscribers and the event's
`defaultFn` (if configured) have executed. Like `after()` if any `on()` phase
subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()`
subscribers will execute.
The listener is immediately detached when executed.
See the <a href="#methods_on">`on()` method</a> for additional subscription
options.
@see once
@method onceAfter
@param {String} type The custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@for YUI
**/
/**
Like `on()`, this method creates a subscription to a custom event or to the
execution of a method on an object.
For events, `after()` subscribers are executed after the event's
`defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber.
See the <a href="#methods_on">`on()` method</a> for additional subscription
options.
NOTE: The subscription signature shown is for events, not for function
injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a>
for that signature.
@see on
@see Do.after
@method after
@param {String} type The custom event name
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [args*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching the
subscription
@for YUI
**/
}, '@VERSION@', {"requires": ["oop"]});
YUI.add('event-custom-complex', function (Y, NAME) {
/**
* Adds event facades, preventable default behavior, and bubbling.
* events.
* @module event-custom
* @submodule event-custom-complex
*/
var FACADE,
FACADE_KEYS,
YObject = Y.Object,
key,
EMPTY = {},
CEProto = Y.CustomEvent.prototype,
ETProto = Y.EventTarget.prototype,
mixFacadeProps = function(facade, payload) {
var p;
for (p in payload) {
if (!(FACADE_KEYS.hasOwnProperty(p))) {
facade[p] = payload[p];
}
}
};
/**
* Wraps and protects a custom event for use when emitFacade is set to true.
* Requires the event-custom-complex module
* @class EventFacade
* @param e {Event} the custom event
* @param currentTarget {HTMLElement} the element the listener was attached to
*/
Y.EventFacade = function(e, currentTarget) {
if (!e) {
e = EMPTY;
}
this._event = e;
/**
* The arguments passed to fire
* @property details
* @type Array
*/
this.details = e.details;
/**
* The event type, this can be overridden by the fire() payload
* @property type
* @type string
*/
this.type = e.type;
/**
* The real event type
* @property _type
* @type string
* @private
*/
this._type = e.type;
//////////////////////////////////////////////////////
/**
* Node reference for the targeted eventtarget
* @property target
* @type Node
*/
this.target = e.target;
/**
* Node reference for the element that the listener was attached to.
* @property currentTarget
* @type Node
*/
this.currentTarget = currentTarget;
/**
* Node reference to the relatedTarget
* @property relatedTarget
* @type Node
*/
this.relatedTarget = e.relatedTarget;
};
Y.mix(Y.EventFacade.prototype, {
/**
* Stops the propagation to the next bubble target
* @method stopPropagation
*/
stopPropagation: function() {
this._event.stopPropagation();
this.stopped = 1;
},
/**
* Stops the propagation to the next bubble target and
* prevents any additional listeners from being exectued
* on the current target.
* @method stopImmediatePropagation
*/
stopImmediatePropagation: function() {
this._event.stopImmediatePropagation();
this.stopped = 2;
},
/**
* Prevents the event's default behavior
* @method preventDefault
*/
preventDefault: function() {
this._event.preventDefault();
this.prevented = 1;
},
/**
* Stops the event propagation and prevents the default
* event behavior.
* @method halt
* @param immediate {boolean} if true additional listeners
* on the current target will not be executed
*/
halt: function(immediate) {
this._event.halt(immediate);
this.prevented = 1;
this.stopped = (immediate) ? 2 : 1;
}
});
CEProto.fireComplex = function(args) {
var es,
ef,
q,
queue,
ce,
ret = true,
events,
subs,
ons,
afters,
afterQueue,
postponed,
prevented,
preventedFn,
defaultFn,
self = this,
host = self.host || self,
next,
oldbubble,
stack,
yuievt = host._yuievt,
hasPotentialSubscribers;
stack = self.stack;
if (stack) {
// queue this event if the current item in the queue bubbles
if (self.queuable && self.type !== stack.next.type) {
self.log('queue ' + self.type);
if (!stack.queue) {
stack.queue = [];
}
stack.queue.push([self, args]);
return true;
}
}
hasPotentialSubscribers = self.hasSubs() || yuievt.hasTargets || self.broadcast;
self.target = self.target || host;
self.currentTarget = host;
self.details = args.concat();
if (hasPotentialSubscribers) {
es = stack || {
id: self.id, // id of the first event in the stack
next: self,
silent: self.silent,
stopped: 0,
prevented: 0,
bubbling: null,
type: self.type,
// defaultFnQueue: new Y.Queue(),
defaultTargetOnly: self.defaultTargetOnly
};
subs = self.getSubs();
ons = subs[0];
afters = subs[1];
self.stopped = (self.type !== es.type) ? 0 : es.stopped;
self.prevented = (self.type !== es.type) ? 0 : es.prevented;
if (self.stoppedFn) {
// PERF TODO: Can we replace with callback, like preventedFn. Look into history
events = new Y.EventTarget({
fireOnce: true,
context: host
});
self.events = events;
events.on('stopped', self.stoppedFn);
}
// self.log("Firing " + self + ", " + "args: " + args);
self.log("Firing " + self.type);
self._facade = null; // kill facade to eliminate stale properties
ef = self._getFacade(args);
if (ons) {
self._procSubs(ons, args, ef);
}
// bubble if this is hosted in an event target and propagation has not been stopped
if (self.bubbles && host.bubble && !self.stopped) {
oldbubble = es.bubbling;
es.bubbling = self.type;
if (es.type !== self.type) {
es.stopped = 0;
es.prevented = 0;
}
ret = host.bubble(self, args, null, es);
self.stopped = Math.max(self.stopped, es.stopped);
self.prevented = Math.max(self.prevented, es.prevented);
es.bubbling = oldbubble;
}
prevented = self.prevented;
if (prevented) {
preventedFn = self.preventedFn;
if (preventedFn) {
preventedFn.apply(host, args);
}
} else {
defaultFn = self.defaultFn;
if (defaultFn && ((!self.defaultTargetOnly && !es.defaultTargetOnly) || host === ef.target)) {
defaultFn.apply(host, args);
}
}
// broadcast listeners are fired as discreet events on the
// YUI instance and potentially the YUI global.
if (self.broadcast) {
self._broadcast(args);
}
if (afters && !self.prevented && self.stopped < 2) {
// Queue the after
afterQueue = es.afterQueue;
if (es.id === self.id || self.type !== yuievt.bubbling) {
self._procSubs(afters, args, ef);
if (afterQueue) {
while ((next = afterQueue.last())) {
next();
}
}
} else {
postponed = afters;
if (es.execDefaultCnt) {
postponed = Y.merge(postponed);
Y.each(postponed, function(s) {
s.postponed = true;
});
}
if (!afterQueue) {
es.afterQueue = new Y.Queue();
}
es.afterQueue.add(function() {
self._procSubs(postponed, args, ef);
});
}
}
self.target = null;
if (es.id === self.id) {
queue = es.queue;
if (queue) {
while (queue.length) {
q = queue.pop();
ce = q[0];
// set up stack to allow the next item to be processed
es.next = ce;
ce._fire(q[1]);
}
}
self.stack = null;
}
ret = !(self.stopped);
if (self.type !== yuievt.bubbling) {
es.stopped = 0;
es.prevented = 0;
self.stopped = 0;
self.prevented = 0;
}
} else {
defaultFn = self.defaultFn;
if(defaultFn) {
ef = self._getFacade(args);
if ((!self.defaultTargetOnly) || (host === ef.target)) {
defaultFn.apply(host, args);
}
}
}
// Kill the cached facade to free up memory.
// Otherwise we have the facade from the last fire, sitting around forever.
self._facade = null;
return ret;
};
CEProto._getFacade = function(fireArgs) {
var userArgs = this.details,
firstArg = userArgs && userArgs[0],
firstArgIsObj = (firstArg && (typeof firstArg === "object")),
ef = this._facade;
if (!ef) {
ef = new Y.EventFacade(this, this.currentTarget);
}
if (firstArgIsObj) {
// protect the event facade properties
mixFacadeProps(ef, firstArg);
// Allow the event type to be faked http://yuilibrary.com/projects/yui3/ticket/2528376
if (firstArg.type) {
ef.type = firstArg.type;
}
if (fireArgs) {
fireArgs[0] = ef;
}
} else {
if (fireArgs) {
fireArgs.unshift(ef);
}
}
// update the details field with the arguments
ef.details = this.details;
// use the original target when the event bubbled to this target
ef.target = this.originalTarget || this.target;
ef.currentTarget = this.currentTarget;
ef.stopped = 0;
ef.prevented = 0;
this._facade = ef;
return this._facade;
};
/**
* Stop propagation to bubble targets
* @for CustomEvent
* @method stopPropagation
*/
CEProto.stopPropagation = function() {
this.stopped = 1;
if (this.stack) {
this.stack.stopped = 1;
}
if (this.events) {
this.events.fire('stopped', this);
}
};
/**
* Stops propagation to bubble targets, and prevents any remaining
* subscribers on the current target from executing.
* @method stopImmediatePropagation
*/
CEProto.stopImmediatePropagation = function() {
this.stopped = 2;
if (this.stack) {
this.stack.stopped = 2;
}
if (this.events) {
this.events.fire('stopped', this);
}
};
/**
* Prevents the execution of this event's defaultFn
* @method preventDefault
*/
CEProto.preventDefault = function() {
if (this.preventable) {
this.prevented = 1;
if (this.stack) {
this.stack.prevented = 1;
}
}
};
/**
* Stops the event propagation and prevents the default
* event behavior.
* @method halt
* @param immediate {boolean} if true additional listeners
* on the current target will not be executed
*/
CEProto.halt = function(immediate) {
if (immediate) {
this.stopImmediatePropagation();
} else {
this.stopPropagation();
}
this.preventDefault();
};
/**
* Registers another EventTarget as a bubble target. Bubble order
* is determined by the order registered. Multiple targets can
* be specified.
*
* Events can only bubble if emitFacade is true.
*
* Included in the event-custom-complex submodule.
*
* @method addTarget
* @param o {EventTarget} the target to add
* @for EventTarget
*/
ETProto.addTarget = function(o) {
var etState = this._yuievt;
if (!etState.targets) {
etState.targets = {};
}
etState.targets[Y.stamp(o)] = o;
etState.hasTargets = true;
};
/**
* Returns an array of bubble targets for this object.
* @method getTargets
* @return EventTarget[]
*/
ETProto.getTargets = function() {
var targets = this._yuievt.targets;
return targets ? YObject.values(targets) : [];
};
/**
* Removes a bubble target
* @method removeTarget
* @param o {EventTarget} the target to remove
* @for EventTarget
*/
ETProto.removeTarget = function(o) {
var targets = this._yuievt.targets;
if (targets) {
delete targets[Y.stamp(o, true)];
if (YObject.size(targets) === 0) {
this._yuievt.hasTargets = false;
}
}
};
/**
* Propagate an event. Requires the event-custom-complex module.
* @method bubble
* @param evt {CustomEvent} the custom event to propagate
* @return {boolean} the aggregated return value from Event.Custom.fire
* @for EventTarget
*/
ETProto.bubble = function(evt, args, target, es) {
var targs = this._yuievt.targets,
ret = true,
t,
ce,
i,
bc,
ce2,
type = evt && evt.type,
originalTarget = target || (evt && evt.target) || this,
oldbubble;
if (!evt || ((!evt.stopped) && targs)) {
for (i in targs) {
if (targs.hasOwnProperty(i)) {
t = targs[i];
ce = t._yuievt.events[type];
if (t._hasSiblings) {
ce2 = t.getSibling(type, ce);
}
if (ce2 && !ce) {
ce = t.publish(type);
}
oldbubble = t._yuievt.bubbling;
t._yuievt.bubbling = type;
// if this event was not published on the bubble target,
// continue propagating the event.
if (!ce) {
if (t._yuievt.hasTargets) {
t.bubble(evt, args, originalTarget, es);
}
} else {
if (ce2) {
ce.sibling = ce2;
}
// set the original target to that the target payload on the facade is correct.
ce.target = originalTarget;
ce.originalTarget = originalTarget;
ce.currentTarget = t;
bc = ce.broadcast;
ce.broadcast = false;
// default publish may not have emitFacade true -- that
// shouldn't be what the implementer meant to do
ce.emitFacade = true;
ce.stack = es;
// TODO: See what's getting in the way of changing this to use
// the more performant ce._fire(args || evt.details || []).
// Something in Widget Parent/Child tests is not happy if we
// change it - maybe evt.details related?
ret = ret && ce.fire.apply(ce, args || evt.details || []);
ce.broadcast = bc;
ce.originalTarget = null;
// stopPropagation() was called
if (ce.stopped) {
break;
}
}
t._yuievt.bubbling = oldbubble;
}
}
}
return ret;
};
FACADE = new Y.EventFacade();
FACADE_KEYS = {};
// Flatten whitelist
for (key in FACADE) {
FACADE_KEYS[key] = true;
}
}, '@VERSION@', {"requires": ["event-custom-base"]});
YUI.add('node-core', function (Y, NAME) {
/**
* The Node Utility provides a DOM-like interface for interacting with DOM nodes.
* @module node
* @main node
* @submodule node-core
*/
/**
* The Node class provides a wrapper for manipulating DOM Nodes.
* Node properties can be accessed via the set/get methods.
* Use `Y.one()` to retrieve Node instances.
*
* <strong>NOTE:</strong> Node properties are accessed using
* the <code>set</code> and <code>get</code> methods.
*
* @class Node
* @constructor
* @param {DOMNode} node the DOM node to be mapped to the Node instance.
* @uses EventTarget
*/
// "globals"
var DOT = '.',
NODE_NAME = 'nodeName',
NODE_TYPE = 'nodeType',
OWNER_DOCUMENT = 'ownerDocument',
TAG_NAME = 'tagName',
UID = '_yuid',
EMPTY_OBJ = {},
_slice = Array.prototype.slice,
Y_DOM = Y.DOM,
Y_Node = function(node) {
if (!this.getDOMNode) { // support optional "new"
return new Y_Node(node);
}
if (typeof node == 'string') {
node = Y_Node._fromString(node);
if (!node) {
return null; // NOTE: return
}
}
var uid = (node.nodeType !== 9) ? node.uniqueID : node[UID];
if (uid && Y_Node._instances[uid] && Y_Node._instances[uid]._node !== node) {
node[UID] = null; // unset existing uid to prevent collision (via clone or hack)
}
uid = uid || Y.stamp(node);
if (!uid) { // stamp failed; likely IE non-HTMLElement
uid = Y.guid();
}
this[UID] = uid;
/**
* The underlying DOM node bound to the Y.Node instance
* @property _node
* @type DOMNode
* @private
*/
this._node = node;
this._stateProxy = node; // when augmented with Attribute
if (this._initPlugins) { // when augmented with Plugin.Host
this._initPlugins();
}
},
// used with previous/next/ancestor tests
_wrapFn = function(fn) {
var ret = null;
if (fn) {
ret = (typeof fn == 'string') ?
function(n) {
return Y.Selector.test(n, fn);
} :
function(n) {
return fn(Y.one(n));
};
}
return ret;
};
// end "globals"
Y_Node.ATTRS = {};
Y_Node.DOM_EVENTS = {};
Y_Node._fromString = function(node) {
if (node) {
if (node.indexOf('doc') === 0) { // doc OR document
node = Y.config.doc;
} else if (node.indexOf('win') === 0) { // win OR window
node = Y.config.win;
} else {
node = Y.Selector.query(node, null, true);
}
}
return node || null;
};
/**
* The name of the component
* @static
* @type String
* @property NAME
*/
Y_Node.NAME = 'node';
/*
* The pattern used to identify ARIA attributes
*/
Y_Node.re_aria = /^(?:role$|aria-)/;
Y_Node.SHOW_TRANSITION = 'fadeIn';
Y_Node.HIDE_TRANSITION = 'fadeOut';
/**
* A list of Node instances that have been created
* @private
* @type Object
* @property _instances
* @static
*
*/
Y_Node._instances = {};
/**
* Retrieves the DOM node bound to a Node instance
* @method getDOMNode
* @static
*
* @param {Node | HTMLNode} node The Node instance or an HTMLNode
* @return {HTMLNode} The DOM node bound to the Node instance. If a DOM node is passed
* as the node argument, it is simply returned.
*/
Y_Node.getDOMNode = function(node) {
if (node) {
return (node.nodeType) ? node : node._node || null;
}
return null;
};
/**
* Checks Node return values and wraps DOM Nodes as Y.Node instances
* and DOM Collections / Arrays as Y.NodeList instances.
* Other return values just pass thru. If undefined is returned (e.g. no return)
* then the Node instance is returned for chainability.
* @method scrubVal
* @static
*
* @param {any} node The Node instance or an HTMLNode
* @return {Node | NodeList | Any} Depends on what is returned from the DOM node.
*/
Y_Node.scrubVal = function(val, node) {
if (val) { // only truthy values are risky
if (typeof val == 'object' || typeof val == 'function') { // safari nodeList === function
if (NODE_TYPE in val || Y_DOM.isWindow(val)) {// node || window
val = Y.one(val);
} else if ((val.item && !val._nodes) || // dom collection or Node instance
(val[0] && val[0][NODE_TYPE])) { // array of DOM Nodes
val = Y.all(val);
}
}
} else if (typeof val === 'undefined') {
val = node; // for chaining
} else if (val === null) {
val = null; // IE: DOM null not the same as null
}
return val;
};
/**
* Adds methods to the Y.Node prototype, routing through scrubVal.
* @method addMethod
* @static
*
* @param {String} name The name of the method to add
* @param {Function} fn The function that becomes the method
* @param {Object} context An optional context to call the method with
* (defaults to the Node instance)
* @return {any} Depends on what is returned from the DOM node.
*/
Y_Node.addMethod = function(name, fn, context) {
if (name && fn && typeof fn == 'function') {
Y_Node.prototype[name] = function() {
var args = _slice.call(arguments),
node = this,
ret;
if (args[0] && args[0]._node) {
args[0] = args[0]._node;
}
if (args[1] && args[1]._node) {
args[1] = args[1]._node;
}
args.unshift(node._node);
ret = fn.apply(node, args);
if (ret) { // scrub truthy
ret = Y_Node.scrubVal(ret, node);
}
(typeof ret != 'undefined') || (ret = node);
return ret;
};
} else {
Y.log('unable to add method: ' + name, 'warn', 'Node');
}
};
/**
* Imports utility methods to be added as Y.Node methods.
* @method importMethod
* @static
*
* @param {Object} host The object that contains the method to import.
* @param {String} name The name of the method to import
* @param {String} altName An optional name to use in place of the host name
* @param {Object} context An optional context to call the method with
*/
Y_Node.importMethod = function(host, name, altName) {
if (typeof name == 'string') {
altName = altName || name;
Y_Node.addMethod(altName, host[name], host);
} else {
Y.Array.each(name, function(n) {
Y_Node.importMethod(host, n);
});
}
};
/**
* Retrieves a NodeList based on the given CSS selector.
* @method all
*
* @param {string} selector The CSS selector to test against.
* @return {NodeList} A NodeList instance for the matching HTMLCollection/Array.
* @for YUI
*/
/**
* Returns a single Node instance bound to the node or the
* first element matching the given selector. Returns null if no match found.
* <strong>Note:</strong> For chaining purposes you may want to
* use <code>Y.all</code>, which returns a NodeList when no match is found.
* @method one
* @param {String | HTMLElement} node a node or Selector
* @return {Node | null} a Node instance or null if no match found.
* @for YUI
*/
/**
* Returns a single Node instance bound to the node or the
* first element matching the given selector. Returns null if no match found.
* <strong>Note:</strong> For chaining purposes you may want to
* use <code>Y.all</code>, which returns a NodeList when no match is found.
* @method one
* @static
* @param {String | HTMLElement} node a node or Selector
* @return {Node | null} a Node instance or null if no match found.
* @for Node
*/
Y_Node.one = function(node) {
var instance = null,
cachedNode,
uid;
if (node) {
if (typeof node == 'string') {
node = Y_Node._fromString(node);
if (!node) {
return null; // NOTE: return
}
} else if (node.getDOMNode) {
return node; // NOTE: return
}
if (node.nodeType || Y.DOM.isWindow(node)) { // avoid bad input (numbers, boolean, etc)
uid = (node.uniqueID && node.nodeType !== 9) ? node.uniqueID : node._yuid;
instance = Y_Node._instances[uid]; // reuse exising instances
cachedNode = instance ? instance._node : null;
if (!instance || (cachedNode && node !== cachedNode)) { // new Node when nodes don't match
instance = new Y_Node(node);
if (node.nodeType != 11) { // dont cache document fragment
Y_Node._instances[instance[UID]] = instance; // cache node
}
}
}
}
return instance;
};
/**
* The default setter for DOM properties
* Called with instance context (this === the Node instance)
* @method DEFAULT_SETTER
* @static
* @param {String} name The attribute/property being set
* @param {any} val The value to be set
* @return {any} The value
*/
Y_Node.DEFAULT_SETTER = function(name, val) {
var node = this._stateProxy,
strPath;
if (name.indexOf(DOT) > -1) {
strPath = name;
name = name.split(DOT);
// only allow when defined on node
Y.Object.setValue(node, name, val);
} else if (typeof node[name] != 'undefined') { // pass thru DOM properties
node[name] = val;
}
return val;
};
/**
* The default getter for DOM properties
* Called with instance context (this === the Node instance)
* @method DEFAULT_GETTER
* @static
* @param {String} name The attribute/property to look up
* @return {any} The current value
*/
Y_Node.DEFAULT_GETTER = function(name) {
var node = this._stateProxy,
val;
if (name.indexOf && name.indexOf(DOT) > -1) {
val = Y.Object.getValue(node, name.split(DOT));
} else if (typeof node[name] != 'undefined') { // pass thru from DOM
val = node[name];
}
return val;
};
Y.mix(Y_Node.prototype, {
DATA_PREFIX: 'data-',
/**
* The method called when outputting Node instances as strings
* @method toString
* @return {String} A string representation of the Node instance
*/
toString: function() {
var str = this[UID] + ': not bound to a node',
node = this._node,
attrs, id, className;
if (node) {
attrs = node.attributes;
id = (attrs && attrs.id) ? node.getAttribute('id') : null;
className = (attrs && attrs.className) ? node.getAttribute('className') : null;
str = node[NODE_NAME];
if (id) {
str += '#' + id;
}
if (className) {
str += '.' + className.replace(' ', '.');
}
// TODO: add yuid?
str += ' ' + this[UID];
}
return str;
},
/**
* Returns an attribute value on the Node instance.
* Unless pre-configured (via `Node.ATTRS`), get hands
* off to the underlying DOM node. Only valid
* attributes/properties for the node will be queried.
* @method get
* @param {String} attr The attribute
* @return {any} The current value of the attribute
*/
get: function(attr) {
var val;
if (this._getAttr) { // use Attribute imple
val = this._getAttr(attr);
} else {
val = this._get(attr);
}
if (val) {
val = Y_Node.scrubVal(val, this);
} else if (val === null) {
val = null; // IE: DOM null is not true null (even though they ===)
}
return val;
},
/**
* Helper method for get.
* @method _get
* @private
* @param {String} attr The attribute
* @return {any} The current value of the attribute
*/
_get: function(attr) {
var attrConfig = Y_Node.ATTRS[attr],
val;
if (attrConfig && attrConfig.getter) {
val = attrConfig.getter.call(this);
} else if (Y_Node.re_aria.test(attr)) {
val = this._node.getAttribute(attr, 2);
} else {
val = Y_Node.DEFAULT_GETTER.apply(this, arguments);
}
return val;
},
/**
* Sets an attribute on the Node instance.
* Unless pre-configured (via Node.ATTRS), set hands
* off to the underlying DOM node. Only valid
* attributes/properties for the node will be set.
* To set custom attributes use setAttribute.
* @method set
* @param {String} attr The attribute to be set.
* @param {any} val The value to set the attribute to.
* @chainable
*/
set: function(attr, val) {
var attrConfig = Y_Node.ATTRS[attr];
if (this._setAttr) { // use Attribute imple
this._setAttr.apply(this, arguments);
} else { // use setters inline
if (attrConfig && attrConfig.setter) {
attrConfig.setter.call(this, val, attr);
} else if (Y_Node.re_aria.test(attr)) { // special case Aria
this._node.setAttribute(attr, val);
} else {
Y_Node.DEFAULT_SETTER.apply(this, arguments);
}
}
return this;
},
/**
* Sets multiple attributes.
* @method setAttrs
* @param {Object} attrMap an object of name/value pairs to set
* @chainable
*/
setAttrs: function(attrMap) {
if (this._setAttrs) { // use Attribute imple
this._setAttrs(attrMap);
} else { // use setters inline
Y.Object.each(attrMap, function(v, n) {
this.set(n, v);
}, this);
}
return this;
},
/**
* Returns an object containing the values for the requested attributes.
* @method getAttrs
* @param {Array} attrs an array of attributes to get values
* @return {Object} An object with attribute name/value pairs.
*/
getAttrs: function(attrs) {
var ret = {};
if (this._getAttrs) { // use Attribute imple
this._getAttrs(attrs);
} else { // use setters inline
Y.Array.each(attrs, function(v, n) {
ret[v] = this.get(v);
}, this);
}
return ret;
},
/**
* Compares nodes to determine if they match.
* Node instances can be compared to each other and/or HTMLElements.
* @method compareTo
* @param {HTMLElement | Node} refNode The reference node to compare to the node.
* @return {Boolean} True if the nodes match, false if they do not.
*/
compareTo: function(refNode) {
var node = this._node;
if (refNode && refNode._node) {
refNode = refNode._node;
}
return node === refNode;
},
/**
* Determines whether the node is appended to the document.
* @method inDoc
* @param {Node|HTMLElement} doc optional An optional document to check against.
* Defaults to current document.
* @return {Boolean} Whether or not this node is appended to the document.
*/
inDoc: function(doc) {
var node = this._node;
doc = (doc) ? doc._node || doc : node[OWNER_DOCUMENT];
if (doc.documentElement) {
return Y_DOM.contains(doc.documentElement, node);
}
},
getById: function(id) {
var node = this._node,
ret = Y_DOM.byId(id, node[OWNER_DOCUMENT]);
if (ret && Y_DOM.contains(node, ret)) {
ret = Y.one(ret);
} else {
ret = null;
}
return ret;
},
/**
* Returns the nearest ancestor that passes the test applied by supplied boolean method.
* @method ancestor
* @param {String | Function} fn A selector string or boolean method for testing elements.
* If a function is used, it receives the current node being tested as the only argument.
* If fn is not passed as an argument, the parent node will be returned.
* @param {Boolean} testSelf optional Whether or not to include the element in the scan
* @param {String | Function} stopFn optional A selector string or boolean
* method to indicate when the search should stop. The search bails when the function
* returns true or the selector matches.
* If a function is used, it receives the current node being tested as the only argument.
* @return {Node} The matching Node instance or null if not found
*/
ancestor: function(fn, testSelf, stopFn) {
// testSelf is optional, check for stopFn as 2nd arg
if (arguments.length === 2 &&
(typeof testSelf == 'string' || typeof testSelf == 'function')) {
stopFn = testSelf;
}
return Y.one(Y_DOM.ancestor(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn)));
},
/**
* Returns the ancestors that pass the test applied by supplied boolean method.
* @method ancestors
* @param {String | Function} fn A selector string or boolean method for testing elements.
* @param {Boolean} testSelf optional Whether or not to include the element in the scan
* If a function is used, it receives the current node being tested as the only argument.
* @return {NodeList} A NodeList instance containing the matching elements
*/
ancestors: function(fn, testSelf, stopFn) {
if (arguments.length === 2 &&
(typeof testSelf == 'string' || typeof testSelf == 'function')) {
stopFn = testSelf;
}
return Y.all(Y_DOM.ancestors(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn)));
},
/**
* Returns the previous matching sibling.
* Returns the nearest element node sibling if no method provided.
* @method previous
* @param {String | Function} fn A selector or boolean method for testing elements.
* If a function is used, it receives the current node being tested as the only argument.
* @return {Node} Node instance or null if not found
*/
previous: function(fn, all) {
return Y.one(Y_DOM.elementByAxis(this._node, 'previousSibling', _wrapFn(fn), all));
},
/**
* Returns the next matching sibling.
* Returns the nearest element node sibling if no method provided.
* @method next
* @param {String | Function} fn A selector or boolean method for testing elements.
* If a function is used, it receives the current node being tested as the only argument.
* @return {Node} Node instance or null if not found
*/
next: function(fn, all) {
return Y.one(Y_DOM.elementByAxis(this._node, 'nextSibling', _wrapFn(fn), all));
},
/**
* Returns all matching siblings.
* Returns all siblings if no method provided.
* @method siblings
* @param {String | Function} fn A selector or boolean method for testing elements.
* If a function is used, it receives the current node being tested as the only argument.
* @return {NodeList} NodeList instance bound to found siblings
*/
siblings: function(fn) {
return Y.all(Y_DOM.siblings(this._node, _wrapFn(fn)));
},
/**
* Retrieves a single Node instance, the first element matching the given
* CSS selector.
* Returns null if no match found.
* @method one
*
* @param {string} selector The CSS selector to test against.
* @return {Node | null} A Node instance for the matching HTMLElement or null
* if no match found.
*/
one: function(selector) {
return Y.one(Y.Selector.query(selector, this._node, true));
},
/**
* Retrieves a NodeList based on the given CSS selector.
* @method all
*
* @param {string} selector The CSS selector to test against.
* @return {NodeList} A NodeList instance for the matching HTMLCollection/Array.
*/
all: function(selector) {
var nodelist;
if (this._node) {
nodelist = Y.all(Y.Selector.query(selector, this._node));
nodelist._query = selector;
nodelist._queryRoot = this._node;
}
return nodelist || Y.all([]);
},
// TODO: allow fn test
/**
* Test if the supplied node matches the supplied selector.
* @method test
*
* @param {string} selector The CSS selector to test against.
* @return {boolean} Whether or not the node matches the selector.
*/
test: function(selector) {
return Y.Selector.test(this._node, selector);
},
/**
* Removes the node from its parent.
* Shortcut for myNode.get('parentNode').removeChild(myNode);
* @method remove
* @param {Boolean} destroy whether or not to call destroy() on the node
* after removal.
* @chainable
*
*/
remove: function(destroy) {
var node = this._node;
if (node && node.parentNode) {
node.parentNode.removeChild(node);
}
if (destroy) {
this.destroy();
}
return this;
},
/**
* Replace the node with the other node. This is a DOM update only
* and does not change the node bound to the Node instance.
* Shortcut for myNode.get('parentNode').replaceChild(newNode, myNode);
* @method replace
* @param {Node | HTMLNode} newNode Node to be inserted
* @chainable
*
*/
replace: function(newNode) {
var node = this._node;
if (typeof newNode == 'string') {
newNode = Y_Node.create(newNode);
}
node.parentNode.replaceChild(Y_Node.getDOMNode(newNode), node);
return this;
},
/**
* @method replaceChild
* @for Node
* @param {String | HTMLElement | Node} node Node to be inserted
* @param {HTMLElement | Node} refNode Node to be replaced
* @return {Node} The replaced node
*/
replaceChild: function(node, refNode) {
if (typeof node == 'string') {
node = Y_DOM.create(node);
}
return Y.one(this._node.replaceChild(Y_Node.getDOMNode(node), Y_Node.getDOMNode(refNode)));
},
/**
* Nulls internal node references, removes any plugins and event listeners.
* Note that destroy() will not remove the node from its parent or from the DOM. For that
* functionality, call remove(true).
* @method destroy
* @param {Boolean} recursivePurge (optional) Whether or not to remove listeners from the
* node's subtree (default is false)
*
*/
destroy: function(recursive) {
var UID = Y.config.doc.uniqueID ? 'uniqueID' : '_yuid',
instance;
this.purge(); // TODO: only remove events add via this Node
if (this.unplug) { // may not be a PluginHost
this.unplug();
}
this.clearData();
if (recursive) {
Y.NodeList.each(this.all('*'), function(node) {
instance = Y_Node._instances[node[UID]];
if (instance) {
instance.destroy();
} else { // purge in case added by other means
Y.Event.purgeElement(node);
}
});
}
this._node = null;
this._stateProxy = null;
delete Y_Node._instances[this._yuid];
},
/**
* Invokes a method on the Node instance
* @method invoke
* @param {String} method The name of the method to invoke
* @param {Any} a, b, c, etc. Arguments to invoke the method with.
* @return Whatever the underly method returns.
* DOM Nodes and Collections return values
* are converted to Node/NodeList instances.
*
*/
invoke: function(method, a, b, c, d, e) {
var node = this._node,
ret;
if (a && a._node) {
a = a._node;
}
if (b && b._node) {
b = b._node;
}
ret = node[method](a, b, c, d, e);
return Y_Node.scrubVal(ret, this);
},
/**
* @method swap
* @description Swap DOM locations with the given node.
* This does not change which DOM node each Node instance refers to.
* @param {Node} otherNode The node to swap with
* @chainable
*/
swap: Y.config.doc.documentElement.swapNode ?
function(otherNode) {
this._node.swapNode(Y_Node.getDOMNode(otherNode));
} :
function(otherNode) {
otherNode = Y_Node.getDOMNode(otherNode);
var node = this._node,
parent = otherNode.parentNode,
nextSibling = otherNode.nextSibling;
if (nextSibling === node) {
parent.insertBefore(node, otherNode);
} else if (otherNode === node.nextSibling) {
parent.insertBefore(otherNode, node);
} else {
node.parentNode.replaceChild(otherNode, node);
Y_DOM.addHTML(parent, node, nextSibling);
}
return this;
},
hasMethod: function(method) {
var node = this._node;
return !!(node && method in node &&
typeof node[method] != 'unknown' &&
(typeof node[method] == 'function' ||
String(node[method]).indexOf('function') === 1)); // IE reports as object, prepends space
},
isFragment: function() {
return (this.get('nodeType') === 11);
},
/**
* Removes and destroys all of the nodes within the node.
* @method empty
* @chainable
*/
empty: function() {
this.get('childNodes').remove().destroy(true);
return this;
},
/**
* Returns the DOM node bound to the Node instance
* @method getDOMNode
* @return {DOMNode}
*/
getDOMNode: function() {
return this._node;
}
}, true);
Y.Node = Y_Node;
Y.one = Y_Node.one;
/**
* The NodeList module provides support for managing collections of Nodes.
* @module node
* @submodule node-core
*/
/**
* The NodeList class provides a wrapper for manipulating DOM NodeLists.
* NodeList properties can be accessed via the set/get methods.
* Use Y.all() to retrieve NodeList instances.
*
* @class NodeList
* @constructor
* @param nodes {String|element|Node|Array} A selector, DOM element, Node, list of DOM elements, or list of Nodes with which to populate this NodeList.
*/
var NodeList = function(nodes) {
var tmp = [];
if (nodes) {
if (typeof nodes === 'string') { // selector query
this._query = nodes;
nodes = Y.Selector.query(nodes);
} else if (nodes.nodeType || Y_DOM.isWindow(nodes)) { // domNode || window
nodes = [nodes];
} else if (nodes._node) { // Y.Node
nodes = [nodes._node];
} else if (nodes[0] && nodes[0]._node) { // allow array of Y.Nodes
Y.Array.each(nodes, function(node) {
if (node._node) {
tmp.push(node._node);
}
});
nodes = tmp;
} else { // array of domNodes or domNodeList (no mixed array of Y.Node/domNodes)
nodes = Y.Array(nodes, 0, true);
}
}
/**
* The underlying array of DOM nodes bound to the Y.NodeList instance
* @property _nodes
* @private
*/
this._nodes = nodes || [];
};
NodeList.NAME = 'NodeList';
/**
* Retrieves the DOM nodes bound to a NodeList instance
* @method getDOMNodes
* @static
*
* @param {NodeList} nodelist The NodeList instance
* @return {Array} The array of DOM nodes bound to the NodeList
*/
NodeList.getDOMNodes = function(nodelist) {
return (nodelist && nodelist._nodes) ? nodelist._nodes : nodelist;
};
NodeList.each = function(instance, fn, context) {
var nodes = instance._nodes;
if (nodes && nodes.length) {
Y.Array.each(nodes, fn, context || instance);
} else {
Y.log('no nodes bound to ' + this, 'warn', 'NodeList');
}
};
NodeList.addMethod = function(name, fn, context) {
if (name && fn) {
NodeList.prototype[name] = function() {
var ret = [],
args = arguments;
Y.Array.each(this._nodes, function(node) {
var UID = (node.uniqueID && node.nodeType !== 9 ) ? 'uniqueID' : '_yuid',
instance = Y.Node._instances[node[UID]],
ctx,
result;
if (!instance) {
instance = NodeList._getTempNode(node);
}
ctx = context || instance;
result = fn.apply(ctx, args);
if (result !== undefined && result !== instance) {
ret[ret.length] = result;
}
});
// TODO: remove tmp pointer
return ret.length ? ret : this;
};
} else {
Y.log('unable to add method: ' + name + ' to NodeList', 'warn', 'node');
}
};
NodeList.importMethod = function(host, name, altName) {
if (typeof name === 'string') {
altName = altName || name;
NodeList.addMethod(name, host[name]);
} else {
Y.Array.each(name, function(n) {
NodeList.importMethod(host, n);
});
}
};
NodeList._getTempNode = function(node) {
var tmp = NodeList._tempNode;
if (!tmp) {
tmp = Y.Node.create('<div></div>');
NodeList._tempNode = tmp;
}
tmp._node = node;
tmp._stateProxy = node;
return tmp;
};
Y.mix(NodeList.prototype, {
_invoke: function(method, args, getter) {
var ret = (getter) ? [] : this;
this.each(function(node) {
var val = node[method].apply(node, args);
if (getter) {
ret.push(val);
}
});
return ret;
},
/**
* Retrieves the Node instance at the given index.
* @method item
*
* @param {Number} index The index of the target Node.
* @return {Node} The Node instance at the given index.
*/
item: function(index) {
return Y.one((this._nodes || [])[index]);
},
/**
* Applies the given function to each Node in the NodeList.
* @method each
* @param {Function} fn The function to apply. It receives 3 arguments:
* the current node instance, the node's index, and the NodeList instance
* @param {Object} context optional An optional context to apply the function with
* Default context is the current Node instance
* @chainable
*/
each: function(fn, context) {
var instance = this;
Y.Array.each(this._nodes, function(node, index) {
node = Y.one(node);
return fn.call(context || node, node, index, instance);
});
return instance;
},
batch: function(fn, context) {
var nodelist = this;
Y.Array.each(this._nodes, function(node, index) {
var instance = Y.Node._instances[node[UID]];
if (!instance) {
instance = NodeList._getTempNode(node);
}
return fn.call(context || instance, instance, index, nodelist);
});
return nodelist;
},
/**
* Executes the function once for each node until a true value is returned.
* @method some
* @param {Function} fn The function to apply. It receives 3 arguments:
* the current node instance, the node's index, and the NodeList instance
* @param {Object} context optional An optional context to execute the function from.
* Default context is the current Node instance
* @return {Boolean} Whether or not the function returned true for any node.
*/
some: function(fn, context) {
var instance = this;
return Y.Array.some(this._nodes, function(node, index) {
node = Y.one(node);
context = context || node;
return fn.call(context, node, index, instance);
});
},
/**
* Creates a documenFragment from the nodes bound to the NodeList instance
* @method toFrag
* @return {Node} a Node instance bound to the documentFragment
*/
toFrag: function() {
return Y.one(Y.DOM._nl2frag(this._nodes));
},
/**
* Returns the index of the node in the NodeList instance
* or -1 if the node isn't found.
* @method indexOf
* @param {Node | DOMNode} node the node to search for
* @return {Int} the index of the node value or -1 if not found
*/
indexOf: function(node) {
return Y.Array.indexOf(this._nodes, Y.Node.getDOMNode(node));
},
/**
* Filters the NodeList instance down to only nodes matching the given selector.
* @method filter
* @param {String} selector The selector to filter against
* @return {NodeList} NodeList containing the updated collection
* @see Selector
*/
filter: function(selector) {
return Y.all(Y.Selector.filter(this._nodes, selector));
},
/**
* Creates a new NodeList containing all nodes at every n indices, where
* remainder n % index equals r.
* (zero-based index).
* @method modulus
* @param {Int} n The offset to use (return every nth node)
* @param {Int} r An optional remainder to use with the modulus operation (defaults to zero)
* @return {NodeList} NodeList containing the updated collection
*/
modulus: function(n, r) {
r = r || 0;
var nodes = [];
NodeList.each(this, function(node, i) {
if (i % n === r) {
nodes.push(node);
}
});
return Y.all(nodes);
},
/**
* Creates a new NodeList containing all nodes at odd indices
* (zero-based index).
* @method odd
* @return {NodeList} NodeList containing the updated collection
*/
odd: function() {
return this.modulus(2, 1);
},
/**
* Creates a new NodeList containing all nodes at even indices
* (zero-based index), including zero.
* @method even
* @return {NodeList} NodeList containing the updated collection
*/
even: function() {
return this.modulus(2);
},
destructor: function() {
},
/**
* Reruns the initial query, when created using a selector query
* @method refresh
* @chainable
*/
refresh: function() {
var doc,
nodes = this._nodes,
query = this._query,
root = this._queryRoot;
if (query) {
if (!root) {
if (nodes && nodes[0] && nodes[0].ownerDocument) {
root = nodes[0].ownerDocument;
}
}
this._nodes = Y.Selector.query(query, root);
}
return this;
},
/**
* Returns the current number of items in the NodeList.
* @method size
* @return {Int} The number of items in the NodeList.
*/
size: function() {
return this._nodes.length;
},
/**
* Determines if the instance is bound to any nodes
* @method isEmpty
* @return {Boolean} Whether or not the NodeList is bound to any nodes
*/
isEmpty: function() {
return this._nodes.length < 1;
},
toString: function() {
var str = '',
errorMsg = this[UID] + ': not bound to any nodes',
nodes = this._nodes,
node;
if (nodes && nodes[0]) {
node = nodes[0];
str += node[NODE_NAME];
if (node.id) {
str += '#' + node.id;
}
if (node.className) {
str += '.' + node.className.replace(' ', '.');
}
if (nodes.length > 1) {
str += '...[' + nodes.length + ' items]';
}
}
return str || errorMsg;
},
/**
* Returns the DOM node bound to the Node instance
* @method getDOMNodes
* @return {Array}
*/
getDOMNodes: function() {
return this._nodes;
}
}, true);
NodeList.importMethod(Y.Node.prototype, [
/**
* Called on each Node instance. Nulls internal node references,
* removes any plugins and event listeners
* @method destroy
* @param {Boolean} recursivePurge (optional) Whether or not to
* remove listeners from the node's subtree (default is false)
* @see Node.destroy
*/
'destroy',
/**
* Called on each Node instance. Removes and destroys all of the nodes
* within the node
* @method empty
* @chainable
* @see Node.empty
*/
'empty',
/**
* Called on each Node instance. Removes the node from its parent.
* Shortcut for myNode.get('parentNode').removeChild(myNode);
* @method remove
* @param {Boolean} destroy whether or not to call destroy() on the node
* after removal.
* @chainable
* @see Node.remove
*/
'remove',
/**
* Called on each Node instance. Sets an attribute on the Node instance.
* Unless pre-configured (via Node.ATTRS), set hands
* off to the underlying DOM node. Only valid
* attributes/properties for the node will be set.
* To set custom attributes use setAttribute.
* @method set
* @param {String} attr The attribute to be set.
* @param {any} val The value to set the attribute to.
* @chainable
* @see Node.set
*/
'set'
]);
// one-off implementation to convert array of Nodes to NodeList
// e.g. Y.all('input').get('parentNode');
/** Called on each Node instance
* @method get
* @see Node
*/
NodeList.prototype.get = function(attr) {
var ret = [],
nodes = this._nodes,
isNodeList = false,
getTemp = NodeList._getTempNode,
instance,
val;
if (nodes[0]) {
instance = Y.Node._instances[nodes[0]._yuid] || getTemp(nodes[0]);
val = instance._get(attr);
if (val && val.nodeType) {
isNodeList = true;
}
}
Y.Array.each(nodes, function(node) {
instance = Y.Node._instances[node._yuid];
if (!instance) {
instance = getTemp(node);
}
val = instance._get(attr);
if (!isNodeList) { // convert array of Nodes to NodeList
val = Y.Node.scrubVal(val, instance);
}
ret.push(val);
});
return (isNodeList) ? Y.all(ret) : ret;
};
Y.NodeList = NodeList;
Y.all = function(nodes) {
return new NodeList(nodes);
};
Y.Node.all = Y.all;
/**
* @module node
* @submodule node-core
*/
var Y_NodeList = Y.NodeList,
ArrayProto = Array.prototype,
ArrayMethods = {
/** Returns a new NodeList combining the given NodeList(s)
* @for NodeList
* @method concat
* @param {NodeList | Array} valueN Arrays/NodeLists and/or values to
* concatenate to the resulting NodeList
* @return {NodeList} A new NodeList comprised of this NodeList joined with the input.
*/
'concat': 1,
/** Removes the last from the NodeList and returns it.
* @for NodeList
* @method pop
* @return {Node | null} The last item in the NodeList, or null if the list is empty.
*/
'pop': 0,
/** Adds the given Node(s) to the end of the NodeList.
* @for NodeList
* @method push
* @param {Node | DOMNode} nodes One or more nodes to add to the end of the NodeList.
*/
'push': 0,
/** Removes the first item from the NodeList and returns it.
* @for NodeList
* @method shift
* @return {Node | null} The first item in the NodeList, or null if the NodeList is empty.
*/
'shift': 0,
/** Returns a new NodeList comprising the Nodes in the given range.
* @for NodeList
* @method slice
* @param {Number} begin Zero-based index at which to begin extraction.
As a negative index, start indicates an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element in the sequence.
* @param {Number} end Zero-based index at which to end extraction. slice extracts up to but not including end.
slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3).
As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence.
If end is omitted, slice extracts to the end of the sequence.
* @return {NodeList} A new NodeList comprised of this NodeList joined with the input.
*/
'slice': 1,
/** Changes the content of the NodeList, adding new elements while removing old elements.
* @for NodeList
* @method splice
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end.
* @param {Number} howMany An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed.
* {Node | DOMNode| element1, ..., elementN
The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array.
* @return {NodeList} The element(s) removed.
*/
'splice': 1,
/** Adds the given Node(s) to the beginning of the NodeList.
* @for NodeList
* @method unshift
* @param {Node | DOMNode} nodes One or more nodes to add to the NodeList.
*/
'unshift': 0
};
Y.Object.each(ArrayMethods, function(returnNodeList, name) {
Y_NodeList.prototype[name] = function() {
var args = [],
i = 0,
arg,
ret;
while (typeof (arg = arguments[i++]) != 'undefined') { // use DOM nodes/nodeLists
args.push(arg._node || arg._nodes || arg);
}
ret = ArrayProto[name].apply(this._nodes, args);
if (returnNodeList) {
ret = Y.all(ret);
} else {
ret = Y.Node.scrubVal(ret);
}
return ret;
};
});
/**
* @module node
* @submodule node-core
*/
Y.Array.each([
/**
* Passes through to DOM method.
* @for Node
* @method removeChild
* @param {HTMLElement | Node} node Node to be removed
* @return {Node} The removed node
*/
'removeChild',
/**
* Passes through to DOM method.
* @method hasChildNodes
* @return {Boolean} Whether or not the node has any childNodes
*/
'hasChildNodes',
/**
* Passes through to DOM method.
* @method cloneNode
* @param {Boolean} deep Whether or not to perform a deep clone, which includes
* subtree and attributes
* @return {Node} The clone
*/
'cloneNode',
/**
* Passes through to DOM method.
* @method hasAttribute
* @param {String} attribute The attribute to test for
* @return {Boolean} Whether or not the attribute is present
*/
'hasAttribute',
/**
* Passes through to DOM method.
* @method scrollIntoView
* @chainable
*/
'scrollIntoView',
/**
* Passes through to DOM method.
* @method getElementsByTagName
* @param {String} tagName The tagName to collect
* @return {NodeList} A NodeList representing the HTMLCollection
*/
'getElementsByTagName',
/**
* Passes through to DOM method.
* @method focus
* @chainable
*/
'focus',
/**
* Passes through to DOM method.
* @method blur
* @chainable
*/
'blur',
/**
* Passes through to DOM method.
* Only valid on FORM elements
* @method submit
* @chainable
*/
'submit',
/**
* Passes through to DOM method.
* Only valid on FORM elements
* @method reset
* @chainable
*/
'reset',
/**
* Passes through to DOM method.
* @method select
* @chainable
*/
'select',
/**
* Passes through to DOM method.
* Only valid on TABLE elements
* @method createCaption
* @chainable
*/
'createCaption'
], function(method) {
Y.log('adding: ' + method, 'info', 'node');
Y.Node.prototype[method] = function(arg1, arg2, arg3) {
var ret = this.invoke(method, arg1, arg2, arg3);
return ret;
};
});
/**
* Passes through to DOM method.
* @method removeAttribute
* @param {String} attribute The attribute to be removed
* @chainable
*/
// one-off implementation due to IE returning boolean, breaking chaining
Y.Node.prototype.removeAttribute = function(attr) {
var node = this._node;
if (node) {
node.removeAttribute(attr, 0); // comma zero for IE < 8 to force case-insensitive
}
return this;
};
Y.Node.importMethod(Y.DOM, [
/**
* Determines whether the node is an ancestor of another HTML element in the DOM hierarchy.
* @method contains
* @param {Node | HTMLElement} needle The possible node or descendent
* @return {Boolean} Whether or not this node is the needle its ancestor
*/
'contains',
/**
* Allows setting attributes on DOM nodes, normalizing in some cases.
* This passes through to the DOM node, allowing for custom attributes.
* @method setAttribute
* @for Node
* @chainable
* @param {string} name The attribute name
* @param {string} value The value to set
*/
'setAttribute',
/**
* Allows getting attributes on DOM nodes, normalizing in some cases.
* This passes through to the DOM node, allowing for custom attributes.
* @method getAttribute
* @for Node
* @param {string} name The attribute name
* @return {string} The attribute value
*/
'getAttribute',
/**
* Wraps the given HTML around the node.
* @method wrap
* @param {String} html The markup to wrap around the node.
* @chainable
* @for Node
*/
'wrap',
/**
* Removes the node's parent node.
* @method unwrap
* @chainable
*/
'unwrap',
/**
* Applies a unique ID to the node if none exists
* @method generateID
* @return {String} The existing or generated ID
*/
'generateID'
]);
Y.NodeList.importMethod(Y.Node.prototype, [
/**
* Allows getting attributes on DOM nodes, normalizing in some cases.
* This passes through to the DOM node, allowing for custom attributes.
* @method getAttribute
* @see Node
* @for NodeList
* @param {string} name The attribute name
* @return {string} The attribute value
*/
'getAttribute',
/**
* Allows setting attributes on DOM nodes, normalizing in some cases.
* This passes through to the DOM node, allowing for custom attributes.
* @method setAttribute
* @see Node
* @for NodeList
* @chainable
* @param {string} name The attribute name
* @param {string} value The value to set
*/
'setAttribute',
/**
* Allows for removing attributes on DOM nodes.
* This passes through to the DOM node, allowing for custom attributes.
* @method removeAttribute
* @see Node
* @for NodeList
* @param {string} name The attribute to remove
*/
'removeAttribute',
/**
* Removes the parent node from node in the list.
* @method unwrap
* @chainable
*/
'unwrap',
/**
* Wraps the given HTML around each node.
* @method wrap
* @param {String} html The markup to wrap around the node.
* @chainable
*/
'wrap',
/**
* Applies a unique ID to each node if none exists
* @method generateID
* @return {String} The existing or generated ID
*/
'generateID'
]);
}, '@VERSION@', {"requires": ["dom-core", "selector"]});
YUI.add('node-base', function (Y, NAME) {
/**
* @module node
* @submodule node-base
*/
var methods = [
/**
* Determines whether each node has the given className.
* @method hasClass
* @for Node
* @param {String} className the class name to search for
* @return {Boolean} Whether or not the element has the specified class
*/
'hasClass',
/**
* Adds a class name to each node.
* @method addClass
* @param {String} className the class name to add to the node's class attribute
* @chainable
*/
'addClass',
/**
* Removes a class name from each node.
* @method removeClass
* @param {String} className the class name to remove from the node's class attribute
* @chainable
*/
'removeClass',
/**
* Replace a class with another class for each node.
* If no oldClassName is present, the newClassName is simply added.
* @method replaceClass
* @param {String} oldClassName the class name to be replaced
* @param {String} newClassName the class name that will be replacing the old class name
* @chainable
*/
'replaceClass',
/**
* If the className exists on the node it is removed, if it doesn't exist it is added.
* @method toggleClass
* @param {String} className the class name to be toggled
* @param {Boolean} force Option to force adding or removing the class.
* @chainable
*/
'toggleClass'
];
Y.Node.importMethod(Y.DOM, methods);
/**
* Determines whether each node has the given className.
* @method hasClass
* @see Node.hasClass
* @for NodeList
* @param {String} className the class name to search for
* @return {Array} An array of booleans for each node bound to the NodeList.
*/
/**
* Adds a class name to each node.
* @method addClass
* @see Node.addClass
* @param {String} className the class name to add to the node's class attribute
* @chainable
*/
/**
* Removes a class name from each node.
* @method removeClass
* @see Node.removeClass
* @param {String} className the class name to remove from the node's class attribute
* @chainable
*/
/**
* Replace a class with another class for each node.
* If no oldClassName is present, the newClassName is simply added.
* @method replaceClass
* @see Node.replaceClass
* @param {String} oldClassName the class name to be replaced
* @param {String} newClassName the class name that will be replacing the old class name
* @chainable
*/
/**
* If the className exists on the node it is removed, if it doesn't exist it is added.
* @method toggleClass
* @see Node.toggleClass
* @param {String} className the class name to be toggled
* @chainable
*/
Y.NodeList.importMethod(Y.Node.prototype, methods);
/**
* @module node
* @submodule node-base
*/
var Y_Node = Y.Node,
Y_DOM = Y.DOM;
/**
* Returns a new dom node using the provided markup string.
* @method create
* @static
* @param {String} html The markup used to create the element
* Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a>
* to escape html content.
* @param {HTMLDocument} doc An optional document context
* @return {Node} A Node instance bound to a DOM node or fragment
* @for Node
*/
Y_Node.create = function(html, doc) {
if (doc && doc._node) {
doc = doc._node;
}
return Y.one(Y_DOM.create(html, doc));
};
Y.mix(Y_Node.prototype, {
/**
* Creates a new Node using the provided markup string.
* @method create
* @param {String} html The markup used to create the element.
* Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a>
* to escape html content.
* @param {HTMLDocument} doc An optional document context
* @return {Node} A Node instance bound to a DOM node or fragment
*/
create: Y_Node.create,
/**
* Inserts the content before the reference node.
* @method insert
* @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert
* Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a>
* to escape html content.
* @param {Int | Node | HTMLElement | String} where The position to insert at.
* Possible "where" arguments
* <dl>
* <dt>Y.Node</dt>
* <dd>The Node to insert before</dd>
* <dt>HTMLElement</dt>
* <dd>The element to insert before</dd>
* <dt>Int</dt>
* <dd>The index of the child element to insert before</dd>
* <dt>"replace"</dt>
* <dd>Replaces the existing HTML</dd>
* <dt>"before"</dt>
* <dd>Inserts before the existing HTML</dd>
* <dt>"before"</dt>
* <dd>Inserts content before the node</dd>
* <dt>"after"</dt>
* <dd>Inserts content after the node</dd>
* </dl>
* @chainable
*/
insert: function(content, where) {
this._insert(content, where);
return this;
},
_insert: function(content, where) {
var node = this._node,
ret = null;
if (typeof where == 'number') { // allow index
where = this._node.childNodes[where];
} else if (where && where._node) { // Node
where = where._node;
}
if (content && typeof content != 'string') { // allow Node or NodeList/Array instances
content = content._node || content._nodes || content;
}
ret = Y_DOM.addHTML(node, content, where);
return ret;
},
/**
* Inserts the content as the firstChild of the node.
* @method prepend
* @param {String | Node | HTMLElement} content The content to insert
* Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a>
* to escape html content.
* @chainable
*/
prepend: function(content) {
return this.insert(content, 0);
},
/**
* Inserts the content as the lastChild of the node.
* @method append
* @param {String | Node | HTMLElement} content The content to insert
* Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a>
* to escape html content.
* @chainable
*/
append: function(content) {
return this.insert(content, null);
},
/**
* @method appendChild
* @param {String | HTMLElement | Node} node Node to be appended
* Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a>
* to escape html content.
* @return {Node} The appended node
*/
appendChild: function(node) {
return Y_Node.scrubVal(this._insert(node));
},
/**
* @method insertBefore
* @param {String | HTMLElement | Node} newNode Node to be appended
* @param {HTMLElement | Node} refNode Node to be inserted before
* Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a>
* to escape html content.
* @return {Node} The inserted node
*/
insertBefore: function(newNode, refNode) {
return Y.Node.scrubVal(this._insert(newNode, refNode));
},
/**
* Appends the node to the given node.
* @method appendTo
* @param {Node | HTMLElement} node The node to append to
* @chainable
*/
appendTo: function(node) {
Y.one(node).append(this);
return this;
},
/**
* Replaces the node's current content with the content.
* Note that this passes to innerHTML and is not escaped.
* Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a>
* to escape html content or `set('text')` to add as text.
* @method setContent
* @deprecated Use setHTML
* @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert
* @chainable
*/
setContent: function(content) {
this._insert(content, 'replace');
return this;
},
/**
* Returns the node's current content (e.g. innerHTML)
* @method getContent
* @deprecated Use getHTML
* @return {String} The current content
*/
getContent: function(content) {
return this.get('innerHTML');
}
});
/**
* Replaces the node's current html content with the content provided.
* Note that this passes to innerHTML and is not escaped.
* Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text.
* @method setHTML
* @param {String | HTML | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert
* @chainable
*/
Y.Node.prototype.setHTML = Y.Node.prototype.setContent;
/**
* Returns the node's current html content (e.g. innerHTML)
* @method getHTML
* @return {String} The html content
*/
Y.Node.prototype.getHTML = Y.Node.prototype.getContent;
Y.NodeList.importMethod(Y.Node.prototype, [
/**
* Called on each Node instance
* @for NodeList
* @method append
* @see Node.append
*/
'append',
/**
* Called on each Node instance
* @for NodeList
* @method insert
* @see Node.insert
*/
'insert',
/**
* Called on each Node instance
* @for NodeList
* @method appendChild
* @see Node.appendChild
*/
'appendChild',
/**
* Called on each Node instance
* @for NodeList
* @method insertBefore
* @see Node.insertBefore
*/
'insertBefore',
/**
* Called on each Node instance
* @for NodeList
* @method prepend
* @see Node.prepend
*/
'prepend',
/**
* Called on each Node instance
* Note that this passes to innerHTML and is not escaped.
* Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text.
* @for NodeList
* @method setContent
* @deprecated Use setHTML
*/
'setContent',
/**
* Called on each Node instance
* @for NodeList
* @method getContent
* @deprecated Use getHTML
*/
'getContent',
/**
* Called on each Node instance
* Note that this passes to innerHTML and is not escaped.
* Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text.
* @for NodeList
* @method setHTML
* @see Node.setHTML
*/
'setHTML',
/**
* Called on each Node instance
* @for NodeList
* @method getHTML
* @see Node.getHTML
*/
'getHTML'
]);
/**
* @module node
* @submodule node-base
*/
var Y_Node = Y.Node,
Y_DOM = Y.DOM;
/**
* Static collection of configuration attributes for special handling
* @property ATTRS
* @static
* @type object
*/
Y_Node.ATTRS = {
/**
* Allows for getting and setting the text of an element.
* Formatting is preserved and special characters are treated literally.
* @config text
* @type String
*/
text: {
getter: function() {
return Y_DOM.getText(this._node);
},
setter: function(content) {
Y_DOM.setText(this._node, content);
return content;
}
},
/**
* Allows for getting and setting the text of an element.
* Formatting is preserved and special characters are treated literally.
* @config for
* @type String
*/
'for': {
getter: function() {
return Y_DOM.getAttribute(this._node, 'for');
},
setter: function(val) {
Y_DOM.setAttribute(this._node, 'for', val);
return val;
}
},
'options': {
getter: function() {
return this._node.getElementsByTagName('option');
}
},
/**
* Returns a NodeList instance of all HTMLElement children.
* @readOnly
* @config children
* @type NodeList
*/
'children': {
getter: function() {
var node = this._node,
children = node.children,
childNodes, i, len;
if (!children) {
childNodes = node.childNodes;
children = [];
for (i = 0, len = childNodes.length; i < len; ++i) {
if (childNodes[i].tagName) {
children[children.length] = childNodes[i];
}
}
}
return Y.all(children);
}
},
value: {
getter: function() {
return Y_DOM.getValue(this._node);
},
setter: function(val) {
Y_DOM.setValue(this._node, val);
return val;
}
}
};
Y.Node.importMethod(Y.DOM, [
/**
* Allows setting attributes on DOM nodes, normalizing in some cases.
* This passes through to the DOM node, allowing for custom attributes.
* @method setAttribute
* @for Node
* @for NodeList
* @chainable
* @param {string} name The attribute name
* @param {string} value The value to set
*/
'setAttribute',
/**
* Allows getting attributes on DOM nodes, normalizing in some cases.
* This passes through to the DOM node, allowing for custom attributes.
* @method getAttribute
* @for Node
* @for NodeList
* @param {string} name The attribute name
* @return {string} The attribute value
*/
'getAttribute'
]);
/**
* @module node
* @submodule node-base
*/
var Y_Node = Y.Node;
var Y_NodeList = Y.NodeList;
/**
* List of events that route to DOM events
* @static
* @property DOM_EVENTS
* @for Node
*/
Y_Node.DOM_EVENTS = {
abort: 1,
beforeunload: 1,
blur: 1,
change: 1,
click: 1,
close: 1,
command: 1,
contextmenu: 1,
dblclick: 1,
DOMMouseScroll: 1,
drag: 1,
dragstart: 1,
dragenter: 1,
dragover: 1,
dragleave: 1,
dragend: 1,
drop: 1,
error: 1,
focus: 1,
key: 1,
keydown: 1,
keypress: 1,
keyup: 1,
load: 1,
message: 1,
mousedown: 1,
mouseenter: 1,
mouseleave: 1,
mousemove: 1,
mousemultiwheel: 1,
mouseout: 1,
mouseover: 1,
mouseup: 1,
mousewheel: 1,
orientationchange: 1,
reset: 1,
resize: 1,
select: 1,
selectstart: 1,
submit: 1,
scroll: 1,
textInput: 1,
unload: 1
};
// Add custom event adaptors to this list. This will make it so
// that delegate, key, available, contentready, etc all will
// be available through Node.on
Y.mix(Y_Node.DOM_EVENTS, Y.Env.evt.plugins);
Y.augment(Y_Node, Y.EventTarget);
Y.mix(Y_Node.prototype, {
/**
* Removes event listeners from the node and (optionally) its subtree
* @method purge
* @param {Boolean} recurse (optional) Whether or not to remove listeners from the
* node's subtree
* @param {String} type (optional) Only remove listeners of the specified type
* @chainable
*
*/
purge: function(recurse, type) {
Y.Event.purgeElement(this._node, recurse, type);
return this;
}
});
Y.mix(Y.NodeList.prototype, {
_prepEvtArgs: function(type, fn, context) {
// map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc)
var args = Y.Array(arguments, 0, true);
if (args.length < 2) { // type only (event hash) just add nodes
args[2] = this._nodes;
} else {
args.splice(2, 0, this._nodes);
}
args[3] = context || this; // default to NodeList instance as context
return args;
},
/**
Subscribe a callback function for each `Node` in the collection to execute
in response to a DOM event.
NOTE: Generally, the `on()` method should be avoided on `NodeLists`, in
favor of using event delegation from a parent Node. See the Event user
guide for details.
Most DOM events are associated with a preventable default behavior, such as
link clicks navigating to a new page. Callbacks are passed a
`DOMEventFacade` object as their first argument (usually called `e`) that
can be used to prevent this default behavior with `e.preventDefault()`. See
the `DOMEventFacade` API for all available properties and methods on the
object.
By default, the `this` object will be the `NodeList` that the subscription
came from, <em>not the `Node` that received the event</em>. Use
`e.currentTarget` to refer to the `Node`.
Returning `false` from a callback is supported as an alternative to calling
`e.preventDefault(); e.stopPropagation();`. However, it is recommended to
use the event methods.
@example
Y.all(".sku").on("keydown", function (e) {
if (e.keyCode === 13) {
e.preventDefault();
// Use e.currentTarget to refer to the individual Node
var item = Y.MyApp.searchInventory( e.currentTarget.get('value') );
// etc ...
}
});
@method on
@param {String} type The name of the event
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching that
subscription
@for NodeList
**/
on: function(type, fn, context) {
return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments));
},
/**
* Applies an one-time event listener to each Node bound to the NodeList.
* @method once
* @param {String} type The event being listened for
* @param {Function} fn The handler to call when the event fires
* @param {Object} context The context to call the handler with.
* Default is the NodeList instance.
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
* @for NodeList
*/
once: function(type, fn, context) {
return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments));
},
/**
* Applies an event listener to each Node bound to the NodeList.
* The handler is called only after all on() handlers are called
* and the event is not prevented.
* @method after
* @param {String} type The event being listened for
* @param {Function} fn The handler to call when the event fires
* @param {Object} context The context to call the handler with.
* Default is the NodeList instance.
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
* @for NodeList
*/
after: function(type, fn, context) {
return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments));
},
/**
* Applies an one-time event listener to each Node bound to the NodeList
* that will be called only after all on() handlers are called and the
* event is not prevented.
*
* @method onceAfter
* @param {String} type The event being listened for
* @param {Function} fn The handler to call when the event fires
* @param {Object} context The context to call the handler with.
* Default is the NodeList instance.
* @return {EventHandle} A subscription handle capable of detaching that
* subscription
* @for NodeList
*/
onceAfter: function(type, fn, context) {
return Y.onceAfter.apply(Y, this._prepEvtArgs.apply(this, arguments));
}
});
Y_NodeList.importMethod(Y.Node.prototype, [
/**
* Called on each Node instance
* @method detach
* @see Node.detach
* @for NodeList
*/
'detach',
/** Called on each Node instance
* @method detachAll
* @see Node.detachAll
* @for NodeList
*/
'detachAll'
]);
/**
Subscribe a callback function to execute in response to a DOM event or custom
event.
Most DOM events are associated with a preventable default behavior such as
link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade`
object as their first argument (usually called `e`) that can be used to
prevent this default behavior with `e.preventDefault()`. See the
`DOMEventFacade` API for all available properties and methods on the object.
If the event name passed as the first parameter is not a whitelisted DOM event,
it will be treated as a custom event subscriptions, allowing
`node.fire('customEventName')` later in the code. Refer to the Event user guide
for the full DOM event whitelist.
By default, the `this` object in the callback will refer to the subscribed
`Node`.
Returning `false` from a callback is supported as an alternative to calling
`e.preventDefault(); e.stopPropagation();`. However, it is recommended to use
the event methods.
@example
Y.one("#my-form").on("submit", function (e) {
e.preventDefault();
// proceed with ajax form submission instead...
});
@method on
@param {String} type The name of the event
@param {Function} fn The callback to execute in response to the event
@param {Object} [context] Override `this` object in callback
@param {Any} [arg*] 0..n additional arguments to supply to the subscriber
@return {EventHandle} A subscription handle capable of detaching that
subscription
@for Node
**/
Y.mix(Y.Node.ATTRS, {
offsetHeight: {
setter: function(h) {
Y.DOM.setHeight(this._node, h);
return h;
},
getter: function() {
return this._node.offsetHeight;
}
},
offsetWidth: {
setter: function(w) {
Y.DOM.setWidth(this._node, w);
return w;
},
getter: function() {
return this._node.offsetWidth;
}
}
});
Y.mix(Y.Node.prototype, {
sizeTo: function(w, h) {
var node;
if (arguments.length < 2) {
node = Y.one(w);
w = node.get('offsetWidth');
h = node.get('offsetHeight');
}
this.setAttrs({
offsetWidth: w,
offsetHeight: h
});
}
});
/**
* @module node
* @submodule node-base
*/
var Y_Node = Y.Node;
Y.mix(Y_Node.prototype, {
/**
* Makes the node visible.
* If the "transition" module is loaded, show optionally
* animates the showing of the node using either the default
* transition effect ('fadeIn'), or the given named effect.
* @method show
* @for Node
* @param {String} name A named Transition effect to use as the show effect.
* @param {Object} config Options to use with the transition.
* @param {Function} callback An optional function to run after the transition completes.
* @chainable
*/
show: function(callback) {
callback = arguments[arguments.length - 1];
this.toggleView(true, callback);
return this;
},
/**
* The implementation for showing nodes.
* Default is to remove the hidden attribute and reset the CSS style.display property.
* @method _show
* @protected
* @chainable
*/
_show: function() {
this.removeAttribute('hidden');
// For back-compat we need to leave this in for browsers that
// do not visually hide a node via the hidden attribute
// and for users that check visibility based on style display.
this.setStyle('display', '');
},
_isHidden: function() {
return Y.DOM.getAttribute(this._node, 'hidden') === 'true';
},
/**
* Displays or hides the node.
* If the "transition" module is loaded, toggleView optionally
* animates the toggling of the node using given named effect.
* @method toggleView
* @for Node
* @param {String} [name] An optional string value to use as transition effect.
* @param {Boolean} [on] An optional boolean value to force the node to be shown or hidden
* @param {Function} [callback] An optional function to run after the transition completes.
* @chainable
*/
toggleView: function(on, callback) {
this._toggleView.apply(this, arguments);
return this;
},
_toggleView: function(on, callback) {
callback = arguments[arguments.length - 1];
// base on current state if not forcing
if (typeof on != 'boolean') {
on = (this._isHidden()) ? 1 : 0;
}
if (on) {
this._show();
} else {
this._hide();
}
if (typeof callback == 'function') {
callback.call(this);
}
return this;
},
/**
* Hides the node.
* If the "transition" module is loaded, hide optionally
* animates the hiding of the node using either the default
* transition effect ('fadeOut'), or the given named effect.
* @method hide
* @param {String} name A named Transition effect to use as the show effect.
* @param {Object} config Options to use with the transition.
* @param {Function} callback An optional function to run after the transition completes.
* @chainable
*/
hide: function(callback) {
callback = arguments[arguments.length - 1];
this.toggleView(false, callback);
return this;
},
/**
* The implementation for hiding nodes.
* Default is to set the hidden attribute to true and set the CSS style.display to 'none'.
* @method _hide
* @protected
* @chainable
*/
_hide: function() {
this.setAttribute('hidden', true);
// For back-compat we need to leave this in for browsers that
// do not visually hide a node via the hidden attribute
// and for users that check visibility based on style display.
this.setStyle('display', 'none');
}
});
Y.NodeList.importMethod(Y.Node.prototype, [
/**
* Makes each node visible.
* If the "transition" module is loaded, show optionally
* animates the showing of the node using either the default
* transition effect ('fadeIn'), or the given named effect.
* @method show
* @param {String} name A named Transition effect to use as the show effect.
* @param {Object} config Options to use with the transition.
* @param {Function} callback An optional function to run after the transition completes.
* @for NodeList
* @chainable
*/
'show',
/**
* Hides each node.
* If the "transition" module is loaded, hide optionally
* animates the hiding of the node using either the default
* transition effect ('fadeOut'), or the given named effect.
* @method hide
* @param {String} name A named Transition effect to use as the show effect.
* @param {Object} config Options to use with the transition.
* @param {Function} callback An optional function to run after the transition completes.
* @chainable
*/
'hide',
/**
* Displays or hides each node.
* If the "transition" module is loaded, toggleView optionally
* animates the toggling of the nodes using given named effect.
* @method toggleView
* @param {String} [name] An optional string value to use as transition effect.
* @param {Boolean} [on] An optional boolean value to force the nodes to be shown or hidden
* @param {Function} [callback] An optional function to run after the transition completes.
* @chainable
*/
'toggleView'
]);
if (!Y.config.doc.documentElement.hasAttribute) { // IE < 8
Y.Node.prototype.hasAttribute = function(attr) {
if (attr === 'value') {
if (this.get('value') !== "") { // IE < 8 fails to populate specified when set in HTML
return true;
}
}
return !!(this._node.attributes[attr] &&
this._node.attributes[attr].specified);
};
}
// IE throws an error when calling focus() on an element that's invisible, not
// displayed, or disabled.
Y.Node.prototype.focus = function () {
try {
this._node.focus();
} catch (e) {
Y.log('error focusing node: ' + e.toString(), 'error', 'node');
}
return this;
};
// IE throws error when setting input.type = 'hidden',
// input.setAttribute('type', 'hidden') and input.attributes.type.value = 'hidden'
Y.Node.ATTRS.type = {
setter: function(val) {
if (val === 'hidden') {
try {
this._node.type = 'hidden';
} catch(e) {
this.setStyle('display', 'none');
this._inputType = 'hidden';
}
} else {
try { // IE errors when changing the type from "hidden'
this._node.type = val;
} catch (e) {
Y.log('error setting type: ' + val, 'info', 'node');
}
}
return val;
},
getter: function() {
return this._inputType || this._node.type;
},
_bypassProxy: true // don't update DOM when using with Attribute
};
if (Y.config.doc.createElement('form').elements.nodeType) {
// IE: elements collection is also FORM node which trips up scrubVal.
Y.Node.ATTRS.elements = {
getter: function() {
return this.all('input, textarea, button, select');
}
};
}
/**
* Provides methods for managing custom Node data.
*
* @module node
* @main node
* @submodule node-data
*/
Y.mix(Y.Node.prototype, {
_initData: function() {
if (! ('_data' in this)) {
this._data = {};
}
},
/**
* @method getData
* @for Node
* @description Retrieves arbitrary data stored on a Node instance.
* If no data is associated with the Node, it will attempt to retrieve
* a value from the corresponding HTML data attribute. (e.g. node.getData('foo')
* will check node.getAttribute('data-foo')).
* @param {string} name Optional name of the data field to retrieve.
* If no name is given, all data is returned.
* @return {any | Object} Whatever is stored at the given field,
* or an object hash of all fields.
*/
getData: function(name) {
this._initData();
var data = this._data,
ret = data;
if (arguments.length) { // single field
if (name in data) {
ret = data[name];
} else { // initialize from HTML attribute
ret = this._getDataAttribute(name);
}
} else if (typeof data == 'object' && data !== null) { // all fields
ret = {};
Y.Object.each(data, function(v, n) {
ret[n] = v;
});
ret = this._getDataAttributes(ret);
}
return ret;
},
_getDataAttributes: function(ret) {
ret = ret || {};
var i = 0,
attrs = this._node.attributes,
len = attrs.length,
prefix = this.DATA_PREFIX,
prefixLength = prefix.length,
name;
while (i < len) {
name = attrs[i].name;
if (name.indexOf(prefix) === 0) {
name = name.substr(prefixLength);
if (!(name in ret)) { // only merge if not already stored
ret[name] = this._getDataAttribute(name);
}
}
i += 1;
}
return ret;
},
_getDataAttribute: function(name) {
name = this.DATA_PREFIX + name;
var node = this._node,
attrs = node.attributes,
data = attrs && attrs[name] && attrs[name].value;
return data;
},
/**
* @method setData
* @for Node
* @description Stores arbitrary data on a Node instance.
* This is not stored with the DOM node.
* @param {string} name The name of the field to set. If no val
* is given, name is treated as the data and overrides any existing data.
* @param {any} val The value to be assigned to the field.
* @chainable
*/
setData: function(name, val) {
this._initData();
if (arguments.length > 1) {
this._data[name] = val;
} else {
this._data = name;
}
return this;
},
/**
* @method clearData
* @for Node
* @description Clears internally stored data.
* @param {string} name The name of the field to clear. If no name
* is given, all data is cleared.
* @chainable
*/
clearData: function(name) {
if ('_data' in this) {
if (typeof name != 'undefined') {
delete this._data[name];
} else {
delete this._data;
}
}
return this;
}
});
Y.mix(Y.NodeList.prototype, {
/**
* @method getData
* @for NodeList
* @description Retrieves arbitrary data stored on each Node instance
* bound to the NodeList.
* @see Node
* @param {string} name Optional name of the data field to retrieve.
* If no name is given, all data is returned.
* @return {Array} An array containing all of the data for each Node instance.
* or an object hash of all fields.
*/
getData: function(name) {
var args = (arguments.length) ? [name] : [];
return this._invoke('getData', args, true);
},
/**
* @method setData
* @for NodeList
* @description Stores arbitrary data on each Node instance bound to the
* NodeList. This is not stored with the DOM node.
* @param {string} name The name of the field to set. If no name
* is given, name is treated as the data and overrides any existing data.
* @param {any} val The value to be assigned to the field.
* @chainable
*/
setData: function(name, val) {
var args = (arguments.length > 1) ? [name, val] : [name];
return this._invoke('setData', args);
},
/**
* @method clearData
* @for NodeList
* @description Clears data on all Node instances bound to the NodeList.
* @param {string} name The name of the field to clear. If no name
* is given, all data is cleared.
* @chainable
*/
clearData: function(name) {
var args = (arguments.length) ? [name] : [];
return this._invoke('clearData', [name]);
}
});
}, '@VERSION@', {"requires": ["event-base", "node-core", "dom-base"]});
(function () {
var GLOBAL_ENV = YUI.Env;
if (!GLOBAL_ENV._ready) {
GLOBAL_ENV._ready = function() {
GLOBAL_ENV.DOMReady = true;
GLOBAL_ENV.remove(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready);
};
GLOBAL_ENV.add(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready);
}
})();
YUI.add('event-base', function (Y, NAME) {
/*
* DOM event listener abstraction layer
* @module event
* @submodule event-base
*/
/**
* The domready event fires at the moment the browser's DOM is
* usable. In most cases, this is before images are fully
* downloaded, allowing you to provide a more responsive user
* interface.
*
* In YUI 3, domready subscribers will be notified immediately if
* that moment has already passed when the subscription is created.
*
* One exception is if the yui.js file is dynamically injected into
* the page. If this is done, you must tell the YUI instance that
* you did this in order for DOMReady (and window load events) to
* fire normally. That configuration option is 'injected' -- set
* it to true if the yui.js script is not included inline.
*
* This method is part of the 'event-ready' module, which is a
* submodule of 'event'.
*
* @event domready
* @for YUI
*/
Y.publish('domready', {
fireOnce: true,
async: true
});
if (YUI.Env.DOMReady) {
Y.fire('domready');
} else {
Y.Do.before(function() { Y.fire('domready'); }, YUI.Env, '_ready');
}
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event
* @submodule event-base
*/
/**
* Wraps a DOM event, properties requiring browser abstraction are
* fixed here. Provids a security layer when required.
* @class DOMEventFacade
* @param ev {Event} the DOM event
* @param currentTarget {HTMLElement} the element the listener was attached to
* @param wrapper {Event.Custom} the custom event wrapper for this DOM event
*/
var ua = Y.UA,
EMPTY = {},
/**
* webkit key remapping required for Safari < 3.1
* @property webkitKeymap
* @private
*/
webkitKeymap = {
63232: 38, // up
63233: 40, // down
63234: 37, // left
63235: 39, // right
63276: 33, // page up
63277: 34, // page down
25: 9, // SHIFT-TAB (Safari provides a different key code in
// this case, even though the shiftKey modifier is set)
63272: 46, // delete
63273: 36, // home
63275: 35 // end
},
/**
* Returns a wrapped node. Intended to be used on event targets,
* so it will return the node's parent if the target is a text
* node.
*
* If accessing a property of the node throws an error, this is
* probably the anonymous div wrapper Gecko adds inside text
* nodes. This likely will only occur when attempting to access
* the relatedTarget. In this case, we now return null because
* the anonymous div is completely useless and we do not know
* what the related target was because we can't even get to
* the element's parent node.
*
* @method resolve
* @private
*/
resolve = function(n) {
if (!n) {
return n;
}
try {
if (n && 3 == n.nodeType) {
n = n.parentNode;
}
} catch(e) {
return null;
}
return Y.one(n);
},
DOMEventFacade = function(ev, currentTarget, wrapper) {
this._event = ev;
this._currentTarget = currentTarget;
this._wrapper = wrapper || EMPTY;
// if not lazy init
this.init();
};
Y.extend(DOMEventFacade, Object, {
init: function() {
var e = this._event,
overrides = this._wrapper.overrides,
x = e.pageX,
y = e.pageY,
c,
currentTarget = this._currentTarget;
this.altKey = e.altKey;
this.ctrlKey = e.ctrlKey;
this.metaKey = e.metaKey;
this.shiftKey = e.shiftKey;
this.type = (overrides && overrides.type) || e.type;
this.clientX = e.clientX;
this.clientY = e.clientY;
this.pageX = x;
this.pageY = y;
// charCode is unknown in keyup, keydown. keyCode is unknown in keypress.
// FF 3.6 - 8+? pass 0 for keyCode in keypress events.
// Webkit, FF 3.6-8+?, and IE9+? pass 0 for charCode in keydown, keyup.
// Webkit and IE9+? duplicate charCode in keyCode.
// Opera never sets charCode, always keyCode (though with the charCode).
// IE6-8 don't set charCode or which.
// All browsers other than IE6-8 set which=keyCode in keydown, keyup, and
// which=charCode in keypress.
//
// Moral of the story: (e.which || e.keyCode) will always return the
// known code for that key event phase. e.keyCode is often different in
// keypress from keydown and keyup.
c = e.keyCode || e.charCode;
if (ua.webkit && (c in webkitKeymap)) {
c = webkitKeymap[c];
}
this.keyCode = c;
this.charCode = c;
// Fill in e.which for IE - implementers should always use this over
// e.keyCode or e.charCode.
this.which = e.which || e.charCode || c;
// this.button = e.button;
this.button = this.which;
this.target = resolve(e.target);
this.currentTarget = resolve(currentTarget);
this.relatedTarget = resolve(e.relatedTarget);
if (e.type == "mousewheel" || e.type == "DOMMouseScroll") {
this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1);
}
if (this._touch) {
this._touch(e, currentTarget, this._wrapper);
}
},
stopPropagation: function() {
this._event.stopPropagation();
this._wrapper.stopped = 1;
this.stopped = 1;
},
stopImmediatePropagation: function() {
var e = this._event;
if (e.stopImmediatePropagation) {
e.stopImmediatePropagation();
} else {
this.stopPropagation();
}
this._wrapper.stopped = 2;
this.stopped = 2;
},
preventDefault: function(returnValue) {
var e = this._event;
e.preventDefault();
e.returnValue = returnValue || false;
this._wrapper.prevented = 1;
this.prevented = 1;
},
halt: function(immediate) {
if (immediate) {
this.stopImmediatePropagation();
} else {
this.stopPropagation();
}
this.preventDefault();
}
});
DOMEventFacade.resolve = resolve;
Y.DOM2EventFacade = DOMEventFacade;
Y.DOMEventFacade = DOMEventFacade;
/**
* The native event
* @property _event
* @type {Native DOM Event}
* @private
*/
/**
The name of the event (e.g. "click")
@property type
@type {String}
**/
/**
`true` if the "alt" or "option" key is pressed.
@property altKey
@type {Boolean}
**/
/**
`true` if the shift key is pressed.
@property shiftKey
@type {Boolean}
**/
/**
`true` if the "Windows" key on a Windows keyboard, "command" key on an
Apple keyboard, or "meta" key on other keyboards is pressed.
@property metaKey
@type {Boolean}
**/
/**
`true` if the "Ctrl" or "control" key is pressed.
@property ctrlKey
@type {Boolean}
**/
/**
* The X location of the event on the page (including scroll)
* @property pageX
* @type {Number}
*/
/**
* The Y location of the event on the page (including scroll)
* @property pageY
* @type {Number}
*/
/**
* The X location of the event in the viewport
* @property clientX
* @type {Number}
*/
/**
* The Y location of the event in the viewport
* @property clientY
* @type {Number}
*/
/**
* The keyCode for key events. Uses charCode if keyCode is not available
* @property keyCode
* @type {Number}
*/
/**
* The charCode for key events. Same as keyCode
* @property charCode
* @type {Number}
*/
/**
* The button that was pushed. 1 for left click, 2 for middle click, 3 for
* right click. This is only reliably populated on `mouseup` events.
* @property button
* @type {Number}
*/
/**
* The button that was pushed. Same as button.
* @property which
* @type {Number}
*/
/**
* Node reference for the targeted element
* @property target
* @type {Node}
*/
/**
* Node reference for the element that the listener was attached to.
* @property currentTarget
* @type {Node}
*/
/**
* Node reference to the relatedTarget
* @property relatedTarget
* @type {Node}
*/
/**
* Number representing the direction and velocity of the movement of the mousewheel.
* Negative is down, the higher the number, the faster. Applies to the mousewheel event.
* @property wheelDelta
* @type {Number}
*/
/**
* Stops the propagation to the next bubble target
* @method stopPropagation
*/
/**
* Stops the propagation to the next bubble target and
* prevents any additional listeners from being exectued
* on the current target.
* @method stopImmediatePropagation
*/
/**
* Prevents the event's default behavior
* @method preventDefault
* @param returnValue {string} sets the returnValue of the event to this value
* (rather than the default false value). This can be used to add a customized
* confirmation query to the beforeunload event).
*/
/**
* Stops the event propagation and prevents the default
* event behavior.
* @method halt
* @param immediate {boolean} if true additional listeners
* on the current target will not be executed
*/
(function() {
/**
* The event utility provides functions to add and remove event listeners,
* event cleansing. It also tries to automatically remove listeners it
* registers during the unload event.
* @module event
* @main event
* @submodule event-base
*/
/**
* The event utility provides functions to add and remove event listeners,
* event cleansing. It also tries to automatically remove listeners it
* registers during the unload event.
*
* @class Event
* @static
*/
Y.Env.evt.dom_wrappers = {};
Y.Env.evt.dom_map = {};
var _eventenv = Y.Env.evt,
config = Y.config,
win = config.win,
add = YUI.Env.add,
remove = YUI.Env.remove,
onLoad = function() {
YUI.Env.windowLoaded = true;
Y.Event._load();
remove(win, "load", onLoad);
},
onUnload = function() {
Y.Event._unload();
},
EVENT_READY = 'domready',
COMPAT_ARG = '~yui|2|compat~',
shouldIterate = function(o) {
try {
// TODO: See if there's a more performant way to return true early on this, for the common case
return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !Y.DOM.isWindow(o));
} catch(ex) {
Y.log("collection check failure", "warn", "event");
return false;
}
},
// aliases to support DOM event subscription clean up when the last
// subscriber is detached. deleteAndClean overrides the DOM event's wrapper
// CustomEvent _delete method.
_ceProtoDelete = Y.CustomEvent.prototype._delete,
_deleteAndClean = function(s) {
var ret = _ceProtoDelete.apply(this, arguments);
if (!this.hasSubs()) {
Y.Event._clean(this);
}
return ret;
},
Event = function() {
/**
* True after the onload event has fired
* @property _loadComplete
* @type boolean
* @static
* @private
*/
var _loadComplete = false,
/**
* The number of times to poll after window.onload. This number is
* increased if additional late-bound handlers are requested after
* the page load.
* @property _retryCount
* @static
* @private
*/
_retryCount = 0,
/**
* onAvailable listeners
* @property _avail
* @static
* @private
*/
_avail = [],
/**
* Custom event wrappers for DOM events. Key is
* 'event:' + Element uid stamp + event type
* @property _wrappers
* @type Y.Event.Custom
* @static
* @private
*/
_wrappers = _eventenv.dom_wrappers,
_windowLoadKey = null,
/**
* Custom event wrapper map DOM events. Key is
* Element uid stamp. Each item is a hash of custom event
* wrappers as provided in the _wrappers collection. This
* provides the infrastructure for getListeners.
* @property _el_events
* @static
* @private
*/
_el_events = _eventenv.dom_map;
return {
/**
* The number of times we should look for elements that are not
* in the DOM at the time the event is requested after the document
* has been loaded. The default is 1000@amp;40 ms, so it will poll
* for 40 seconds or until all outstanding handlers are bound
* (whichever comes first).
* @property POLL_RETRYS
* @type int
* @static
* @final
*/
POLL_RETRYS: 1000,
/**
* The poll interval in milliseconds
* @property POLL_INTERVAL
* @type int
* @static
* @final
*/
POLL_INTERVAL: 40,
/**
* addListener/removeListener can throw errors in unexpected scenarios.
* These errors are suppressed, the method returns false, and this property
* is set
* @property lastError
* @static
* @type Error
*/
lastError: null,
/**
* poll handle
* @property _interval
* @static
* @private
*/
_interval: null,
/**
* document readystate poll handle
* @property _dri
* @static
* @private
*/
_dri: null,
/**
* True when the document is initially usable
* @property DOMReady
* @type boolean
* @static
*/
DOMReady: false,
/**
* @method startInterval
* @static
* @private
*/
startInterval: function() {
if (!Event._interval) {
Event._interval = setInterval(Event._poll, Event.POLL_INTERVAL);
}
},
/**
* Executes the supplied callback when the item with the supplied
* id is found. This is meant to be used to execute behavior as
* soon as possible as the page loads. If you use this after the
* initial page load it will poll for a fixed time for the element.
* The number of times it will poll and the frequency are
* configurable. By default it will poll for 10 seconds.
*
* <p>The callback is executed with a single parameter:
* the custom object parameter, if provided.</p>
*
* @method onAvailable
*
* @param {string||string[]} id the id of the element, or an array
* of ids to look for.
* @param {function} fn what to execute when the element is found.
* @param {object} p_obj an optional object to be passed back as
* a parameter to fn.
* @param {boolean|object} p_override If set to true, fn will execute
* in the context of p_obj, if set to an object it
* will execute in the context of that object
* @param checkContent {boolean} check child node readiness (onContentReady)
* @static
* @deprecated Use Y.on("available")
*/
// @TODO fix arguments
onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) {
var a = Y.Array(id), i, availHandle;
// Y.log('onAvailable registered for: ' + id);
for (i=0; i<a.length; i=i+1) {
_avail.push({
id: a[i],
fn: fn,
obj: p_obj,
override: p_override,
checkReady: checkContent,
compat: compat
});
}
_retryCount = this.POLL_RETRYS;
// We want the first test to be immediate, but async
setTimeout(Event._poll, 0);
availHandle = new Y.EventHandle({
_delete: function() {
// set by the event system for lazy DOM listeners
if (availHandle.handle) {
availHandle.handle.detach();
return;
}
var i, j;
// otherwise try to remove the onAvailable listener(s)
for (i = 0; i < a.length; i++) {
for (j = 0; j < _avail.length; j++) {
if (a[i] === _avail[j].id) {
_avail.splice(j, 1);
}
}
}
}
});
return availHandle;
},
/**
* Works the same way as onAvailable, but additionally checks the
* state of sibling elements to determine if the content of the
* available element is safe to modify.
*
* <p>The callback is executed with a single parameter:
* the custom object parameter, if provided.</p>
*
* @method onContentReady
*
* @param {string} id the id of the element to look for.
* @param {function} fn what to execute when the element is ready.
* @param {object} obj an optional object to be passed back as
* a parameter to fn.
* @param {boolean|object} override If set to true, fn will execute
* in the context of p_obj. If an object, fn will
* exectute in the context of that object
*
* @static
* @deprecated Use Y.on("contentready")
*/
// @TODO fix arguments
onContentReady: function(id, fn, obj, override, compat) {
return Event.onAvailable(id, fn, obj, override, true, compat);
},
/**
* Adds an event listener
*
* @method attach
*
* @param {String} type The type of event to append
* @param {Function} fn The method the event invokes
* @param {String|HTMLElement|Array|NodeList} el An id, an element
* reference, or a collection of ids and/or elements to assign the
* listener to.
* @param {Object} context optional context object
* @param {Boolean|object} args 0..n arguments to pass to the callback
* @return {EventHandle} an object to that can be used to detach the listener
*
* @static
*/
attach: function(type, fn, el, context) {
return Event._attach(Y.Array(arguments, 0, true));
},
_createWrapper: function (el, type, capture, compat, facade) {
var cewrapper,
ek = Y.stamp(el),
key = 'event:' + ek + type;
if (false === facade) {
key += 'native';
}
if (capture) {
key += 'capture';
}
cewrapper = _wrappers[key];
if (!cewrapper) {
// create CE wrapper
cewrapper = Y.publish(key, {
silent: true,
bubbles: false,
emitFacade:false,
contextFn: function() {
if (compat) {
return cewrapper.el;
} else {
cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el);
return cewrapper.nodeRef;
}
}
});
cewrapper.overrides = {};
// for later removeListener calls
cewrapper.el = el;
cewrapper.key = key;
cewrapper.domkey = ek;
cewrapper.type = type;
cewrapper.fn = function(e) {
cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade))));
};
cewrapper.capture = capture;
if (el == win && type == "load") {
// window load happens once
cewrapper.fireOnce = true;
_windowLoadKey = key;
}
cewrapper._delete = _deleteAndClean;
_wrappers[key] = cewrapper;
_el_events[ek] = _el_events[ek] || {};
_el_events[ek][key] = cewrapper;
add(el, type, cewrapper.fn, capture);
}
return cewrapper;
},
_attach: function(args, conf) {
var compat,
handles, oEl, cewrapper, context,
fireNow = false, ret,
type = args[0],
fn = args[1],
el = args[2] || win,
facade = conf && conf.facade,
capture = conf && conf.capture,
overrides = conf && conf.overrides;
if (args[args.length-1] === COMPAT_ARG) {
compat = true;
}
if (!fn || !fn.call) {
// throw new TypeError(type + " attach call failed, callback undefined");
Y.log(type + " attach call failed, invalid callback", "error", "event");
return false;
}
// The el argument can be an array of elements or element ids.
if (shouldIterate(el)) {
handles=[];
Y.each(el, function(v, k) {
args[2] = v;
handles.push(Event._attach(args.slice(), conf));
});
// return (handles.length === 1) ? handles[0] : handles;
return new Y.EventHandle(handles);
// If the el argument is a string, we assume it is
// actually the id of the element. If the page is loaded
// we convert el to the actual element, otherwise we
// defer attaching the event until the element is
// ready
} else if (Y.Lang.isString(el)) {
// oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el);
if (compat) {
oEl = Y.DOM.byId(el);
} else {
oEl = Y.Selector.query(el);
switch (oEl.length) {
case 0:
oEl = null;
break;
case 1:
oEl = oEl[0];
break;
default:
args[2] = oEl;
return Event._attach(args, conf);
}
}
if (oEl) {
el = oEl;
// Not found = defer adding the event until the element is available
} else {
// Y.log(el + ' not found');
ret = Event.onAvailable(el, function() {
// Y.log('lazy attach: ' + args);
ret.handle = Event._attach(args, conf);
}, Event, true, false, compat);
return ret;
}
}
// Element should be an html element or node
if (!el) {
Y.log("unable to attach event " + type, "warn", "event");
return false;
}
if (Y.Node && Y.instanceOf(el, Y.Node)) {
el = Y.Node.getDOMNode(el);
}
cewrapper = Event._createWrapper(el, type, capture, compat, facade);
if (overrides) {
Y.mix(cewrapper.overrides, overrides);
}
if (el == win && type == "load") {
// if the load is complete, fire immediately.
// all subscribers, including the current one
// will be notified.
if (YUI.Env.windowLoaded) {
fireNow = true;
}
}
if (compat) {
args.pop();
}
context = args[3];
// set context to the Node if not specified
// ret = cewrapper.on.apply(cewrapper, trimmedArgs);
ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null);
if (fireNow) {
cewrapper.fire();
}
return ret;
},
/**
* Removes an event listener. Supports the signature the event was bound
* with, but the preferred way to remove listeners is using the handle
* that is returned when using Y.on
*
* @method detach
*
* @param {String} type the type of event to remove.
* @param {Function} fn the method the event invokes. If fn is
* undefined, then all event handlers for the type of event are
* removed.
* @param {String|HTMLElement|Array|NodeList|EventHandle} el An
* event handle, an id, an element reference, or a collection
* of ids and/or elements to remove the listener from.
* @return {boolean} true if the unbind was successful, false otherwise.
* @static
*/
detach: function(type, fn, el, obj) {
var args=Y.Array(arguments, 0, true), compat, l, ok, i,
id, ce;
if (args[args.length-1] === COMPAT_ARG) {
compat = true;
// args.pop();
}
if (type && type.detach) {
return type.detach();
}
// The el argument can be a string
if (typeof el == "string") {
// el = (compat) ? Y.DOM.byId(el) : Y.all(el);
if (compat) {
el = Y.DOM.byId(el);
} else {
el = Y.Selector.query(el);
l = el.length;
if (l < 1) {
el = null;
} else if (l == 1) {
el = el[0];
}
}
// return Event.detach.apply(Event, args);
}
if (!el) {
return false;
}
if (el.detach) {
args.splice(2, 1);
return el.detach.apply(el, args);
// The el argument can be an array of elements or element ids.
} else if (shouldIterate(el)) {
ok = true;
for (i=0, l=el.length; i<l; ++i) {
args[2] = el[i];
ok = ( Y.Event.detach.apply(Y.Event, args) && ok );
}
return ok;
}
if (!type || !fn || !fn.call) {
return Event.purgeElement(el, false, type);
}
id = 'event:' + Y.stamp(el) + type;
ce = _wrappers[id];
if (ce) {
return ce.detach(fn);
} else {
return false;
}
},
/**
* Finds the event in the window object, the caller's arguments, or
* in the arguments of another method in the callstack. This is
* executed automatically for events registered through the event
* manager, so the implementer should not normally need to execute
* this function at all.
* @method getEvent
* @param {Event} e the event parameter from the handler
* @param {HTMLElement} el the element the listener was attached to
* @return {Event} the event
* @static
*/
getEvent: function(e, el, noFacade) {
var ev = e || win.event;
return (noFacade) ? ev :
new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]);
},
/**
* Generates an unique ID for the element if it does not already
* have one.
* @method generateId
* @param el the element to create the id for
* @return {string} the resulting id of the element
* @static
*/
generateId: function(el) {
return Y.DOM.generateID(el);
},
/**
* We want to be able to use getElementsByTagName as a collection
* to attach a group of events to. Unfortunately, different
* browsers return different types of collections. This function
* tests to determine if the object is array-like. It will also
* fail if the object is an array, but is empty.
* @method _isValidCollection
* @param o the object to test
* @return {boolean} true if the object is array-like and populated
* @deprecated was not meant to be used directly
* @static
* @private
*/
_isValidCollection: shouldIterate,
/**
* hook up any deferred listeners
* @method _load
* @static
* @private
*/
_load: function(e) {
if (!_loadComplete) {
// Y.log('Load Complete', 'info', 'event');
_loadComplete = true;
// Just in case DOMReady did not go off for some reason
// E._ready();
if (Y.fire) {
Y.fire(EVENT_READY);
}
// Available elements may not have been detected before the
// window load event fires. Try to find them now so that the
// the user is more likely to get the onAvailable notifications
// before the window load notification
Event._poll();
}
},
/**
* Polling function that runs before the onload event fires,
* attempting to attach to DOM Nodes as soon as they are
* available
* @method _poll
* @static
* @private
*/
_poll: function() {
if (Event.locked) {
return;
}
if (Y.UA.ie && !YUI.Env.DOMReady) {
// Hold off if DOMReady has not fired and check current
// readyState to protect against the IE operation aborted
// issue.
Event.startInterval();
return;
}
Event.locked = true;
// Y.log.debug("poll");
// keep trying until after the page is loaded. We need to
// check the page load state prior to trying to bind the
// elements so that we can be certain all elements have been
// tested appropriately
var i, len, item, el, notAvail, executeItem,
tryAgain = !_loadComplete;
if (!tryAgain) {
tryAgain = (_retryCount > 0);
}
// onAvailable
notAvail = [];
executeItem = function (el, item) {
var context, ov = item.override;
try {
if (item.compat) {
if (item.override) {
if (ov === true) {
context = item.obj;
} else {
context = ov;
}
} else {
context = el;
}
item.fn.call(context, item.obj);
} else {
context = item.obj || Y.one(el);
item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []);
}
} catch (e) {
Y.log("Error in available or contentReady callback", 'error', 'event');
}
};
// onAvailable
for (i=0,len=_avail.length; i<len; ++i) {
item = _avail[i];
if (item && !item.checkReady) {
// el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id);
el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true);
if (el) {
// Y.log('avail: ' + el);
executeItem(el, item);
_avail[i] = null;
} else {
// Y.log('NOT avail: ' + el);
notAvail.push(item);
}
}
}
// onContentReady
for (i=0,len=_avail.length; i<len; ++i) {
item = _avail[i];
if (item && item.checkReady) {
// el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id);
el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true);
if (el) {
// The element is available, but not necessarily ready
// @todo should we test parentNode.nextSibling?
if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) {
executeItem(el, item);
_avail[i] = null;
}
} else {
notAvail.push(item);
}
}
}
_retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1;
if (tryAgain) {
// we may need to strip the nulled out items here
Event.startInterval();
} else {
clearInterval(Event._interval);
Event._interval = null;
}
Event.locked = false;
return;
},
/**
* Removes all listeners attached to the given element via addListener.
* Optionally, the node's children can also be purged.
* Optionally, you can specify a specific type of event to remove.
* @method purgeElement
* @param {HTMLElement} el the element to purge
* @param {boolean} recurse recursively purge this element's children
* as well. Use with caution.
* @param {string} type optional type of listener to purge. If
* left out, all listeners will be removed
* @static
*/
purgeElement: function(el, recurse, type) {
// var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el,
var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el,
lis = Event.getListeners(oEl, type), i, len, children, child;
if (recurse && oEl) {
lis = lis || [];
children = Y.Selector.query('*', oEl);
len = children.length;
for (i = 0; i < len; ++i) {
child = Event.getListeners(children[i], type);
if (child) {
lis = lis.concat(child);
}
}
}
if (lis) {
for (i = 0, len = lis.length; i < len; ++i) {
lis[i].detachAll();
}
}
},
/**
* Removes all object references and the DOM proxy subscription for
* a given event for a DOM node.
*
* @method _clean
* @param wrapper {CustomEvent} Custom event proxy for the DOM
* subscription
* @private
* @static
* @since 3.4.0
*/
_clean: function (wrapper) {
var key = wrapper.key,
domkey = wrapper.domkey;
remove(wrapper.el, wrapper.type, wrapper.fn, wrapper.capture);
delete _wrappers[key];
delete Y._yuievt.events[key];
if (_el_events[domkey]) {
delete _el_events[domkey][key];
if (!Y.Object.size(_el_events[domkey])) {
delete _el_events[domkey];
}
}
},
/**
* Returns all listeners attached to the given element via addListener.
* Optionally, you can specify a specific type of event to return.
* @method getListeners
* @param el {HTMLElement|string} the element or element id to inspect
* @param type {string} optional type of listener to return. If
* left out, all listeners will be returned
* @return {CustomEvent} the custom event wrapper for the DOM event(s)
* @static
*/
getListeners: function(el, type) {
var ek = Y.stamp(el, true), evts = _el_events[ek],
results=[] , key = (type) ? 'event:' + ek + type : null,
adapters = _eventenv.plugins;
if (!evts) {
return null;
}
if (key) {
// look for synthetic events
if (adapters[type] && adapters[type].eventDef) {
key += '_synth';
}
if (evts[key]) {
results.push(evts[key]);
}
// get native events as well
key += 'native';
if (evts[key]) {
results.push(evts[key]);
}
} else {
Y.each(evts, function(v, k) {
results.push(v);
});
}
return (results.length) ? results : null;
},
/**
* Removes all listeners registered by pe.event. Called
* automatically during the unload event.
* @method _unload
* @static
* @private
*/
_unload: function(e) {
Y.each(_wrappers, function(v, k) {
if (v.type == 'unload') {
v.fire(e);
}
v.detachAll();
});
remove(win, "unload", onUnload);
},
/**
* Adds a DOM event directly without the caching, cleanup, context adj, etc
*
* @method nativeAdd
* @param {HTMLElement} el the element to bind the handler to
* @param {string} type the type of event handler
* @param {function} fn the callback to invoke
* @param {boolen} capture capture or bubble phase
* @static
* @private
*/
nativeAdd: add,
/**
* Basic remove listener
*
* @method nativeRemove
* @param {HTMLElement} el the element to bind the handler to
* @param {string} type the type of event handler
* @param {function} fn the callback to invoke
* @param {boolen} capture capture or bubble phase
* @static
* @private
*/
nativeRemove: remove
};
}();
Y.Event = Event;
if (config.injected || YUI.Env.windowLoaded) {
onLoad();
} else {
add(win, "load", onLoad);
}
// Process onAvailable/onContentReady items when when the DOM is ready in IE
if (Y.UA.ie) {
Y.on(EVENT_READY, Event._poll);
}
try {
add(win, "unload", onUnload);
} catch(e) {
/*jshint maxlen:300*/
Y.log("Registering unload listener failed. This is known to happen in Chrome Packaged Apps and Extensions, which don't support unload, and don't provide a way to test for support", "warn", "event-base");
}
Event.Custom = Y.CustomEvent;
Event.Subscriber = Y.Subscriber;
Event.Target = Y.EventTarget;
Event.Handle = Y.EventHandle;
Event.Facade = Y.EventFacade;
Event._poll();
}());
/**
* DOM event listener abstraction layer
* @module event
* @submodule event-base
*/
/**
* Executes the callback as soon as the specified element
* is detected in the DOM. This function expects a selector
* string for the element(s) to detect. If you already have
* an element reference, you don't need this event.
* @event available
* @param type {string} 'available'
* @param fn {function} the callback function to execute.
* @param el {string} an selector for the element(s) to attach
* @param context optional argument that specifies what 'this' refers to.
* @param args* 0..n additional arguments to pass on to the callback function.
* These arguments will be added after the event object.
* @return {EventHandle} the detach handle
* @for YUI
*/
Y.Env.evt.plugins.available = {
on: function(type, fn, id, o) {
var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null;
return Y.Event.onAvailable.call(Y.Event, id, fn, o, a);
}
};
/**
* Executes the callback as soon as the specified element
* is detected in the DOM with a nextSibling property
* (indicating that the element's children are available).
* This function expects a selector
* string for the element(s) to detect. If you already have
* an element reference, you don't need this event.
* @event contentready
* @param type {string} 'contentready'
* @param fn {function} the callback function to execute.
* @param el {string} an selector for the element(s) to attach.
* @param context optional argument that specifies what 'this' refers to.
* @param args* 0..n additional arguments to pass on to the callback function.
* These arguments will be added after the event object.
* @return {EventHandle} the detach handle
* @for YUI
*/
Y.Env.evt.plugins.contentready = {
on: function(type, fn, id, o) {
var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null;
return Y.Event.onContentReady.call(Y.Event, id, fn, o, a);
}
};
}, '@VERSION@', {"requires": ["event-custom-base"]});
(function() {
var stateChangeListener,
GLOBAL_ENV = YUI.Env,
config = YUI.config,
doc = config.doc,
docElement = doc && doc.documentElement,
EVENT_NAME = 'onreadystatechange',
pollInterval = config.pollInterval || 40;
if (docElement.doScroll && !GLOBAL_ENV._ieready) {
GLOBAL_ENV._ieready = function() {
GLOBAL_ENV._ready();
};
/*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller/Diego Perini */
// Internet Explorer: use the doScroll() method on the root element.
// This isolates what appears to be a safe moment to manipulate the
// DOM prior to when the document's readyState suggests it is safe to do so.
if (self !== self.top) {
stateChangeListener = function() {
if (doc.readyState == 'complete') {
GLOBAL_ENV.remove(doc, EVENT_NAME, stateChangeListener);
GLOBAL_ENV.ieready();
}
};
GLOBAL_ENV.add(doc, EVENT_NAME, stateChangeListener);
} else {
GLOBAL_ENV._dri = setInterval(function() {
try {
docElement.doScroll('left');
clearInterval(GLOBAL_ENV._dri);
GLOBAL_ENV._dri = null;
GLOBAL_ENV._ieready();
} catch (domNotReady) { }
}, pollInterval);
}
}
})();
YUI.add('event-base-ie', function (Y, NAME) {
/*
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event
* @submodule event-base
*/
function IEEventFacade() {
// IEEventFacade.superclass.constructor.apply(this, arguments);
Y.DOM2EventFacade.apply(this, arguments);
}
/*
* (intentially left out of API docs)
* Alternate Facade implementation that is based on Object.defineProperty, which
* is partially supported in IE8. Properties that involve setup work are
* deferred to temporary getters using the static _define method.
*/
function IELazyFacade(e) {
var proxy = Y.config.doc.createEventObject(e),
proto = IELazyFacade.prototype;
// TODO: necessary?
proxy.hasOwnProperty = function () { return true; };
proxy.init = proto.init;
proxy.halt = proto.halt;
proxy.preventDefault = proto.preventDefault;
proxy.stopPropagation = proto.stopPropagation;
proxy.stopImmediatePropagation = proto.stopImmediatePropagation;
Y.DOM2EventFacade.apply(proxy, arguments);
return proxy;
}
var imp = Y.config.doc && Y.config.doc.implementation,
useLazyFacade = Y.config.lazyEventFacade,
buttonMap = {
0: 1, // left click
4: 2, // middle click
2: 3 // right click
},
relatedTargetMap = {
mouseout: 'toElement',
mouseover: 'fromElement'
},
resolve = Y.DOM2EventFacade.resolve,
proto = {
init: function() {
IEEventFacade.superclass.init.apply(this, arguments);
var e = this._event,
x, y, d, b, de, t;
this.target = resolve(e.srcElement);
if (('clientX' in e) && (!x) && (0 !== x)) {
x = e.clientX;
y = e.clientY;
d = Y.config.doc;
b = d.body;
de = d.documentElement;
x += (de.scrollLeft || (b && b.scrollLeft) || 0);
y += (de.scrollTop || (b && b.scrollTop) || 0);
this.pageX = x;
this.pageY = y;
}
if (e.type == "mouseout") {
t = e.toElement;
} else if (e.type == "mouseover") {
t = e.fromElement;
}
// fallback to t.relatedTarget to support simulated events.
// IE doesn't support setting toElement or fromElement on generic
// events, so Y.Event.simulate sets relatedTarget instead.
this.relatedTarget = resolve(t || e.relatedTarget);
// which should contain the unicode key code if this is a key event.
// For click events, which is normalized for which mouse button was
// clicked.
this.which = // chained assignment
this.button = e.keyCode || buttonMap[e.button] || e.button;
},
stopPropagation: function() {
this._event.cancelBubble = true;
this._wrapper.stopped = 1;
this.stopped = 1;
},
stopImmediatePropagation: function() {
this.stopPropagation();
this._wrapper.stopped = 2;
this.stopped = 2;
},
preventDefault: function(returnValue) {
this._event.returnValue = returnValue || false;
this._wrapper.prevented = 1;
this.prevented = 1;
}
};
Y.extend(IEEventFacade, Y.DOM2EventFacade, proto);
Y.extend(IELazyFacade, Y.DOM2EventFacade, proto);
IELazyFacade.prototype.init = function () {
var e = this._event,
overrides = this._wrapper.overrides,
define = IELazyFacade._define,
lazyProperties = IELazyFacade._lazyProperties,
prop;
this.altKey = e.altKey;
this.ctrlKey = e.ctrlKey;
this.metaKey = e.metaKey;
this.shiftKey = e.shiftKey;
this.type = (overrides && overrides.type) || e.type;
this.clientX = e.clientX;
this.clientY = e.clientY;
this.keyCode = // chained assignment
this.charCode = e.keyCode;
this.which = // chained assignment
this.button = e.keyCode || buttonMap[e.button] || e.button;
for (prop in lazyProperties) {
if (lazyProperties.hasOwnProperty(prop)) {
define(this, prop, lazyProperties[prop]);
}
}
if (this._touch) {
this._touch(e, this._currentTarget, this._wrapper);
}
};
IELazyFacade._lazyProperties = {
target: function () {
return resolve(this._event.srcElement);
},
relatedTarget: function () {
var e = this._event,
targetProp = relatedTargetMap[e.type] || 'relatedTarget';
// fallback to t.relatedTarget to support simulated events.
// IE doesn't support setting toElement or fromElement on generic
// events, so Y.Event.simulate sets relatedTarget instead.
return resolve(e[targetProp] || e.relatedTarget);
},
currentTarget: function () {
return resolve(this._currentTarget);
},
wheelDelta: function () {
var e = this._event;
if (e.type === "mousewheel" || e.type === "DOMMouseScroll") {
return (e.detail) ?
(e.detail * -1) :
// wheelDelta between -80 and 80 result in -1 or 1
Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1);
}
},
pageX: function () {
var e = this._event,
val = e.pageX,
doc, bodyScroll, docScroll;
if (val === undefined) {
doc = Y.config.doc;
bodyScroll = doc.body && doc.body.scrollLeft;
docScroll = doc.documentElement.scrollLeft;
val = e.clientX + (docScroll || bodyScroll || 0);
}
return val;
},
pageY: function () {
var e = this._event,
val = e.pageY,
doc, bodyScroll, docScroll;
if (val === undefined) {
doc = Y.config.doc;
bodyScroll = doc.body && doc.body.scrollTop;
docScroll = doc.documentElement.scrollTop;
val = e.clientY + (docScroll || bodyScroll || 0);
}
return val;
}
};
/**
* Wrapper function for Object.defineProperty that creates a property whose
* value will be calulated only when asked for. After calculating the value,
* the getter wll be removed, so it will behave as a normal property beyond that
* point. A setter is also assigned so assigning to the property will clear
* the getter, so foo.prop = 'a'; foo.prop; won't trigger the getter,
* overwriting value 'a'.
*
* Used only by the DOMEventFacades used by IE8 when the YUI configuration
* <code>lazyEventFacade</code> is set to true.
*
* @method _define
* @param o {DOMObject} A DOM object to add the property to
* @param prop {String} The name of the new property
* @param valueFn {Function} The function that will return the initial, default
* value for the property.
* @static
* @private
*/
IELazyFacade._define = function (o, prop, valueFn) {
function val(v) {
var ret = (arguments.length) ? v : valueFn.call(this);
delete o[prop];
Object.defineProperty(o, prop, {
value: ret,
configurable: true,
writable: true
});
return ret;
}
Object.defineProperty(o, prop, {
get: val,
set: val,
configurable: true
});
};
if (imp && (!imp.hasFeature('Events', '2.0'))) {
if (useLazyFacade) {
// Make sure we can use the lazy facade logic
try {
Object.defineProperty(Y.config.doc.createEventObject(), 'z', {});
} catch (e) {
useLazyFacade = false;
}
}
Y.DOMEventFacade = (useLazyFacade) ? IELazyFacade : IEEventFacade;
}
}, '@VERSION@', {"requires": ["node-base"]});
YUI.add('pluginhost-base', function (Y, NAME) {
/**
* Provides the augmentable PluginHost interface, which can be added to any class.
* @module pluginhost
*/
/**
* Provides the augmentable PluginHost interface, which can be added to any class.
* @module pluginhost-base
*/
/**
* <p>
* An augmentable class, which provides the augmented class with the ability to host plugins.
* It adds <a href="#method_plug">plug</a> and <a href="#method_unplug">unplug</a> methods to the augmented class, which can
* be used to add or remove plugins from instances of the class.
* </p>
*
* <p>Plugins can also be added through the constructor configuration object passed to the host class' constructor using
* the "plugins" property. Supported values for the "plugins" property are those defined by the <a href="#method_plug">plug</a> method.
*
* For example the following code would add the AnimPlugin and IOPlugin to Overlay (the plugin host):
* <xmp>
* var o = new Overlay({plugins: [ AnimPlugin, {fn:IOPlugin, cfg:{section:"header"}}]});
* </xmp>
* </p>
* <p>
* Plug.Host's protected <a href="#method_initPlugins">_initPlugins</a> and <a href="#method_destroyPlugins">_destroyPlugins</a>
* methods should be invoked by the host class at the appropriate point in the host's lifecyle.
* </p>
*
* @class Plugin.Host
*/
var L = Y.Lang;
function PluginHost() {
this._plugins = {};
}
PluginHost.prototype = {
/**
* Adds a plugin to the host object. This will instantiate the
* plugin and attach it to the configured namespace on the host object.
*
* @method plug
* @chainable
* @param P {Function | Object |Array} Accepts the plugin class, or an
* object with a "fn" property specifying the plugin class and
* a "cfg" property specifying the configuration for the Plugin.
* <p>
* Additionally an Array can also be passed in, with the above function or
* object values, allowing the user to add multiple plugins in a single call.
* </p>
* @param config (Optional) If the first argument is the plugin class, the second argument
* can be the configuration for the plugin.
* @return {Base} A reference to the host object
*/
plug: function(Plugin, config) {
var i, ln, ns;
if (L.isArray(Plugin)) {
for (i = 0, ln = Plugin.length; i < ln; i++) {
this.plug(Plugin[i]);
}
} else {
if (Plugin && !L.isFunction(Plugin)) {
config = Plugin.cfg;
Plugin = Plugin.fn;
}
// Plugin should be fn by now
if (Plugin && Plugin.NS) {
ns = Plugin.NS;
config = config || {};
config.host = this;
if (this.hasPlugin(ns)) {
// Update config
if (this[ns].setAttrs) {
this[ns].setAttrs(config);
}
else { Y.log("Attempt to replug an already attached plugin, and we can't setAttrs, because it's not Attribute based: " + ns); }
} else {
// Create new instance
this[ns] = new Plugin(config);
this._plugins[ns] = Plugin;
}
}
else { Y.log("Attempt to plug in an invalid plugin. Host:" + this + ", Plugin:" + Plugin); }
}
return this;
},
/**
* Removes a plugin from the host object. This will destroy the
* plugin instance and delete the namespace from the host object.
*
* @method unplug
* @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided,
* all registered plugins are unplugged.
* @return {Base} A reference to the host object
* @chainable
*/
unplug: function(plugin) {
var ns = plugin,
plugins = this._plugins;
if (plugin) {
if (L.isFunction(plugin)) {
ns = plugin.NS;
if (ns && (!plugins[ns] || plugins[ns] !== plugin)) {
ns = null;
}
}
if (ns) {
if (this[ns]) {
if (this[ns].destroy) {
this[ns].destroy();
}
delete this[ns];
}
if (plugins[ns]) {
delete plugins[ns];
}
}
} else {
for (ns in this._plugins) {
if (this._plugins.hasOwnProperty(ns)) {
this.unplug(ns);
}
}
}
return this;
},
/**
* Determines if a plugin has plugged into this host.
*
* @method hasPlugin
* @param {String} ns The plugin's namespace
* @return {Plugin} Returns a truthy value (the plugin instance) if present, or undefined if not.
*/
hasPlugin : function(ns) {
return (this._plugins[ns] && this[ns]);
},
/**
* Initializes static plugins registered on the host (using the
* Base.plug static method) and any plugins passed to the
* instance through the "plugins" configuration property.
*
* @method _initPlugins
* @param {Config} config The configuration object with property name/value pairs.
* @private
*/
_initPlugins: function(config) {
this._plugins = this._plugins || {};
if (this._initConfigPlugins) {
this._initConfigPlugins(config);
}
},
/**
* Unplugs and destroys all plugins on the host
* @method _destroyPlugins
* @private
*/
_destroyPlugins: function() {
this.unplug();
}
};
Y.namespace("Plugin").Host = PluginHost;
}, '@VERSION@', {"requires": ["yui-base"]});
YUI.add('pluginhost-config', function (Y, NAME) {
/**
* Adds pluginhost constructor configuration and static configuration support
* @submodule pluginhost-config
*/
var PluginHost = Y.Plugin.Host,
L = Y.Lang;
/**
* A protected initialization method, used by the host class to initialize
* plugin configurations passed the constructor, through the config object.
*
* Host objects should invoke this method at the appropriate time in their
* construction lifecycle.
*
* @method _initConfigPlugins
* @param {Object} config The configuration object passed to the constructor
* @protected
* @for Plugin.Host
*/
PluginHost.prototype._initConfigPlugins = function(config) {
// Class Configuration
var classes = (this._getClasses) ? this._getClasses() : [this.constructor],
plug = [],
unplug = {},
constructor, i, classPlug, classUnplug, pluginClassName;
// TODO: Room for optimization. Can we apply statically/unplug in same pass?
for (i = classes.length - 1; i >= 0; i--) {
constructor = classes[i];
classUnplug = constructor._UNPLUG;
if (classUnplug) {
// subclasses over-write
Y.mix(unplug, classUnplug, true);
}
classPlug = constructor._PLUG;
if (classPlug) {
// subclasses over-write
Y.mix(plug, classPlug, true);
}
}
for (pluginClassName in plug) {
if (plug.hasOwnProperty(pluginClassName)) {
if (!unplug[pluginClassName]) {
this.plug(plug[pluginClassName]);
}
}
}
// User Configuration
if (config && config.plugins) {
this.plug(config.plugins);
}
};
/**
* Registers plugins to be instantiated at the class level (plugins
* which should be plugged into every instance of the class by default).
*
* @method plug
* @static
*
* @param {Function} hostClass The host class on which to register the plugins
* @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined)
* @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin
* @for Plugin.Host
*/
PluginHost.plug = function(hostClass, plugin, config) {
// Cannot plug into Base, since Plugins derive from Base [ will cause infinite recurrsion ]
var p, i, l, name;
if (hostClass !== Y.Base) {
hostClass._PLUG = hostClass._PLUG || {};
if (!L.isArray(plugin)) {
if (config) {
plugin = {fn:plugin, cfg:config};
}
plugin = [plugin];
}
for (i = 0, l = plugin.length; i < l;i++) {
p = plugin[i];
name = p.NAME || p.fn.NAME;
hostClass._PLUG[name] = p;
}
}
};
/**
* Unregisters any class level plugins which have been registered by the host class, or any
* other class in the hierarchy.
*
* @method unplug
* @static
*
* @param {Function} hostClass The host class from which to unregister the plugins
* @param {Function | Array} plugin The plugin class, or an array of plugin classes
* @for Plugin.Host
*/
PluginHost.unplug = function(hostClass, plugin) {
var p, i, l, name;
if (hostClass !== Y.Base) {
hostClass._UNPLUG = hostClass._UNPLUG || {};
if (!L.isArray(plugin)) {
plugin = [plugin];
}
for (i = 0, l = plugin.length; i < l; i++) {
p = plugin[i];
name = p.NAME;
if (!hostClass._PLUG[name]) {
hostClass._UNPLUG[name] = p;
} else {
delete hostClass._PLUG[name];
}
}
}
};
}, '@VERSION@', {"requires": ["pluginhost-base"]});
YUI.add('event-delegate', function (Y, NAME) {
/**
* Adds event delegation support to the library.
*
* @module event
* @submodule event-delegate
*/
var toArray = Y.Array,
YLang = Y.Lang,
isString = YLang.isString,
isObject = YLang.isObject,
isArray = YLang.isArray,
selectorTest = Y.Selector.test,
detachCategories = Y.Env.evt.handles;
/**
* <p>Sets up event delegation on a container element. The delegated event
* will use a supplied selector or filtering function to test if the event
* references at least one node that should trigger the subscription
* callback.</p>
*
* <p>Selector string filters will trigger the callback if the event originated
* from a node that matches it or is contained in a node that matches it.
* Function filters are called for each Node up the parent axis to the
* subscribing container node, and receive at each level the Node and the event
* object. The function should return true (or a truthy value) if that Node
* should trigger the subscription callback. Note, it is possible for filters
* to match multiple Nodes for a single event. In this case, the delegate
* callback will be executed for each matching Node.</p>
*
* <p>For each matching Node, the callback will be executed with its 'this'
* object set to the Node matched by the filter (unless a specific context was
* provided during subscription), and the provided event's
* <code>currentTarget</code> will also be set to the matching Node. The
* containing Node from which the subscription was originally made can be
* referenced as <code>e.container</code>.
*
* @method delegate
* @param type {String} the event type to delegate
* @param fn {Function} the callback function to execute. This function
* will be provided the event object for the delegated event.
* @param el {String|node} the element that is the delegation container
* @param filter {string|Function} a selector that must match the target of the
* event or a function to test target and its parents for a match
* @param context optional argument that specifies what 'this' refers to.
* @param args* 0..n additional arguments to pass on to the callback function.
* These arguments will be added after the event object.
* @return {EventHandle} the detach handle
* @static
* @for Event
*/
function delegate(type, fn, el, filter) {
var args = toArray(arguments, 0, true),
query = isString(el) ? el : null,
typeBits, synth, container, categories, cat, i, len, handles, handle;
// Support Y.delegate({ click: fnA, key: fnB }, el, filter, ...);
// and Y.delegate(['click', 'key'], fn, el, filter, ...);
if (isObject(type)) {
handles = [];
if (isArray(type)) {
for (i = 0, len = type.length; i < len; ++i) {
args[0] = type[i];
handles.push(Y.delegate.apply(Y, args));
}
} else {
// Y.delegate({'click', fn}, el, filter) =>
// Y.delegate('click', fn, el, filter)
args.unshift(null); // one arg becomes two; need to make space
for (i in type) {
if (type.hasOwnProperty(i)) {
args[0] = i;
args[1] = type[i];
handles.push(Y.delegate.apply(Y, args));
}
}
}
return new Y.EventHandle(handles);
}
typeBits = type.split(/\|/);
if (typeBits.length > 1) {
cat = typeBits.shift();
args[0] = type = typeBits.shift();
}
synth = Y.Node.DOM_EVENTS[type];
if (isObject(synth) && synth.delegate) {
handle = synth.delegate.apply(synth, arguments);
}
if (!handle) {
if (!type || !fn || !el || !filter) {
Y.log("delegate requires type, callback, parent, & filter", "warn");
return;
}
container = (query) ? Y.Selector.query(query, null, true) : el;
if (!container && isString(el)) {
handle = Y.on('available', function () {
Y.mix(handle, Y.delegate.apply(Y, args), true);
}, el);
}
if (!handle && container) {
args.splice(2, 2, container); // remove the filter
handle = Y.Event._attach(args, { facade: false });
handle.sub.filter = filter;
handle.sub._notify = delegate.notifySub;
}
}
if (handle && cat) {
categories = detachCategories[cat] || (detachCategories[cat] = {});
categories = categories[type] || (categories[type] = []);
categories.push(handle);
}
return handle;
}
/**
Overrides the <code>_notify</code> method on the normal DOM subscription to
inject the filtering logic and only proceed in the case of a match.
This method is hosted as a private property of the `delegate` method
(e.g. `Y.delegate.notifySub`)
@method notifySub
@param thisObj {Object} default 'this' object for the callback
@param args {Array} arguments passed to the event's <code>fire()</code>
@param ce {CustomEvent} the custom event managing the DOM subscriptions for
the subscribed event on the subscribing node.
@return {Boolean} false if the event was stopped
@private
@static
@since 3.2.0
**/
delegate.notifySub = function (thisObj, args, ce) {
// Preserve args for other subscribers
args = args.slice();
if (this.args) {
args.push.apply(args, this.args);
}
// Only notify subs if the event occurred on a targeted element
var currentTarget = delegate._applyFilter(this.filter, args, ce),
//container = e.currentTarget,
e, i, len, ret;
if (currentTarget) {
// Support multiple matches up the the container subtree
currentTarget = toArray(currentTarget);
// The second arg is the currentTarget, but we'll be reusing this
// facade, replacing the currentTarget for each use, so it doesn't
// matter what element we seed it with.
e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce);
e.container = Y.one(ce.el);
for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) {
e.currentTarget = Y.one(currentTarget[i]);
ret = this.fn.apply(this.context || e.currentTarget, args);
if (ret === false) { // stop further notifications
break;
}
}
return ret;
}
};
/**
Compiles a selector string into a filter function to identify whether
Nodes along the parent axis of an event's target should trigger event
notification.
This function is memoized, so previously compiled filter functions are
returned if the same selector string is provided.
This function may be useful when defining synthetic events for delegate
handling.
Hosted as a property of the `delegate` method (e.g. `Y.delegate.compileFilter`).
@method compileFilter
@param selector {String} the selector string to base the filtration on
@return {Function}
@since 3.2.0
@static
**/
delegate.compileFilter = Y.cached(function (selector) {
return function (target, e) {
return selectorTest(target._node, selector,
(e.currentTarget === e.target) ? null : e.currentTarget._node);
};
});
/**
Regex to test for disabled elements during filtering. This is only relevant to
IE to normalize behavior with other browsers, which swallow events that occur
to disabled elements. IE fires the event from the parent element instead of the
original target, though it does preserve `event.srcElement` as the disabled
element. IE also supports disabled on `<a>`, but the event still bubbles, so it
acts more like `e.preventDefault()` plus styling. That issue is not handled here
because other browsers fire the event on the `<a>`, so delegate is supported in
both cases.
@property _disabledRE
@type {RegExp}
@protected
@since 3.8.1
**/
delegate._disabledRE = /^(?:button|input|select|textarea)$/i;
/**
Walks up the parent axis of an event's target, and tests each element
against a supplied filter function. If any Nodes, including the container,
satisfy the filter, the delegated callback will be triggered for each.
Hosted as a protected property of the `delegate` method (e.g.
`Y.delegate._applyFilter`).
@method _applyFilter
@param filter {Function} boolean function to test for inclusion in event
notification
@param args {Array} the arguments that would be passed to subscribers
@param ce {CustomEvent} the DOM event wrapper
@return {Node|Node[]|undefined} The Node or Nodes that satisfy the filter
@protected
**/
delegate._applyFilter = function (filter, args, ce) {
var e = args[0],
container = ce.el, // facadeless events in IE, have no e.currentTarget
target = e.target || e.srcElement,
match = [],
isContainer = false;
// Resolve text nodes to their containing element
if (target.nodeType === 3) {
target = target.parentNode;
}
// For IE. IE propagates events from the parent element of disabled
// elements, where other browsers swallow the event entirely. To normalize
// this in IE, filtering for matching elements should abort if the target
// is a disabled form control.
if (target.disabled && delegate._disabledRE.test(target.nodeName)) {
return match;
}
// passing target as the first arg rather than leaving well enough alone
// making 'this' in the filter function refer to the target. This is to
// support bound filter functions.
args.unshift(target);
if (isString(filter)) {
while (target) {
isContainer = (target === container);
if (selectorTest(target, filter, (isContainer ? null: container))) {
match.push(target);
}
if (isContainer) {
break;
}
target = target.parentNode;
}
} else {
// filter functions are implementer code and should receive wrappers
args[0] = Y.one(target);
args[1] = new Y.DOMEventFacade(e, container, ce);
while (target) {
// filter(target, e, extra args...) - this === target
if (filter.apply(args[0], args)) {
match.push(target);
}
if (target === container) {
break;
}
target = target.parentNode;
args[0] = Y.one(target);
}
args[1] = e; // restore the raw DOM event
}
if (match.length <= 1) {
match = match[0]; // single match or undefined
}
// remove the target
args.shift();
return match;
};
/**
* Sets up event delegation on a container element. The delegated event
* will use a supplied filter to test if the callback should be executed.
* This filter can be either a selector string or a function that returns
* a Node to use as the currentTarget for the event.
*
* The event object for the delegated event is supplied to the callback
* function. It is modified slightly in order to support all properties
* that may be needed for event delegation. 'currentTarget' is set to
* the element that matched the selector string filter or the Node returned
* from the filter function. 'container' is set to the element that the
* listener is delegated from (this normally would be the 'currentTarget').
*
* Filter functions will be called with the arguments that would be passed to
* the callback function, including the event object as the first parameter.
* The function should return false (or a falsey value) if the success criteria
* aren't met, and the Node to use as the event's currentTarget and 'this'
* object if they are.
*
* @method delegate
* @param type {string} the event type to delegate
* @param fn {function} the callback function to execute. This function
* will be provided the event object for the delegated event.
* @param el {string|node} the element that is the delegation container
* @param filter {string|function} a selector that must match the target of the
* event or a function that returns a Node or false.
* @param context optional argument that specifies what 'this' refers to.
* @param args* 0..n additional arguments to pass on to the callback function.
* These arguments will be added after the event object.
* @return {EventHandle} the detach handle
* @for YUI
*/
Y.delegate = Y.Event.delegate = delegate;
}, '@VERSION@', {"requires": ["node-base"]});
YUI.add('node-event-delegate', function (Y, NAME) {
/**
* Functionality to make the node a delegated event container
* @module node
* @submodule node-event-delegate
*/
/**
* <p>Sets up a delegation listener for an event occurring inside the Node.
* The delegated event will be verified against a supplied selector or
* filtering function to test if the event references at least one node that
* should trigger the subscription callback.</p>
*
* <p>Selector string filters will trigger the callback if the event originated
* from a node that matches it or is contained in a node that matches it.
* Function filters are called for each Node up the parent axis to the
* subscribing container node, and receive at each level the Node and the event
* object. The function should return true (or a truthy value) if that Node
* should trigger the subscription callback. Note, it is possible for filters
* to match multiple Nodes for a single event. In this case, the delegate
* callback will be executed for each matching Node.</p>
*
* <p>For each matching Node, the callback will be executed with its 'this'
* object set to the Node matched by the filter (unless a specific context was
* provided during subscription), and the provided event's
* <code>currentTarget</code> will also be set to the matching Node. The
* containing Node from which the subscription was originally made can be
* referenced as <code>e.container</code>.
*
* @method delegate
* @param type {String} the event type to delegate
* @param fn {Function} the callback function to execute. This function
* will be provided the event object for the delegated event.
* @param spec {String|Function} a selector that must match the target of the
* event or a function to test target and its parents for a match
* @param context {Object} optional argument that specifies what 'this' refers to.
* @param args* {any} 0..n additional arguments to pass on to the callback function.
* These arguments will be added after the event object.
* @return {EventHandle} the detach handle
* @for Node
*/
Y.Node.prototype.delegate = function(type) {
var args = Y.Array(arguments, 0, true),
index = (Y.Lang.isObject(type) && !Y.Lang.isArray(type)) ? 1 : 2;
args.splice(index, 0, this._node);
return Y.delegate.apply(Y, args);
};
}, '@VERSION@', {"requires": ["node-base", "event-delegate"]});
YUI.add('node-pluginhost', function (Y, NAME) {
/**
* @module node
* @submodule node-pluginhost
*/
/**
* Registers plugins to be instantiated at the class level (plugins
* which should be plugged into every instance of Node by default).
*
* @method plug
* @static
* @for Node
* @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined)
* @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin
*/
Y.Node.plug = function() {
var args = Y.Array(arguments);
args.unshift(Y.Node);
Y.Plugin.Host.plug.apply(Y.Base, args);
return Y.Node;
};
/**
* Unregisters any class level plugins which have been registered by the Node
*
* @method unplug
* @static
*
* @param {Function | Array} plugin The plugin class, or an array of plugin classes
*/
Y.Node.unplug = function() {
var args = Y.Array(arguments);
args.unshift(Y.Node);
Y.Plugin.Host.unplug.apply(Y.Base, args);
return Y.Node;
};
Y.mix(Y.Node, Y.Plugin.Host, false, null, 1);
// allow batching of plug/unplug via NodeList
// doesn't use NodeList.importMethod because we need real Nodes (not tmpNode)
/**
* Adds a plugin to each node in the NodeList.
* This will instantiate the plugin and attach it to the configured namespace on each node
* @method plug
* @for NodeList
* @param P {Function | Object |Array} Accepts the plugin class, or an
* object with a "fn" property specifying the plugin class and
* a "cfg" property specifying the configuration for the Plugin.
* <p>
* Additionally an Array can also be passed in, with the above function or
* object values, allowing the user to add multiple plugins in a single call.
* </p>
* @param config (Optional) If the first argument is the plugin class, the second argument
* can be the configuration for the plugin.
* @chainable
*/
Y.NodeList.prototype.plug = function() {
var args = arguments;
Y.NodeList.each(this, function(node) {
Y.Node.prototype.plug.apply(Y.one(node), args);
});
return this;
};
/**
* Removes a plugin from all nodes in the NodeList. This will destroy the
* plugin instance and delete the namespace each node.
* @method unplug
* @for NodeList
* @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided,
* all registered plugins are unplugged.
* @chainable
*/
Y.NodeList.prototype.unplug = function() {
var args = arguments;
Y.NodeList.each(this, function(node) {
Y.Node.prototype.unplug.apply(Y.one(node), args);
});
return this;
};
}, '@VERSION@', {"requires": ["node-base", "pluginhost"]});
YUI.add('node-screen', function (Y, NAME) {
/**
* Extended Node interface for managing regions and screen positioning.
* Adds support for positioning elements and normalizes window size and scroll detection.
* @module node
* @submodule node-screen
*/
// these are all "safe" returns, no wrapping required
Y.each([
/**
* Returns the inner width of the viewport (exludes scrollbar).
* @config winWidth
* @for Node
* @type {Int}
*/
'winWidth',
/**
* Returns the inner height of the viewport (exludes scrollbar).
* @config winHeight
* @type {Int}
*/
'winHeight',
/**
* Document width
* @config docWidth
* @type {Int}
*/
'docWidth',
/**
* Document height
* @config docHeight
* @type {Int}
*/
'docHeight',
/**
* Pixel distance the page has been scrolled horizontally
* @config docScrollX
* @type {Int}
*/
'docScrollX',
/**
* Pixel distance the page has been scrolled vertically
* @config docScrollY
* @type {Int}
*/
'docScrollY'
],
function(name) {
Y.Node.ATTRS[name] = {
getter: function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(Y.Node.getDOMNode(this));
return Y.DOM[name].apply(this, args);
}
};
}
);
Y.Node.ATTRS.scrollLeft = {
getter: function() {
var node = Y.Node.getDOMNode(this);
return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node);
},
setter: function(val) {
var node = Y.Node.getDOMNode(this);
if (node) {
if ('scrollLeft' in node) {
node.scrollLeft = val;
} else if (node.document || node.nodeType === 9) {
Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc
}
} else {
Y.log('unable to set scrollLeft for ' + node, 'error', 'Node');
}
}
};
Y.Node.ATTRS.scrollTop = {
getter: function() {
var node = Y.Node.getDOMNode(this);
return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node);
},
setter: function(val) {
var node = Y.Node.getDOMNode(this);
if (node) {
if ('scrollTop' in node) {
node.scrollTop = val;
} else if (node.document || node.nodeType === 9) {
Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc
}
} else {
Y.log('unable to set scrollTop for ' + node, 'error', 'Node');
}
}
};
Y.Node.importMethod(Y.DOM, [
/**
* Gets the current position of the node in page coordinates.
* @method getXY
* @for Node
* @return {Array} The XY position of the node
*/
'getXY',
/**
* Set the position of the node in page coordinates, regardless of how the node is positioned.
* @method setXY
* @param {Array} xy Contains X & Y values for new position (coordinates are page-based)
* @chainable
*/
'setXY',
/**
* Gets the current position of the node in page coordinates.
* @method getX
* @return {Int} The X position of the node
*/
'getX',
/**
* Set the position of the node in page coordinates, regardless of how the node is positioned.
* @method setX
* @param {Int} x X value for new position (coordinates are page-based)
* @chainable
*/
'setX',
/**
* Gets the current position of the node in page coordinates.
* @method getY
* @return {Int} The Y position of the node
*/
'getY',
/**
* Set the position of the node in page coordinates, regardless of how the node is positioned.
* @method setY
* @param {Int} y Y value for new position (coordinates are page-based)
* @chainable
*/
'setY',
/**
* Swaps the XY position of this node with another node.
* @method swapXY
* @param {Node | HTMLElement} otherNode The node to swap with.
* @chainable
*/
'swapXY'
]);
/**
* @module node
* @submodule node-screen
*/
/**
* Returns a region object for the node
* @config region
* @for Node
* @type Node
*/
Y.Node.ATTRS.region = {
getter: function() {
var node = this.getDOMNode(),
region;
if (node && !node.tagName) {
if (node.nodeType === 9) { // document
node = node.documentElement;
}
}
if (Y.DOM.isWindow(node)) {
region = Y.DOM.viewportRegion(node);
} else {
region = Y.DOM.region(node);
}
return region;
}
};
/**
* Returns a region object for the node's viewport
* @config viewportRegion
* @type Node
*/
Y.Node.ATTRS.viewportRegion = {
getter: function() {
return Y.DOM.viewportRegion(Y.Node.getDOMNode(this));
}
};
Y.Node.importMethod(Y.DOM, 'inViewportRegion');
// these need special treatment to extract 2nd node arg
/**
* Compares the intersection of the node with another node or region
* @method intersect
* @for Node
* @param {Node|Object} node2 The node or region to compare with.
* @param {Object} altRegion An alternate region to use (rather than this node's).
* @return {Object} An object representing the intersection of the regions.
*/
Y.Node.prototype.intersect = function(node2, altRegion) {
var node1 = Y.Node.getDOMNode(this);
if (Y.instanceOf(node2, Y.Node)) { // might be a region object
node2 = Y.Node.getDOMNode(node2);
}
return Y.DOM.intersect(node1, node2, altRegion);
};
/**
* Determines whether or not the node is within the giving region.
* @method inRegion
* @param {Node|Object} node2 The node or region to compare with.
* @param {Boolean} all Whether or not all of the node must be in the region.
* @param {Object} altRegion An alternate region to use (rather than this node's).
* @return {Boolean} True if in region, false if not.
*/
Y.Node.prototype.inRegion = function(node2, all, altRegion) {
var node1 = Y.Node.getDOMNode(this);
if (Y.instanceOf(node2, Y.Node)) { // might be a region object
node2 = Y.Node.getDOMNode(node2);
}
return Y.DOM.inRegion(node1, node2, all, altRegion);
};
}, '@VERSION@', {"requires": ["dom-screen", "node-base"]});
YUI.add('node-style', function (Y, NAME) {
(function(Y) {
/**
* Extended Node interface for managing node styles.
* @module node
* @submodule node-style
*/
Y.mix(Y.Node.prototype, {
/**
* Sets a style property of the node.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method setStyle
* @param {String} attr The style attribute to set.
* @param {String|Number} val The value.
* @chainable
*/
setStyle: function(attr, val) {
Y.DOM.setStyle(this._node, attr, val);
return this;
},
/**
* Sets multiple style properties on the node.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method setStyles
* @param {Object} hash An object literal of property:value pairs.
* @chainable
*/
setStyles: function(hash) {
Y.DOM.setStyles(this._node, hash);
return this;
},
/**
* Returns the style's current value.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method getStyle
* @for Node
* @param {String} attr The style attribute to retrieve.
* @return {String} The current value of the style property for the element.
*/
getStyle: function(attr) {
return Y.DOM.getStyle(this._node, attr);
},
/**
* Returns the computed value for the given style property.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method getComputedStyle
* @param {String} attr The style attribute to retrieve.
* @return {String} The computed value of the style property for the element.
*/
getComputedStyle: function(attr) {
return Y.DOM.getComputedStyle(this._node, attr);
}
});
/**
* Returns an array of values for each node.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method getStyle
* @for NodeList
* @see Node.getStyle
* @param {String} attr The style attribute to retrieve.
* @return {Array} The current values of the style property for the element.
*/
/**
* Returns an array of the computed value for each node.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method getComputedStyle
* @see Node.getComputedStyle
* @param {String} attr The style attribute to retrieve.
* @return {Array} The computed values for each node.
*/
/**
* Sets a style property on each node.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method setStyle
* @see Node.setStyle
* @param {String} attr The style attribute to set.
* @param {String|Number} val The value.
* @chainable
*/
/**
* Sets multiple style properties on each node.
* Use camelCase (e.g. 'backgroundColor') for multi-word properties.
* @method setStyles
* @see Node.setStyles
* @param {Object} hash An object literal of property:value pairs.
* @chainable
*/
// These are broken out to handle undefined return (avoid false positive for
// chainable)
Y.NodeList.importMethod(Y.Node.prototype, ['getStyle', 'getComputedStyle', 'setStyle', 'setStyles']);
})(Y);
}, '@VERSION@', {"requires": ["dom-style", "node-base"]});
YUI.add('querystring-stringify-simple', function (Y, NAME) {
/*global Y */
/**
* <p>Provides Y.QueryString.stringify method for converting objects to Query Strings.
* This is a subset implementation of the full querystring-stringify.</p>
* <p>This module provides the bare minimum functionality (encoding a hash of simple values),
* without the additional support for nested data structures. Every key-value pair is
* encoded by encodeURIComponent.</p>
* <p>This module provides a minimalistic way for io to handle single-level objects
* as transaction data.</p>
*
* @module querystring
* @submodule querystring-stringify-simple
*/
var QueryString = Y.namespace("QueryString"),
EUC = encodeURIComponent;
QueryString.stringify = function (obj, c) {
var qs = [],
// Default behavior is false; standard key notation.
s = c && c.arrayKey ? true : false,
key, i, l;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (Y.Lang.isArray(obj[key])) {
for (i = 0, l = obj[key].length; i < l; i++) {
qs.push(EUC(s ? key + '[]' : key) + '=' + EUC(obj[key][i]));
}
}
else {
qs.push(EUC(key) + '=' + EUC(obj[key]));
}
}
}
return qs.join('&');
};
}, '@VERSION@', {"requires": ["yui-base"]});
YUI.add('io-base', function (Y, NAME) {
/**
Base IO functionality. Provides basic XHR transport support.
@module io
@submodule io-base
@for IO
**/
var // List of events that comprise the IO event lifecycle.
EVENTS = ['start', 'complete', 'end', 'success', 'failure', 'progress'],
// Whitelist of used XHR response object properties.
XHR_PROPS = ['status', 'statusText', 'responseText', 'responseXML'],
win = Y.config.win,
uid = 0;
/**
The IO class is a utility that brokers HTTP requests through a simplified
interface. Specifically, it allows JavaScript to make HTTP requests to
a resource without a page reload. The underlying transport for making
same-domain requests is the XMLHttpRequest object. IO can also use
Flash, if specified as a transport, for cross-domain requests.
@class IO
@constructor
@param {Object} config Object of EventTarget's publish method configurations
used to configure IO's events.
**/
function IO (config) {
var io = this;
io._uid = 'io:' + uid++;
io._init(config);
Y.io._map[io._uid] = io;
}
IO.prototype = {
//--------------------------------------
// Properties
//--------------------------------------
/**
* A counter that increments for each transaction.
*
* @property _id
* @private
* @type {Number}
*/
_id: 0,
/**
* Object of IO HTTP headers sent with each transaction.
*
* @property _headers
* @private
* @type {Object}
*/
_headers: {
'X-Requested-With' : 'XMLHttpRequest'
},
/**
* Object that stores timeout values for any transaction with a defined
* "timeout" configuration property.
*
* @property _timeout
* @private
* @type {Object}
*/
_timeout: {},
//--------------------------------------
// Methods
//--------------------------------------
_init: function(config) {
var io = this, i, len;
io.cfg = config || {};
Y.augment(io, Y.EventTarget);
for (i = 0, len = EVENTS.length; i < len; ++i) {
// Publish IO global events with configurations, if any.
// IO global events are set to broadcast by default.
// These events use the "io:" namespace.
io.publish('io:' + EVENTS[i], Y.merge({ broadcast: 1 }, config));
// Publish IO transaction events with configurations, if
// any. These events use the "io-trn:" namespace.
io.publish('io-trn:' + EVENTS[i], config);
}
},
/**
* Method that creates a unique transaction object for each request.
*
* @method _create
* @private
* @param {Object} cfg Configuration object subset to determine if
* the transaction is an XDR or file upload,
* requiring an alternate transport.
* @param {Number} id Transaction id
* @return {Object} The transaction object
*/
_create: function(config, id) {
var io = this,
transaction = {
id : Y.Lang.isNumber(id) ? id : io._id++,
uid: io._uid
},
alt = config.xdr ? config.xdr.use : null,
form = config.form && config.form.upload ? 'iframe' : null,
use;
if (alt === 'native') {
// Non-IE and IE >= 10 can use XHR level 2 and not rely on an
// external transport.
alt = Y.UA.ie && !SUPPORTS_CORS ? 'xdr' : null;
// Prevent "pre-flight" OPTIONS request by removing the
// `X-Requested-With` HTTP header from CORS requests. This header
// can be added back on a per-request basis, if desired.
io.setHeader('X-Requested-With');
}
use = alt || form;
transaction = use ? Y.merge(Y.IO.customTransport(use), transaction) :
Y.merge(Y.IO.defaultTransport(), transaction);
if (transaction.notify) {
config.notify = function (e, t, c) { io.notify(e, t, c); };
}
if (!use) {
if (win && win.FormData && config.data instanceof win.FormData) {
transaction.c.upload.onprogress = function (e) {
io.progress(transaction, e, config);
};
transaction.c.onload = function (e) {
io.load(transaction, e, config);
};
transaction.c.onerror = function (e) {
io.error(transaction, e, config);
};
transaction.upload = true;
}
}
return transaction;
},
_destroy: function(transaction) {
if (win && !transaction.notify && !transaction.xdr) {
if (XHR && !transaction.upload) {
transaction.c.onreadystatechange = null;
} else if (transaction.upload) {
transaction.c.upload.onprogress = null;
transaction.c.onload = null;
transaction.c.onerror = null;
} else if (Y.UA.ie && !transaction.e) {
// IE, when using XMLHttpRequest as an ActiveX Object, will throw
// a "Type Mismatch" error if the event handler is set to "null".
transaction.c.abort();
}
}
transaction = transaction.c = null;
},
/**
* Method for creating and firing events.
*
* @method _evt
* @private
* @param {String} eventName Event to be published.
* @param {Object} transaction Transaction object.
* @param {Object} config Configuration data subset for event subscription.
*/
_evt: function(eventName, transaction, config) {
var io = this, params,
args = config['arguments'],
emitFacade = io.cfg.emitFacade,
globalEvent = "io:" + eventName,
trnEvent = "io-trn:" + eventName;
// Workaround for #2532107
this.detach(trnEvent);
if (transaction.e) {
transaction.c = { status: 0, statusText: transaction.e };
}
// Fire event with parameters or an Event Facade.
params = [ emitFacade ?
{
id: transaction.id,
data: transaction.c,
cfg: config,
'arguments': args
} :
transaction.id
];
if (!emitFacade) {
if (eventName === EVENTS[0] || eventName === EVENTS[2]) {
if (args) {
params.push(args);
}
} else {
if (transaction.evt) {
params.push(transaction.evt);
} else {
params.push(transaction.c);
}
if (args) {
params.push(args);
}
}
}
params.unshift(globalEvent);
// Fire global events.
io.fire.apply(io, params);
// Fire transaction events, if receivers are defined.
if (config.on) {
params[0] = trnEvent;
io.once(trnEvent, config.on[eventName], config.context || Y);
io.fire.apply(io, params);
}
},
/**
* Fires event "io:start" and creates, fires a transaction-specific
* start event, if `config.on.start` is defined.
*
* @method start
* @param {Object} transaction Transaction object.
* @param {Object} config Configuration object for the transaction.
*/
start: function(transaction, config) {
/**
* Signals the start of an IO request.
* @event io:start
*/
this._evt(EVENTS[0], transaction, config);
},
/**
* Fires event "io:complete" and creates, fires a
* transaction-specific "complete" event, if config.on.complete is
* defined.
*
* @method complete
* @param {Object} transaction Transaction object.
* @param {Object} config Configuration object for the transaction.
*/
complete: function(transaction, config) {
/**
* Signals the completion of the request-response phase of a
* transaction. Response status and data are accessible, if
* available, in this event.
* @event io:complete
*/
this._evt(EVENTS[1], transaction, config);
},
/**
* Fires event "io:end" and creates, fires a transaction-specific "end"
* event, if config.on.end is defined.
*
* @method end
* @param {Object} transaction Transaction object.
* @param {Object} config Configuration object for the transaction.
*/
end: function(transaction, config) {
/**
* Signals the end of the transaction lifecycle.
* @event io:end
*/
this._evt(EVENTS[2], transaction, config);
this._destroy(transaction);
},
/**
* Fires event "io:success" and creates, fires a transaction-specific
* "success" event, if config.on.success is defined.
*
* @method success
* @param {Object} transaction Transaction object.
* @param {Object} config Configuration object for the transaction.
*/
success: function(transaction, config) {
/**
* Signals an HTTP response with status in the 2xx range.
* Fires after io:complete.
* @event io:success
*/
this._evt(EVENTS[3], transaction, config);
this.end(transaction, config);
},
/**
* Fires event "io:failure" and creates, fires a transaction-specific
* "failure" event, if config.on.failure is defined.
*
* @method failure
* @param {Object} transaction Transaction object.
* @param {Object} config Configuration object for the transaction.
*/
failure: function(transaction, config) {
/**
* Signals an HTTP response with status outside of the 2xx range.
* Fires after io:complete.
* @event io:failure
*/
this._evt(EVENTS[4], transaction, config);
this.end(transaction, config);
},
/**
* Fires event "io:progress" and creates, fires a transaction-specific
* "progress" event -- for XMLHttpRequest file upload -- if
* config.on.progress is defined.
*
* @method progress
* @param {Object} transaction Transaction object.
* @param {Object} progress event.
* @param {Object} config Configuration object for the transaction.
*/
progress: function(transaction, e, config) {
/**
* Signals the interactive state during a file upload transaction.
* This event fires after io:start and before io:complete.
* @event io:progress
*/
transaction.evt = e;
this._evt(EVENTS[5], transaction, config);
},
/**
* Fires event "io:complete" and creates, fires a transaction-specific
* "complete" event -- for XMLHttpRequest file upload -- if
* config.on.complete is defined.
*
* @method load
* @param {Object} transaction Transaction object.
* @param {Object} load event.
* @param {Object} config Configuration object for the transaction.
*/
load: function (transaction, e, config) {
transaction.evt = e.target;
this._evt(EVENTS[1], transaction, config);
},
/**
* Fires event "io:failure" and creates, fires a transaction-specific
* "failure" event -- for XMLHttpRequest file upload -- if
* config.on.failure is defined.
*
* @method error
* @param {Object} transaction Transaction object.
* @param {Object} error event.
* @param {Object} config Configuration object for the transaction.
*/
error: function (transaction, e, config) {
transaction.evt = e;
this._evt(EVENTS[4], transaction, config);
},
/**
* Retry an XDR transaction, using the Flash tranport, if the native
* transport fails.
*
* @method _retry
* @private
* @param {Object} transaction Transaction object.
* @param {String} uri Qualified path to transaction resource.
* @param {Object} config Configuration object for the transaction.
*/
_retry: function(transaction, uri, config) {
this._destroy(transaction);
config.xdr.use = 'flash';
return this.send(uri, config, transaction.id);
},
/**
* Method that concatenates string data for HTTP GET transactions.
*
* @method _concat
* @private
* @param {String} uri URI or root data.
* @param {String} data Data to be concatenated onto URI.
* @return {String}
*/
_concat: function(uri, data) {
uri += (uri.indexOf('?') === -1 ? '?' : '&') + data;
return uri;
},
/**
* Stores default client headers for all transactions. If a label is
* passed with no value argument, the header will be deleted.
*
* @method setHeader
* @param {String} name HTTP header
* @param {String} value HTTP header value
*/
setHeader: function(name, value) {
if (value) {
this._headers[name] = value;
} else {
delete this._headers[name];
}
},
/**
* Method that sets all HTTP headers to be sent in a transaction.
*
* @method _setHeaders
* @private
* @param {Object} transaction - XHR instance for the specific transaction.
* @param {Object} headers - HTTP headers for the specific transaction, as
* defined in the configuration object passed to YUI.io().
*/
_setHeaders: function(transaction, headers) {
headers = Y.merge(this._headers, headers);
Y.Object.each(headers, function(value, name) {
if (value !== 'disable') {
transaction.setRequestHeader(name, headers[name]);
}
});
},
/**
* Starts timeout count if the configuration object has a defined
* timeout property.
*
* @method _startTimeout
* @private
* @param {Object} transaction Transaction object generated by _create().
* @param {Object} timeout Timeout in milliseconds.
*/
_startTimeout: function(transaction, timeout) {
var io = this;
io._timeout[transaction.id] = setTimeout(function() {
io._abort(transaction, 'timeout');
}, timeout);
},
/**
* Clears the timeout interval started by _startTimeout().
*
* @method _clearTimeout
* @private
* @param {Number} id - Transaction id.
*/
_clearTimeout: function(id) {
clearTimeout(this._timeout[id]);
delete this._timeout[id];
},
/**
* Method that determines if a transaction response qualifies as success
* or failure, based on the response HTTP status code, and fires the
* appropriate success or failure events.
*
* @method _result
* @private
* @static
* @param {Object} transaction Transaction object generated by _create().
* @param {Object} config Configuration object passed to io().
*/
_result: function(transaction, config) {
var status;
// Firefox will throw an exception if attempting to access
// an XHR object's status property, after a request is aborted.
try {
status = transaction.c.status;
} catch(e) {
status = 0;
}
// IE reports HTTP 204 as HTTP 1223.
if (status >= 200 && status < 300 || status === 304 || status === 1223) {
this.success(transaction, config);
} else {
this.failure(transaction, config);
}
},
/**
* Event handler bound to onreadystatechange.
*
* @method _rS
* @private
* @param {Object} transaction Transaction object generated by _create().
* @param {Object} config Configuration object passed to YUI.io().
*/
_rS: function(transaction, config) {
var io = this;
if (transaction.c.readyState === 4) {
if (config.timeout) {
io._clearTimeout(transaction.id);
}
// Yield in the event of request timeout or abort.
setTimeout(function() {
io.complete(transaction, config);
io._result(transaction, config);
}, 0);
}
},
/**
* Terminates a transaction due to an explicit abort or timeout.
*
* @method _abort
* @private
* @param {Object} transaction Transaction object generated by _create().
* @param {String} type Identifies timed out or aborted transaction.
*/
_abort: function(transaction, type) {
if (transaction && transaction.c) {
transaction.e = type;
transaction.c.abort();
}
},
/**
* Requests a transaction. `send()` is implemented as `Y.io()`. Each
* transaction may include a configuration object. Its properties are:
*
* <dl>
* <dt>method</dt>
* <dd>HTTP method verb (e.g., GET or POST). If this property is not
* not defined, the default value will be GET.</dd>
*
* <dt>data</dt>
* <dd>This is the name-value string that will be sent as the
* transaction data. If the request is HTTP GET, the data become
* part of querystring. If HTTP POST, the data are sent in the
* message body.</dd>
*
* <dt>xdr</dt>
* <dd>Defines the transport to be used for cross-domain requests.
* By setting this property, the transaction will use the specified
* transport instead of XMLHttpRequest. The properties of the
* transport object are:
* <dl>
* <dt>use</dt>
* <dd>The transport to be used: 'flash' or 'native'</dd>
* <dt>dataType</dt>
* <dd>Set the value to 'XML' if that is the expected response
* content type.</dd>
* <dt>credentials</dt>
* <dd>Set the value to 'true' to set XHR.withCredentials property to true.</dd>
* </dl></dd>
*
* <dt>form</dt>
* <dd>Form serialization configuration object. Its properties are:
* <dl>
* <dt>id</dt>
* <dd>Node object or id of HTML form</dd>
* <dt>useDisabled</dt>
* <dd>`true` to also serialize disabled form field values
* (defaults to `false`)</dd>
* </dl></dd>
*
* <dt>on</dt>
* <dd>Assigns transaction event subscriptions. Available events are:
* <dl>
* <dt>start</dt>
* <dd>Fires when a request is sent to a resource.</dd>
* <dt>complete</dt>
* <dd>Fires when the transaction is complete.</dd>
* <dt>success</dt>
* <dd>Fires when the HTTP response status is within the 2xx
* range.</dd>
* <dt>failure</dt>
* <dd>Fires when the HTTP response status is outside the 2xx
* range, if an exception occurs, if the transation is aborted,
* or if the transaction exceeds a configured `timeout`.</dd>
* <dt>end</dt>
* <dd>Fires at the conclusion of the transaction
* lifecycle, after `success` or `failure`.</dd>
* </dl>
*
* <p>Callback functions for `start` and `end` receive the id of the
* transaction as a first argument. For `complete`, `success`, and
* `failure`, callbacks receive the id and the response object
* (usually the XMLHttpRequest instance). If the `arguments`
* property was included in the configuration object passed to
* `Y.io()`, the configured data will be passed to all callbacks as
* the last argument.</p>
* </dd>
*
* <dt>sync</dt>
* <dd>Pass `true` to make a same-domain transaction synchronous.
* <strong>CAVEAT</strong>: This will negatively impact the user
* experience. Have a <em>very</em> good reason if you intend to use
* this.</dd>
*
* <dt>context</dt>
* <dd>The "`this'" object for all configured event handlers. If a
* specific context is needed for individual callbacks, bind the
* callback to a context using `Y.bind()`.</dd>
*
* <dt>headers</dt>
* <dd>Object map of transaction headers to send to the server. The
* object keys are the header names and the values are the header
* values.</dd>
*
* <dt>timeout</dt>
* <dd>Millisecond threshold for the transaction before being
* automatically aborted.</dd>
*
* <dt>arguments</dt>
* <dd>User-defined data passed to all registered event handlers.
* This value is available as the second argument in the "start" and
* "end" event handlers. It is the third argument in the "complete",
* "success", and "failure" event handlers. <strong>Be sure to quote
* this property name in the transaction configuration as
* "arguments" is a reserved word in JavaScript</strong> (e.g.
* `Y.io({ ..., "arguments": stuff })`).</dd>
* </dl>
*
* @method send
* @public
* @param {String} uri Qualified path to transaction resource.
* @param {Object} config Configuration object for the transaction.
* @param {Number} id Transaction id, if already set.
* @return {Object}
*/
send: function(uri, config, id) {
var transaction, method, i, len, sync, data,
io = this,
u = uri,
response = {};
config = config ? Y.Object(config) : {};
transaction = io._create(config, id);
method = config.method ? config.method.toUpperCase() : 'GET';
sync = config.sync;
data = config.data;
// Serialize a map object into a key-value string using
// querystring-stringify-simple.
if ((Y.Lang.isObject(data) && !data.nodeType) && !transaction.upload) {
if (Y.QueryString && Y.QueryString.stringify) {
Y.log('Stringifying config.data for request', 'info', 'io');
config.data = data = Y.QueryString.stringify(data);
} else {
Y.log('Failed to stringify config.data object, likely because `querystring-stringify-simple` is missing.', 'warn', 'io');
}
}
if (config.form) {
if (config.form.upload) {
// This is a file upload transaction, calling
// upload() in io-upload-iframe.
return io.upload(transaction, uri, config);
} else {
// Serialize HTML form data into a key-value string.
data = io._serialize(config.form, data);
}
}
// Convert falsy values to an empty string. This way IE can't be
// rediculous and translate `undefined` to "undefined".
data || (data = '');
if (data) {
switch (method) {
case 'GET':
case 'HEAD':
case 'DELETE':
u = io._concat(u, data);
data = '';
Y.log('HTTP' + method + ' with data. The querystring is: ' + u, 'info', 'io');
break;
case 'POST':
case 'PUT':
// If Content-Type is defined in the configuration object, or
// or as a default header, it will be used instead of
// 'application/x-www-form-urlencoded; charset=UTF-8'
config.headers = Y.merge({
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}, config.headers);
break;
}
}
if (transaction.xdr) {
// Route data to io-xdr module for flash and XDomainRequest.
return io.xdr(u, transaction, config);
}
else if (transaction.notify) {
// Route data to custom transport
return transaction.c.send(transaction, uri, config);
}
if (!sync && !transaction.upload) {
transaction.c.onreadystatechange = function() {
io._rS(transaction, config);
};
}
try {
// Determine if request is to be set as
// synchronous or asynchronous.
transaction.c.open(method, u, !sync, config.username || null, config.password || null);
io._setHeaders(transaction.c, config.headers || {});
io.start(transaction, config);
// Will work only in browsers that implement the
// Cross-Origin Resource Sharing draft.
if (config.xdr && config.xdr.credentials && SUPPORTS_CORS) {
transaction.c.withCredentials = true;
}
// Using "null" with HTTP POST will result in a request
// with no Content-Length header defined.
transaction.c.send(data);
if (sync) {
// Create a response object for synchronous transactions,
// mixing id and arguments properties with the xhr
// properties whitelist.
for (i = 0, len = XHR_PROPS.length; i < len; ++i) {
response[XHR_PROPS[i]] = transaction.c[XHR_PROPS[i]];
}
response.getAllResponseHeaders = function() {
return transaction.c.getAllResponseHeaders();
};
response.getResponseHeader = function(name) {
return transaction.c.getResponseHeader(name);
};
io.complete(transaction, config);
io._result(transaction, config);
return response;
}
} catch(e) {
if (transaction.xdr) {
// This exception is usually thrown by browsers
// that do not support XMLHttpRequest Level 2.
// Retry the request with the XDR transport set
// to 'flash'. If the Flash transport is not
// initialized or available, the transaction
// will resolve to a transport error.
return io._retry(transaction, uri, config);
} else {
io.complete(transaction, config);
io._result(transaction, config);
}
}
// If config.timeout is defined, and the request is standard XHR,
// initialize timeout polling.
if (config.timeout) {
io._startTimeout(transaction, config.timeout);
Y.log('Configuration timeout set to: ' + config.timeout, 'info', 'io');
}
return {
id: transaction.id,
abort: function() {
return transaction.c ? io._abort(transaction, 'abort') : false;
},
isInProgress: function() {
return transaction.c ? (transaction.c.readyState % 4) : false;
},
io: io
};
}
};
/**
Method for initiating an ajax call. The first argument is the url end
point for the call. The second argument is an object to configure the
transaction and attach event subscriptions. The configuration object
supports the following properties:
<dl>
<dt>method</dt>
<dd>HTTP method verb (e.g., GET or POST). If this property is not
not defined, the default value will be GET.</dd>
<dt>data</dt>
<dd>This is the name-value string that will be sent as the
transaction data. If the request is HTTP GET, the data become
part of querystring. If HTTP POST, the data are sent in the
message body.</dd>
<dt>xdr</dt>
<dd>Defines the transport to be used for cross-domain requests.
By setting this property, the transaction will use the specified
transport instead of XMLHttpRequest. The properties of the
transport object are:
<dl>
<dt>use</dt>
<dd>The transport to be used: 'flash' or 'native'</dd>
<dt>dataType</dt>
<dd>Set the value to 'XML' if that is the expected response
content type.</dd>
</dl></dd>
<dt>form</dt>
<dd>Form serialization configuration object. Its properties are:
<dl>
<dt>id</dt>
<dd>Node object or id of HTML form</dd>
<dt>useDisabled</dt>
<dd>`true` to also serialize disabled form field values
(defaults to `false`)</dd>
</dl></dd>
<dt>on</dt>
<dd>Assigns transaction event subscriptions. Available events are:
<dl>
<dt>start</dt>
<dd>Fires when a request is sent to a resource.</dd>
<dt>complete</dt>
<dd>Fires when the transaction is complete.</dd>
<dt>success</dt>
<dd>Fires when the HTTP response status is within the 2xx
range.</dd>
<dt>failure</dt>
<dd>Fires when the HTTP response status is outside the 2xx
range, if an exception occurs, if the transation is aborted,
or if the transaction exceeds a configured `timeout`.</dd>
<dt>end</dt>
<dd>Fires at the conclusion of the transaction
lifecycle, after `success` or `failure`.</dd>
</dl>
<p>Callback functions for `start` and `end` receive the id of the
transaction as a first argument. For `complete`, `success`, and
`failure`, callbacks receive the id and the response object
(usually the XMLHttpRequest instance). If the `arguments`
property was included in the configuration object passed to
`Y.io()`, the configured data will be passed to all callbacks as
the last argument.</p>
</dd>
<dt>sync</dt>
<dd>Pass `true` to make a same-domain transaction synchronous.
<strong>CAVEAT</strong>: This will negatively impact the user
experience. Have a <em>very</em> good reason if you intend to use
this.</dd>
<dt>context</dt>
<dd>The "`this'" object for all configured event handlers. If a
specific context is needed for individual callbacks, bind the
callback to a context using `Y.bind()`.</dd>
<dt>headers</dt>
<dd>Object map of transaction headers to send to the server. The
object keys are the header names and the values are the header
values.</dd>
<dt>timeout</dt>
<dd>Millisecond threshold for the transaction before being
automatically aborted.</dd>
<dt>arguments</dt>
<dd>User-defined data passed to all registered event handlers.
This value is available as the second argument in the "start" and
"end" event handlers. It is the third argument in the "complete",
"success", and "failure" event handlers. <strong>Be sure to quote
this property name in the transaction configuration as
"arguments" is a reserved word in JavaScript</strong> (e.g.
`Y.io({ ..., "arguments": stuff })`).</dd>
</dl>
@method io
@static
@param {String} url qualified path to transaction resource.
@param {Object} config configuration object for the transaction.
@return {Object}
@for YUI
**/
Y.io = function(url, config) {
// Calling IO through the static interface will use and reuse
// an instance of IO.
var transaction = Y.io._map['io:0'] || new IO();
return transaction.send.apply(transaction, [url, config]);
};
/**
Method for setting and deleting IO HTTP headers to be sent with every
request.
Hosted as a property on the `io` function (e.g. `Y.io.header`).
@method header
@param {String} name HTTP header
@param {String} value HTTP header value
@static
**/
Y.io.header = function(name, value) {
// Calling IO through the static interface will use and reuse
// an instance of IO.
var transaction = Y.io._map['io:0'] || new IO();
transaction.setHeader(name, value);
};
Y.IO = IO;
// Map of all IO instances created.
Y.io._map = {};
var XHR = win && win.XMLHttpRequest,
XDR = win && win.XDomainRequest,
AX = win && win.ActiveXObject,
// Checks for the presence of the `withCredentials` in an XHR instance
// object, which will be present if the environment supports CORS.
SUPPORTS_CORS = XHR && 'withCredentials' in (new XMLHttpRequest());
Y.mix(Y.IO, {
/**
* The ID of the default IO transport, defaults to `xhr`
* @property _default
* @type {String}
* @static
*/
_default: 'xhr',
/**
*
* @method defaultTransport
* @static
* @param {String} [id] The transport to set as the default, if empty a new transport is created.
* @return {Object} The transport object with a `send` method
*/
defaultTransport: function(id) {
if (id) {
Y.log('Setting default IO to: ' + id, 'info', 'io');
Y.IO._default = id;
} else {
var o = {
c: Y.IO.transports[Y.IO._default](),
notify: Y.IO._default === 'xhr' ? false : true
};
Y.log('Creating default transport: ' + Y.IO._default, 'info', 'io');
return o;
}
},
/**
* An object hash of custom transports available to IO
* @property transports
* @type {Object}
* @static
*/
transports: {
xhr: function () {
return XHR ? new XMLHttpRequest() :
AX ? new ActiveXObject('Microsoft.XMLHTTP') : null;
},
xdr: function () {
return XDR ? new XDomainRequest() : null;
},
iframe: function () { return {}; },
flash: null,
nodejs: null
},
/**
* Create a custom transport of type and return it's object
* @method customTransport
* @param {String} id The id of the transport to create.
* @static
*/
customTransport: function(id) {
var o = { c: Y.IO.transports[id]() };
o[(id === 'xdr' || id === 'flash') ? 'xdr' : 'notify'] = true;
return o;
}
});
Y.mix(Y.IO.prototype, {
/**
* Fired from the notify method of the transport which in turn fires
* the event on the IO object.
* @method notify
* @param {String} event The name of the event
* @param {Object} transaction The transaction object
* @param {Object} config The configuration object for this transaction
*/
notify: function(event, transaction, config) {
var io = this;
switch (event) {
case 'timeout':
case 'abort':
case 'transport error':
transaction.c = { status: 0, statusText: event };
event = 'failure';
default:
io[event].apply(io, [transaction, config]);
}
}
});
}, '@VERSION@', {"requires": ["event-custom-base", "querystring-stringify-simple"]});
YUI.add('json-parse', function (Y, NAME) {
var _JSON = Y.config.global.JSON;
Y.namespace('JSON').parse = function (obj, reviver, space) {
return _JSON.parse((typeof obj === 'string' ? obj : obj + ''), reviver, space);
};
}, '@VERSION@', {"requires": ["yui-base"]});
YUI.add('transition', function (Y, NAME) {
/**
* Provides the transition method for Node.
* Transition has no API of its own, but adds the transition method to Node.
*
* @module transition
* @requires node-style
*/
var CAMEL_VENDOR_PREFIX = '',
VENDOR_PREFIX = '',
DOCUMENT = Y.config.doc,
DOCUMENT_ELEMENT = 'documentElement',
DOCUMENT_STYLE = DOCUMENT[DOCUMENT_ELEMENT].style,
TRANSITION_CAMEL = 'transition',
TRANSITION_PROPERTY_CAMEL = 'transitionProperty',
TRANSITION_PROPERTY,
TRANSITION_DURATION,
TRANSITION_TIMING_FUNCTION,
TRANSITION_DELAY,
TRANSITION_END,
ON_TRANSITION_END,
EMPTY_OBJ = {},
VENDORS = [
'Webkit',
'Moz'
],
VENDOR_TRANSITION_END = {
Webkit: 'webkitTransitionEnd'
},
/**
* A class for constructing transition instances.
* Adds the "transition" method to Node.
* @class Transition
* @constructor
*/
Transition = function() {
this.init.apply(this, arguments);
};
// One off handling of transform-prefixing.
Transition._TRANSFORM = 'transform';
Transition._toCamel = function(property) {
property = property.replace(/-([a-z])/gi, function(m0, m1) {
return m1.toUpperCase();
});
return property;
};
Transition._toHyphen = function(property) {
property = property.replace(/([A-Z]?)([a-z]+)([A-Z]?)/g, function(m0, m1, m2, m3) {
var str = ((m1) ? '-' + m1.toLowerCase() : '') + m2;
if (m3) {
str += '-' + m3.toLowerCase();
}
return str;
});
return property;
};
Transition.SHOW_TRANSITION = 'fadeIn';
Transition.HIDE_TRANSITION = 'fadeOut';
Transition.useNative = false;
// Map transition properties to vendor-specific versions.
if ('transition' in DOCUMENT_STYLE
&& 'transitionProperty' in DOCUMENT_STYLE
&& 'transitionDuration' in DOCUMENT_STYLE
&& 'transitionTimingFunction' in DOCUMENT_STYLE
&& 'transitionDelay' in DOCUMENT_STYLE) {
Transition.useNative = true;
Transition.supported = true; // TODO: remove
} else {
Y.Array.each(VENDORS, function(val) { // then vendor specific
var property = val + 'Transition';
if (property in DOCUMENT[DOCUMENT_ELEMENT].style) {
CAMEL_VENDOR_PREFIX = val;
VENDOR_PREFIX = Transition._toHyphen(val) + '-';
Transition.useNative = true;
Transition.supported = true; // TODO: remove
Transition._VENDOR_PREFIX = val;
}
});
}
// Map transform property to vendor-specific versions.
// One-off required for cssText injection.
if (typeof DOCUMENT_STYLE.transform === 'undefined') {
Y.Array.each(VENDORS, function(val) { // then vendor specific
var property = val + 'Transform';
if (typeof DOCUMENT_STYLE[property] !== 'undefined') {
Transition._TRANSFORM = property;
}
});
}
if (CAMEL_VENDOR_PREFIX) {
TRANSITION_CAMEL = CAMEL_VENDOR_PREFIX + 'Transition';
TRANSITION_PROPERTY_CAMEL = CAMEL_VENDOR_PREFIX + 'TransitionProperty';
}
TRANSITION_PROPERTY = VENDOR_PREFIX + 'transition-property';
TRANSITION_DURATION = VENDOR_PREFIX + 'transition-duration';
TRANSITION_TIMING_FUNCTION = VENDOR_PREFIX + 'transition-timing-function';
TRANSITION_DELAY = VENDOR_PREFIX + 'transition-delay';
TRANSITION_END = 'transitionend';
ON_TRANSITION_END = 'on' + CAMEL_VENDOR_PREFIX.toLowerCase() + 'transitionend';
TRANSITION_END = VENDOR_TRANSITION_END[CAMEL_VENDOR_PREFIX] || TRANSITION_END;
Transition.fx = {};
Transition.toggles = {};
Transition._hasEnd = {};
Transition._reKeywords = /^(?:node|duration|iterations|easing|delay|on|onstart|onend)$/i;
Y.Node.DOM_EVENTS[TRANSITION_END] = 1;
Transition.NAME = 'transition';
Transition.DEFAULT_EASING = 'ease';
Transition.DEFAULT_DURATION = 0.5;
Transition.DEFAULT_DELAY = 0;
Transition._nodeAttrs = {};
Transition.prototype = {
constructor: Transition,
init: function(node, config) {
var anim = this;
anim._node = node;
if (!anim._running && config) {
anim._config = config;
node._transition = anim; // cache for reuse
anim._duration = ('duration' in config) ?
config.duration: anim.constructor.DEFAULT_DURATION;
anim._delay = ('delay' in config) ?
config.delay: anim.constructor.DEFAULT_DELAY;
anim._easing = config.easing || anim.constructor.DEFAULT_EASING;
anim._count = 0; // track number of animated properties
anim._running = false;
}
return anim;
},
addProperty: function(prop, config) {
var anim = this,
node = this._node,
uid = Y.stamp(node),
nodeInstance = Y.one(node),
attrs = Transition._nodeAttrs[uid],
computed,
compareVal,
dur,
attr,
val;
if (!attrs) {
attrs = Transition._nodeAttrs[uid] = {};
}
attr = attrs[prop];
// might just be a value
if (config && config.value !== undefined) {
val = config.value;
} else if (config !== undefined) {
val = config;
config = EMPTY_OBJ;
}
if (typeof val === 'function') {
val = val.call(nodeInstance, nodeInstance);
}
if (attr && attr.transition) {
// take control if another transition owns this property
if (attr.transition !== anim) {
attr.transition._count--; // remapping attr to this transition
}
}
anim._count++; // properties per transition
// make 0 async and fire events
dur = ((typeof config.duration !== 'undefined') ? config.duration :
anim._duration) || 0.0001;
attrs[prop] = {
value: val,
duration: dur,
delay: (typeof config.delay !== 'undefined') ? config.delay :
anim._delay,
easing: config.easing || anim._easing,
transition: anim
};
// native end event doesnt fire when setting to same value
// supplementing with timer
// val may be a string or number (height: 0, etc), but computedStyle is always string
computed = Y.DOM.getComputedStyle(node, prop);
compareVal = (typeof val === 'string') ? computed : parseFloat(computed);
if (Transition.useNative && compareVal === val) {
setTimeout(function() {
anim._onNativeEnd.call(node, {
propertyName: prop,
elapsedTime: dur
});
}, dur * 1000);
}
},
removeProperty: function(prop) {
var anim = this,
attrs = Transition._nodeAttrs[Y.stamp(anim._node)];
if (attrs && attrs[prop]) {
delete attrs[prop];
anim._count--;
}
},
initAttrs: function(config) {
var attr,
node = this._node;
if (config.transform && !config[Transition._TRANSFORM]) {
config[Transition._TRANSFORM] = config.transform;
delete config.transform; // TODO: copy
}
for (attr in config) {
if (config.hasOwnProperty(attr) && !Transition._reKeywords.test(attr)) {
this.addProperty(attr, config[attr]);
// when size is auto or % webkit starts from zero instead of computed
// (https://bugs.webkit.org/show_bug.cgi?id=16020)
// TODO: selective set
if (node.style[attr] === '') {
Y.DOM.setStyle(node, attr, Y.DOM.getComputedStyle(node, attr));
}
}
}
},
/**
* Starts or an animation.
* @method run
* @chainable
* @private
*/
run: function(callback) {
var anim = this,
node = anim._node,
config = anim._config,
data = {
type: 'transition:start',
config: config
};
if (!anim._running) {
anim._running = true;
if (config.on && config.on.start) {
config.on.start.call(Y.one(node), data);
}
anim.initAttrs(anim._config);
anim._callback = callback;
anim._start();
}
return anim;
},
_start: function() {
this._runNative();
},
_prepDur: function(dur) {
dur = parseFloat(dur) * 1000;
return dur + 'ms';
},
_runNative: function() {
var anim = this,
node = anim._node,
uid = Y.stamp(node),
style = node.style,
computed = node.ownerDocument.defaultView.getComputedStyle(node),
attrs = Transition._nodeAttrs[uid],
cssText = '',
cssTransition = computed[Transition._toCamel(TRANSITION_PROPERTY)],
transitionText = TRANSITION_PROPERTY + ': ',
duration = TRANSITION_DURATION + ': ',
easing = TRANSITION_TIMING_FUNCTION + ': ',
delay = TRANSITION_DELAY + ': ',
hyphy,
attr,
name;
// preserve existing transitions
if (cssTransition !== 'all') {
transitionText += cssTransition + ',';
duration += computed[Transition._toCamel(TRANSITION_DURATION)] + ',';
easing += computed[Transition._toCamel(TRANSITION_TIMING_FUNCTION)] + ',';
delay += computed[Transition._toCamel(TRANSITION_DELAY)] + ',';
}
// run transitions mapped to this instance
for (name in attrs) {
hyphy = Transition._toHyphen(name);
attr = attrs[name];
if ((attr = attrs[name]) && attr.transition === anim) {
if (name in node.style) { // only native styles allowed
duration += anim._prepDur(attr.duration) + ',';
delay += anim._prepDur(attr.delay) + ',';
easing += (attr.easing) + ',';
transitionText += hyphy + ',';
cssText += hyphy + ': ' + attr.value + '; ';
} else {
this.removeProperty(name);
}
}
}
transitionText = transitionText.replace(/,$/, ';');
duration = duration.replace(/,$/, ';');
easing = easing.replace(/,$/, ';');
delay = delay.replace(/,$/, ';');
// only one native end event per node
if (!Transition._hasEnd[uid]) {
node.addEventListener(TRANSITION_END, anim._onNativeEnd, '');
Transition._hasEnd[uid] = true;
}
style.cssText += transitionText + duration + easing + delay + cssText;
},
_end: function(elapsed) {
var anim = this,
node = anim._node,
callback = anim._callback,
config = anim._config,
data = {
type: 'transition:end',
config: config,
elapsedTime: elapsed
},
nodeInstance = Y.one(node);
anim._running = false;
anim._callback = null;
if (node) {
if (config.on && config.on.end) {
setTimeout(function() { // IE: allow previous update to finish
config.on.end.call(nodeInstance, data);
// nested to ensure proper fire order
if (callback) {
callback.call(nodeInstance, data);
}
}, 1);
} else if (callback) {
setTimeout(function() { // IE: allow previous update to finish
callback.call(nodeInstance, data);
}, 1);
}
}
},
_endNative: function(name) {
var node = this._node,
value = node.ownerDocument.defaultView.getComputedStyle(node, '')[Transition._toCamel(TRANSITION_PROPERTY)];
name = Transition._toHyphen(name);
if (typeof value === 'string') {
value = value.replace(new RegExp('(?:^|,\\s)' + name + ',?'), ',');
value = value.replace(/^,|,$/, '');
node.style[TRANSITION_CAMEL] = value;
}
},
_onNativeEnd: function(e) {
var node = this,
uid = Y.stamp(node),
event = e,//e._event,
name = Transition._toCamel(event.propertyName),
elapsed = event.elapsedTime,
attrs = Transition._nodeAttrs[uid],
attr = attrs[name],
anim = (attr) ? attr.transition : null,
data,
config;
if (anim) {
anim.removeProperty(name);
anim._endNative(name);
config = anim._config[name];
data = {
type: 'propertyEnd',
propertyName: name,
elapsedTime: elapsed,
config: config
};
if (config && config.on && config.on.end) {
config.on.end.call(Y.one(node), data);
}
if (anim._count <= 0) { // after propertyEnd fires
anim._end(elapsed);
node.style[TRANSITION_PROPERTY_CAMEL] = ''; // clean up style
}
}
},
destroy: function() {
var anim = this,
node = anim._node;
if (node) {
node.removeEventListener(TRANSITION_END, anim._onNativeEnd, false);
anim._node = null;
}
}
};
Y.Transition = Transition;
Y.TransitionNative = Transition; // TODO: remove
/**
* Animate one or more css properties to a given value. Requires the "transition" module.
* <pre>example usage:
* Y.one('#demo').transition({
* duration: 1, // in seconds, default is 0.5
* easing: 'ease-out', // default is 'ease'
* delay: '1', // delay start for 1 second, default is 0
*
* height: '10px',
* width: '10px',
*
* opacity: { // per property
* value: 0,
* duration: 2,
* delay: 2,
* easing: 'ease-in'
* }
* });
* </pre>
* @for Node
* @method transition
* @param {Object} config An object containing one or more style properties, a duration and an easing.
* @param {Function} callback A function to run after the transition has completed.
* @chainable
*/
Y.Node.prototype.transition = function(name, config, callback) {
var
transitionAttrs = Transition._nodeAttrs[Y.stamp(this._node)],
anim = (transitionAttrs) ? transitionAttrs.transition || null : null,
fxConfig,
prop;
if (typeof name === 'string') { // named effect, pull config from registry
if (typeof config === 'function') {
callback = config;
config = null;
}
fxConfig = Transition.fx[name];
if (config && typeof config !== 'boolean') {
config = Y.clone(config);
for (prop in fxConfig) {
if (fxConfig.hasOwnProperty(prop)) {
if (! (prop in config)) {
config[prop] = fxConfig[prop];
}
}
}
} else {
config = fxConfig;
}
} else { // name is a config, config is a callback or undefined
callback = config;
config = name;
}
if (anim && !anim._running) {
anim.init(this, config);
} else {
anim = new Transition(this._node, config);
}
anim.run(callback);
return this;
};
Y.Node.prototype.show = function(name, config, callback) {
this._show(); // show prior to transition
if (name && Y.Transition) {
if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default
if (typeof config === 'function') {
callback = config;
config = name;
}
name = Transition.SHOW_TRANSITION;
}
this.transition(name, config, callback);
}
else if (name && !Y.Transition) { Y.log('unable to transition show; missing transition module', 'warn', 'node'); }
return this;
};
Y.NodeList.prototype.show = function(name, config, callback) {
var nodes = this._nodes,
i = 0,
node;
while ((node = nodes[i++])) {
Y.one(node).show(name, config, callback);
}
return this;
};
var _wrapCallBack = function(anim, fn, callback) {
return function() {
if (fn) {
fn.call(anim);
}
if (callback && typeof callback === 'function') {
callback.apply(anim._node, arguments);
}
};
};
Y.Node.prototype.hide = function(name, config, callback) {
if (name && Y.Transition) {
if (typeof config === 'function') {
callback = config;
config = null;
}
callback = _wrapCallBack(this, this._hide, callback); // wrap with existing callback
if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default
if (typeof config === 'function') {
callback = config;
config = name;
}
name = Transition.HIDE_TRANSITION;
}
this.transition(name, config, callback);
} else if (name && !Y.Transition) { Y.log('unable to transition hide; missing transition module', 'warn', 'node');
} else {
this._hide();
}
return this;
};
Y.NodeList.prototype.hide = function(name, config, callback) {
var nodes = this._nodes,
i = 0,
node;
while ((node = nodes[i++])) {
Y.one(node).hide(name, config, callback);
}
return this;
};
/**
* Animate one or more css properties to a given value. Requires the "transition" module.
* <pre>example usage:
* Y.all('.demo').transition({
* duration: 1, // in seconds, default is 0.5
* easing: 'ease-out', // default is 'ease'
* delay: '1', // delay start for 1 second, default is 0
*
* height: '10px',
* width: '10px',
*
* opacity: { // per property
* value: 0,
* duration: 2,
* delay: 2,
* easing: 'ease-in'
* }
* });
* </pre>
* @for NodeList
* @method transition
* @param {Object} config An object containing one or more style properties, a duration and an easing.
* @param {Function} callback A function to run after the transition has completed. The callback fires
* once per item in the NodeList.
* @chainable
*/
Y.NodeList.prototype.transition = function(config, callback) {
var nodes = this._nodes,
i = 0,
node;
while ((node = nodes[i++])) {
Y.one(node).transition(config, callback);
}
return this;
};
Y.Node.prototype.toggleView = function(name, on, callback) {
this._toggles = this._toggles || [];
callback = arguments[arguments.length - 1];
if (typeof name !== 'string') { // no transition, just toggle
on = name;
this._toggleView(on, callback); // call original _toggleView in Y.Node
return;
}
if (typeof on === 'function') { // Ignore "on" if used for callback argument.
on = undefined;
}
if (typeof on === 'undefined' && name in this._toggles) { // reverse current toggle
on = ! this._toggles[name];
}
on = (on) ? 1 : 0;
if (on) {
this._show();
} else {
callback = _wrapCallBack(this, this._hide, callback);
}
this._toggles[name] = on;
this.transition(Y.Transition.toggles[name][on], callback);
return this;
};
Y.NodeList.prototype.toggleView = function(name, on, callback) {
var nodes = this._nodes,
i = 0,
node;
while ((node = nodes[i++])) {
node = Y.one(node);
node.toggleView.apply(node, arguments);
}
return this;
};
Y.mix(Transition.fx, {
fadeOut: {
opacity: 0,
duration: 0.5,
easing: 'ease-out'
},
fadeIn: {
opacity: 1,
duration: 0.5,
easing: 'ease-in'
},
sizeOut: {
height: 0,
width: 0,
duration: 0.75,
easing: 'ease-out'
},
sizeIn: {
height: function(node) {
return node.get('scrollHeight') + 'px';
},
width: function(node) {
return node.get('scrollWidth') + 'px';
},
duration: 0.5,
easing: 'ease-in',
on: {
start: function() {
var overflow = this.getStyle('overflow');
if (overflow !== 'hidden') { // enable scrollHeight/Width
this.setStyle('overflow', 'hidden');
this._transitionOverflow = overflow;
}
},
end: function() {
if (this._transitionOverflow) { // revert overridden value
this.setStyle('overflow', this._transitionOverflow);
delete this._transitionOverflow;
}
}
}
}
});
Y.mix(Transition.toggles, {
size: ['sizeOut', 'sizeIn'],
fade: ['fadeOut', 'fadeIn']
});
}, '@VERSION@', {"requires": ["node-style"]});
YUI.add('selector-css2', function (Y, NAME) {
/**
* The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements.
* @module dom
* @submodule selector-css2
* @for Selector
*/
/*
* Provides helper methods for collecting and filtering DOM elements.
*/
var PARENT_NODE = 'parentNode',
TAG_NAME = 'tagName',
ATTRIBUTES = 'attributes',
COMBINATOR = 'combinator',
PSEUDOS = 'pseudos',
Selector = Y.Selector,
SelectorCSS2 = {
_reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/,
SORT_RESULTS: true,
// TODO: better detection, document specific
_isXML: (function() {
var isXML = (Y.config.doc.createElement('div').tagName !== 'DIV');
return isXML;
}()),
/**
* Mapping of shorthand tokens to corresponding attribute selector
* @property shorthand
* @type object
*/
shorthand: {
'\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]',
'\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]'
},
/**
* List of operators and corresponding boolean functions.
* These functions are passed the attribute and the current node's value of the attribute.
* @property operators
* @type object
*/
operators: {
'': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute
'~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited
'|=': '^{val}-?' // optional hyphen-delimited
},
pseudos: {
'first-child': function(node) {
return Y.DOM._children(node[PARENT_NODE])[0] === node;
}
},
_bruteQuery: function(selector, root, firstOnly) {
var ret = [],
nodes = [],
tokens = Selector._tokenize(selector),
token = tokens[tokens.length - 1],
rootDoc = Y.DOM._getDoc(root),
child,
id,
className,
tagName;
if (token) {
// prefilter nodes
id = token.id;
className = token.className;
tagName = token.tagName || '*';
if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags
// try ID first, unless no root.all && root not in document
// (root.all works off document, but not getElementById)
if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) {
nodes = Y.DOM.allById(id, root);
// try className
} else if (className) {
nodes = root.getElementsByClassName(className);
} else { // default to tagName
nodes = root.getElementsByTagName(tagName);
}
} else { // brute getElementsByTagName()
child = root.firstChild;
while (child) {
// only collect HTMLElements
// match tag to supplement missing getElementsByTagName
if (child.tagName && (tagName === '*' || child.tagName === tagName)) {
nodes.push(child);
}
child = child.nextSibling || child.firstChild;
}
}
if (nodes.length) {
ret = Selector._filterNodes(nodes, tokens, firstOnly);
}
}
return ret;
},
_filterNodes: function(nodes, tokens, firstOnly) {
var i = 0,
j,
len = tokens.length,
n = len - 1,
result = [],
node = nodes[0],
tmpNode = node,
getters = Y.Selector.getters,
operator,
combinator,
token,
path,
pass,
value,
tests,
test;
for (i = 0; (tmpNode = node = nodes[i++]);) {
n = len - 1;
path = null;
testLoop:
while (tmpNode && tmpNode.tagName) {
token = tokens[n];
tests = token.tests;
j = tests.length;
if (j && !pass) {
while ((test = tests[--j])) {
operator = test[1];
if (getters[test[0]]) {
value = getters[test[0]](tmpNode, test[0]);
} else {
value = tmpNode[test[0]];
if (test[0] === 'tagName' && !Selector._isXML) {
value = value.toUpperCase();
}
if (typeof value != 'string' && value !== undefined && value.toString) {
value = value.toString(); // coerce for comparison
} else if (value === undefined && tmpNode.getAttribute) {
// use getAttribute for non-standard attributes
value = tmpNode.getAttribute(test[0], 2); // 2 === force string for IE
}
}
if ((operator === '=' && value !== test[2]) || // fast path for equality
(typeof operator !== 'string' && // protect against String.test monkey-patch (Moo)
operator.test && !operator.test(value)) || // regex test
(!operator.test && // protect against RegExp as function (webkit)
typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test
// skip non element nodes or non-matching tags
if ((tmpNode = tmpNode[path])) {
while (tmpNode &&
(!tmpNode.tagName ||
(token.tagName && token.tagName !== tmpNode.tagName))
) {
tmpNode = tmpNode[path];
}
}
continue testLoop;
}
}
}
n--; // move to next token
// now that we've passed the test, move up the tree by combinator
if (!pass && (combinator = token.combinator)) {
path = combinator.axis;
tmpNode = tmpNode[path];
// skip non element nodes
while (tmpNode && !tmpNode.tagName) {
tmpNode = tmpNode[path];
}
if (combinator.direct) { // one pass only
path = null;
}
} else { // success if we made it this far
result.push(node);
if (firstOnly) {
return result;
}
break;
}
}
}
node = tmpNode = null;
return result;
},
combinators: {
' ': {
axis: 'parentNode'
},
'>': {
axis: 'parentNode',
direct: true
},
'+': {
axis: 'previousSibling',
direct: true
}
},
_parsers: [
{
name: ATTRIBUTES,
re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i,
fn: function(match, token) {
var operator = match[2] || '',
operators = Selector.operators,
escVal = (match[3]) ? match[3].replace(/\\/g, '') : '',
test;
// add prefiltering for ID and CLASS
if ((match[1] === 'id' && operator === '=') ||
(match[1] === 'className' &&
Y.config.doc.documentElement.getElementsByClassName &&
(operator === '~=' || operator === '='))) {
token.prefilter = match[1];
match[3] = escVal;
// escape all but ID for prefilter, which may run through QSA (via Dom.allById)
token[match[1]] = (match[1] === 'id') ? match[3] : escVal;
}
// add tests
if (operator in operators) {
test = operators[operator];
if (typeof test === 'string') {
match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1');
test = new RegExp(test.replace('{val}', match[3]));
}
match[2] = test;
}
if (!token.last || token.prefilter !== match[1]) {
return match.slice(1);
}
}
},
{
name: TAG_NAME,
re: /^((?:-?[_a-z]+[\w-]*)|\*)/i,
fn: function(match, token) {
var tag = match[1];
if (!Selector._isXML) {
tag = tag.toUpperCase();
}
token.tagName = tag;
if (tag !== '*' && (!token.last || token.prefilter)) {
return [TAG_NAME, '=', tag];
}
if (!token.prefilter) {
token.prefilter = 'tagName';
}
}
},
{
name: COMBINATOR,
re: /^\s*([>+~]|\s)\s*/,
fn: function(match, token) {
}
},
{
name: PSEUDOS,
re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i,
fn: function(match, token) {
var test = Selector[PSEUDOS][match[1]];
if (test) { // reorder match array and unescape special chars for tests
if (match[2]) {
match[2] = match[2].replace(/\\/g, '');
}
return [match[2], test];
} else { // selector token not supported (possibly missing CSS3 module)
return false;
}
}
}
],
_getToken: function(token) {
return {
tagName: null,
id: null,
className: null,
attributes: {},
combinator: null,
tests: []
};
},
/*
Break selector into token units per simple selector.
Combinator is attached to the previous token.
*/
_tokenize: function(selector) {
selector = selector || '';
selector = Selector._parseSelector(Y.Lang.trim(selector));
var token = Selector._getToken(), // one token per simple selector (left selector holds combinator)
query = selector, // original query for debug report
tokens = [], // array of tokens
found = false, // whether or not any matches were found this pass
match, // the regex match
test,
i, parser;
/*
Search for selector patterns, store, and strip them from the selector string
until no patterns match (invalid selector) or we run out of chars.
Multiple attributes and pseudos are allowed, in any order.
for example:
'form:first-child[type=button]:not(button)[lang|=en]'
*/
outer:
do {
found = false; // reset after full pass
for (i = 0; (parser = Selector._parsers[i++]);) {
if ( (match = parser.re.exec(selector)) ) { // note assignment
if (parser.name !== COMBINATOR ) {
token.selector = selector;
}
selector = selector.replace(match[0], ''); // strip current match from selector
if (!selector.length) {
token.last = true;
}
if (Selector._attrFilters[match[1]]) { // convert class to className, etc.
match[1] = Selector._attrFilters[match[1]];
}
test = parser.fn(match, token);
if (test === false) { // selector not supported
found = false;
break outer;
} else if (test) {
token.tests.push(test);
}
if (!selector.length || parser.name === COMBINATOR) {
tokens.push(token);
token = Selector._getToken(token);
if (parser.name === COMBINATOR) {
token.combinator = Y.Selector.combinators[match[1]];
}
}
found = true;
}
}
} while (found && selector.length);
if (!found || selector.length) { // not fully parsed
Y.log('query: ' + query + ' contains unsupported token in: ' + selector, 'warn', 'Selector');
tokens = [];
}
return tokens;
},
_replaceMarkers: function(selector) {
selector = selector.replace(/\[/g, '\uE003');
selector = selector.replace(/\]/g, '\uE004');
selector = selector.replace(/\(/g, '\uE005');
selector = selector.replace(/\)/g, '\uE006');
return selector;
},
_replaceShorthand: function(selector) {
var shorthand = Y.Selector.shorthand,
re;
for (re in shorthand) {
if (shorthand.hasOwnProperty(re)) {
selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]);
}
}
return selector;
},
_parseSelector: function(selector) {
var replaced = Y.Selector._replaceSelector(selector),
selector = replaced.selector;
// replace shorthand (".foo, #bar") after pseudos and attrs
// to avoid replacing unescaped chars
selector = Y.Selector._replaceShorthand(selector);
selector = Y.Selector._restore('attr', selector, replaced.attrs);
selector = Y.Selector._restore('pseudo', selector, replaced.pseudos);
// replace braces and parens before restoring escaped chars
// to avoid replacing ecaped markers
selector = Y.Selector._replaceMarkers(selector);
selector = Y.Selector._restore('esc', selector, replaced.esc);
return selector;
},
_attrFilters: {
'class': 'className',
'for': 'htmlFor'
},
getters: {
href: function(node, attr) {
return Y.DOM.getAttribute(node, attr);
},
id: function(node, attr) {
return Y.DOM.getId(node);
}
}
};
Y.mix(Y.Selector, SelectorCSS2, true);
Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href;
// IE wants class with native queries
if (Y.Selector.useNative && Y.config.doc.querySelector) {
Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]';
}
}, '@VERSION@', {"requires": ["selector-native"]});
YUI.add('selector-css3', function (Y, NAME) {
/**
* The selector css3 module provides support for css3 selectors.
* @module dom
* @submodule selector-css3
* @for Selector
*/
/*
an+b = get every _a_th node starting at the _b_th
0n+b = no repeat ("0" and "n" may both be omitted (together) , e.g. "0n+1" or "1", not "0+1"), return only the _b_th element
1n+b = get every element starting from b ("1" may may be omitted, e.g. "1n+0" or "n+0" or "n")
an+0 = get every _a_th element, "0" may be omitted
*/
Y.Selector._reNth = /^(?:([\-]?\d*)(n){1}|(odd|even)$)*([\-+]?\d*)$/;
Y.Selector._getNth = function(node, expr, tag, reverse) {
Y.Selector._reNth.test(expr);
var a = parseInt(RegExp.$1, 10), // include every _a_ elements (zero means no repeat, just first _a_)
n = RegExp.$2, // "n"
oddeven = RegExp.$3, // "odd" or "even"
b = parseInt(RegExp.$4, 10) || 0, // start scan from element _b_
result = [],
siblings = Y.DOM._children(node.parentNode, tag),
op;
if (oddeven) {
a = 2; // always every other
op = '+';
n = 'n';
b = (oddeven === 'odd') ? 1 : 0;
} else if ( isNaN(a) ) {
a = (n) ? 1 : 0; // start from the first or no repeat
}
if (a === 0) { // just the first
if (reverse) {
b = siblings.length - b + 1;
}
if (siblings[b - 1] === node) {
return true;
} else {
return false;
}
} else if (a < 0) {
reverse = !!reverse;
a = Math.abs(a);
}
if (!reverse) {
for (var i = b - 1, len = siblings.length; i < len; i += a) {
if ( i >= 0 && siblings[i] === node ) {
return true;
}
}
} else {
for (var i = siblings.length - b, len = siblings.length; i >= 0; i -= a) {
if ( i < len && siblings[i] === node ) {
return true;
}
}
}
return false;
};
Y.mix(Y.Selector.pseudos, {
'root': function(node) {
return node === node.ownerDocument.documentElement;
},
'nth-child': function(node, expr) {
return Y.Selector._getNth(node, expr);
},
'nth-last-child': function(node, expr) {
return Y.Selector._getNth(node, expr, null, true);
},
'nth-of-type': function(node, expr) {
return Y.Selector._getNth(node, expr, node.tagName);
},
'nth-last-of-type': function(node, expr) {
return Y.Selector._getNth(node, expr, node.tagName, true);
},
'last-child': function(node) {
var children = Y.DOM._children(node.parentNode);
return children[children.length - 1] === node;
},
'first-of-type': function(node) {
return Y.DOM._children(node.parentNode, node.tagName)[0] === node;
},
'last-of-type': function(node) {
var children = Y.DOM._children(node.parentNode, node.tagName);
return children[children.length - 1] === node;
},
'only-child': function(node) {
var children = Y.DOM._children(node.parentNode);
return children.length === 1 && children[0] === node;
},
'only-of-type': function(node) {
var children = Y.DOM._children(node.parentNode, node.tagName);
return children.length === 1 && children[0] === node;
},
'empty': function(node) {
return node.childNodes.length === 0;
},
'not': function(node, expr) {
return !Y.Selector.test(node, expr);
},
'contains': function(node, expr) {
var text = node.innerText || node.textContent || '';
return text.indexOf(expr) > -1;
},
'checked': function(node) {
return (node.checked === true || node.selected === true);
},
enabled: function(node) {
return (node.disabled !== undefined && !node.disabled);
},
disabled: function(node) {
return (node.disabled);
}
});
Y.mix(Y.Selector.operators, {
'^=': '^{val}', // Match starts with value
'$=': '{val}$', // Match ends with value
'*=': '{val}' // Match contains value as substring
});
Y.Selector.combinators['~'] = {
axis: 'previousSibling'
};
}, '@VERSION@', {"requires": ["selector-native", "selector-css2"]});
YUI.add('yui-log', function (Y, NAME) {
/**
* Provides console log capability and exposes a custom event for
* console implementations. This module is a `core` YUI module,
* <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>.
*
* @module yui
* @submodule yui-log
*/
var INSTANCE = Y,
LOGEVENT = 'yui:log',
UNDEFINED = 'undefined',
LEVELS = { debug: 1,
info: 2,
warn: 4,
error: 8 };
/**
* If the 'debug' config is true, a 'yui:log' event will be
* dispatched, which the Console widget and anything else
* can consume. If the 'useBrowserConsole' config is true, it will
* write to the browser console if available. YUI-specific log
* messages will only be present in the -debug versions of the
* JS files. The build system is supposed to remove log statements
* from the raw and minified versions of the files.
*
* @method log
* @for YUI
* @param {String} msg The message to log.
* @param {String} cat The log category for the message. Default
* categories are "info", "warn", "error", time".
* Custom categories can be used as well. (opt).
* @param {String} src The source of the the message (opt).
* @param {boolean} silent If true, the log event won't fire.
* @return {YUI} YUI instance.
*/
INSTANCE.log = function(msg, cat, src, silent) {
var bail, excl, incl, m, f, minlevel,
Y = INSTANCE,
c = Y.config,
publisher = (Y.fire) ? Y : YUI.Env.globalEvents;
// suppress log message if the config is off or the event stack
// or the event call stack contains a consumer of the yui:log event
if (c.debug) {
// apply source filters
src = src || "";
if (typeof src !== "undefined") {
excl = c.logExclude;
incl = c.logInclude;
if (incl && !(src in incl)) {
bail = 1;
} else if (incl && (src in incl)) {
bail = !incl[src];
} else if (excl && (src in excl)) {
bail = excl[src];
}
// Determine the current minlevel as defined in configuration
Y.config.logLevel = Y.config.logLevel || 'debug';
minlevel = LEVELS[Y.config.logLevel.toLowerCase()];
if (cat in LEVELS && LEVELS[cat] < minlevel) {
// Skip this message if the we don't meet the defined minlevel
bail = 1;
}
}
if (!bail) {
if (c.useBrowserConsole) {
m = (src) ? src + ': ' + msg : msg;
if (Y.Lang.isFunction(c.logFn)) {
c.logFn.call(Y, msg, cat, src);
} else if (typeof console !== UNDEFINED && console.log) {
f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log';
console[f](m);
} else if (typeof opera !== UNDEFINED) {
opera.postError(m);
}
}
if (publisher && !silent) {
if (publisher === Y && (!publisher.getEvent(LOGEVENT))) {
publisher.publish(LOGEVENT, {
broadcast: 2
});
}
publisher.fire(LOGEVENT, {
msg: msg,
cat: cat,
src: src
});
}
}
}
return Y;
};
/**
* Write a system message. This message will be preserved in the
* minified and raw versions of the YUI files, unlike log statements.
* @method message
* @for YUI
* @param {String} msg The message to log.
* @param {String} cat The log category for the message. Default
* categories are "info", "warn", "error", time".
* Custom categories can be used as well. (opt).
* @param {String} src The source of the the message (opt).
* @param {boolean} silent If true, the log event won't fire.
* @return {YUI} YUI instance.
*/
INSTANCE.message = function() {
return INSTANCE.log.apply(INSTANCE, arguments);
};
}, '@VERSION@', {"requires": ["yui-base"]});
YUI.add('dump', function (Y, NAME) {
/**
* Returns a simple string representation of the object or array.
* Other types of objects will be returned unprocessed. Arrays
* are expected to be indexed. Use object notation for
* associative arrays.
*
* If included, the dump method is added to the YUI instance.
*
* @module dump
*/
var L = Y.Lang,
OBJ = '{...}',
FUN = 'f(){...}',
COMMA = ', ',
ARROW = ' => ',
/**
* Returns a simple string representation of the object or array.
* Other types of objects will be returned unprocessed. Arrays
* are expected to be indexed.
*
* @method dump
* @param {Object} o The object to dump.
* @param {Number} d How deep to recurse child objects, default 3.
* @return {String} the dump result.
* @for YUI
*/
dump = function(o, d) {
var i, len, s = [], type = L.type(o);
// Cast non-objects to string
// Skip dates because the std toString is what we want
// Skip HTMLElement-like objects because trying to dump
// an element will cause an unhandled exception in FF 2.x
if (!L.isObject(o)) {
return o + '';
} else if (type == 'date') {
return o;
} else if (o.nodeType && o.tagName) {
return o.tagName + '#' + o.id;
} else if (o.document && o.navigator) {
return 'window';
} else if (o.location && o.body) {
return 'document';
} else if (type == 'function') {
return FUN;
}
// dig into child objects the depth specifed. Default 3
d = (L.isNumber(d)) ? d : 3;
// arrays [1, 2, 3]
if (type == 'array') {
s.push('[');
for (i = 0, len = o.length; i < len; i = i + 1) {
if (L.isObject(o[i])) {
s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ);
} else {
s.push(o[i]);
}
s.push(COMMA);
}
if (s.length > 1) {
s.pop();
}
s.push(']');
// regexp /foo/
} else if (type == 'regexp') {
s.push(o.toString());
// objects {k1 => v1, k2 => v2}
} else {
s.push('{');
for (i in o) {
if (o.hasOwnProperty(i)) {
try {
s.push(i + ARROW);
if (L.isObject(o[i])) {
s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ);
} else {
s.push(o[i]);
}
s.push(COMMA);
} catch (e) {
s.push('Error: ' + e.message);
}
}
}
if (s.length > 1) {
s.pop();
}
s.push('}');
}
return s.join('');
};
Y.dump = dump;
L.dump = dump;
}, '@VERSION@', {"requires": ["yui-base"]});
YUI.add('transition-timer', function (Y, NAME) {
/**
* Provides the base Transition class, for animating numeric properties.
*
* @module transition
* @submodule transition-timer
*/
var Transition = Y.Transition;
Y.mix(Transition.prototype, {
_start: function() {
if (Transition.useNative) {
this._runNative();
} else {
this._runTimer();
}
},
_runTimer: function() {
var anim = this;
anim._initAttrs();
Transition._running[Y.stamp(anim)] = anim;
anim._startTime = new Date();
Transition._startTimer();
},
_endTimer: function() {
var anim = this;
delete Transition._running[Y.stamp(anim)];
anim._startTime = null;
},
_runFrame: function() {
var t = new Date() - this._startTime;
this._runAttrs(t);
},
_runAttrs: function(time) {
var anim = this,
node = anim._node,
config = anim._config,
uid = Y.stamp(node),
attrs = Transition._nodeAttrs[uid],
customAttr = Transition.behaviors,
done = false,
allDone = false,
data,
name,
attribute,
setter,
elapsed,
delay,
d,
t,
i;
for (name in attrs) {
if ((attribute = attrs[name]) && attribute.transition === anim) {
d = attribute.duration;
delay = attribute.delay;
elapsed = (time - delay) / 1000;
t = time;
data = {
type: 'propertyEnd',
propertyName: name,
config: config,
elapsedTime: elapsed
};
setter = (i in customAttr && 'set' in customAttr[i]) ?
customAttr[i].set : Transition.DEFAULT_SETTER;
done = (t >= d);
if (t > d) {
t = d;
}
if (!delay || time >= delay) {
setter(anim, name, attribute.from, attribute.to, t - delay, d - delay,
attribute.easing, attribute.unit);
if (done) {
delete attrs[name];
anim._count--;
if (config[name] && config[name].on && config[name].on.end) {
config[name].on.end.call(Y.one(node), data);
}
//node.fire('transition:propertyEnd', data);
if (!allDone && anim._count <= 0) {
allDone = true;
anim._end(elapsed);
anim._endTimer();
}
}
}
}
}
},
_initAttrs: function() {
var anim = this,
customAttr = Transition.behaviors,
uid = Y.stamp(anim._node),
attrs = Transition._nodeAttrs[uid],
attribute,
duration,
delay,
easing,
val,
name,
mTo,
mFrom,
unit, begin, end;
for (name in attrs) {
if ((attribute = attrs[name]) && attribute.transition === anim) {
duration = attribute.duration * 1000;
delay = attribute.delay * 1000;
easing = attribute.easing;
val = attribute.value;
// only allow supported properties
if (name in anim._node.style || name in Y.DOM.CUSTOM_STYLES) {
begin = (name in customAttr && 'get' in customAttr[name]) ?
customAttr[name].get(anim, name) : Transition.DEFAULT_GETTER(anim, name);
mFrom = Transition.RE_UNITS.exec(begin);
mTo = Transition.RE_UNITS.exec(val);
begin = mFrom ? mFrom[1] : begin;
end = mTo ? mTo[1] : val;
unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units
if (!unit && Transition.RE_DEFAULT_UNIT.test(name)) {
unit = Transition.DEFAULT_UNIT;
}
if (typeof easing === 'string') {
if (easing.indexOf('cubic-bezier') > -1) {
easing = easing.substring(13, easing.length - 1).split(',');
} else if (Transition.easings[easing]) {
easing = Transition.easings[easing];
}
}
attribute.from = Number(begin);
attribute.to = Number(end);
attribute.unit = unit;
attribute.easing = easing;
attribute.duration = duration + delay;
attribute.delay = delay;
} else {
delete attrs[name];
anim._count--;
}
}
}
},
destroy: function() {
this.detachAll();
this._node = null;
}
}, true);
Y.mix(Y.Transition, {
_runtimeAttrs: {},
/*
* Regex of properties that should use the default unit.
*
* @property RE_DEFAULT_UNIT
* @static
*/
RE_DEFAULT_UNIT: /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i,
/*
* The default unit to use with properties that pass the RE_DEFAULT_UNIT test.
*
* @property DEFAULT_UNIT
* @static
*/
DEFAULT_UNIT: 'px',
/*
* Time in milliseconds passed to setInterval for frame processing
*
* @property intervalTime
* @default 20
* @static
*/
intervalTime: 20,
/*
* Bucket for custom getters and setters
*
* @property behaviors
* @static
*/
behaviors: {
left: {
get: function(anim, attr) {
return Y.DOM._getAttrOffset(anim._node, attr);
}
}
},
/*
* The default setter to use when setting object properties.
*
* @property DEFAULT_SETTER
* @static
*/
DEFAULT_SETTER: function(anim, att, from, to, elapsed, duration, fn, unit) {
from = Number(from);
to = Number(to);
var node = anim._node,
val = Transition.cubicBezier(fn, elapsed / duration);
val = from + val[0] * (to - from);
if (node) {
if (att in node.style || att in Y.DOM.CUSTOM_STYLES) {
unit = unit || '';
Y.DOM.setStyle(node, att, val + unit);
}
} else {
anim._end();
}
},
/*
* The default getter to use when getting object properties.
*
* @property DEFAULT_GETTER
* @static
*/
DEFAULT_GETTER: function(anim, att) {
var node = anim._node,
val = '';
if (att in node.style || att in Y.DOM.CUSTOM_STYLES) {
val = Y.DOM.getComputedStyle(node, att);
}
return val;
},
_startTimer: function() {
if (!Transition._timer) {
Transition._timer = setInterval(Transition._runFrame, Transition.intervalTime);
}
},
_stopTimer: function() {
clearInterval(Transition._timer);
Transition._timer = null;
},
/*
* Called per Interval to handle each animation frame.
* @method _runFrame
* @private
* @static
*/
_runFrame: function() {
var done = true,
anim;
for (anim in Transition._running) {
if (Transition._running[anim]._runFrame) {
done = false;
Transition._running[anim]._runFrame();
}
}
if (done) {
Transition._stopTimer();
}
},
cubicBezier: function(p, t) {
var x0 = 0,
y0 = 0,
x1 = p[0],
y1 = p[1],
x2 = p[2],
y2 = p[3],
x3 = 1,
y3 = 0,
A = x3 - 3 * x2 + 3 * x1 - x0,
B = 3 * x2 - 6 * x1 + 3 * x0,
C = 3 * x1 - 3 * x0,
D = x0,
E = y3 - 3 * y2 + 3 * y1 - y0,
F = 3 * y2 - 6 * y1 + 3 * y0,
G = 3 * y1 - 3 * y0,
H = y0,
x = (((A*t) + B)*t + C)*t + D,
y = (((E*t) + F)*t + G)*t + H;
return [x, y];
},
easings: {
ease: [0.25, 0, 1, 0.25],
linear: [0, 0, 1, 1],
'ease-in': [0.42, 0, 1, 1],
'ease-out': [0, 0, 0.58, 1],
'ease-in-out': [0.42, 0, 0.58, 1]
},
_running: {},
_timer: null,
RE_UNITS: /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/
}, true);
Transition.behaviors.top = Transition.behaviors.bottom = Transition.behaviors.right = Transition.behaviors.left;
Y.Transition = Transition;
}, '@VERSION@', {"requires": ["transition"]});
YUI.add('yui', function (Y, NAME) {
// empty
}, '@VERSION@', {
"use": [
"yui",
"oop",
"dom",
"event-custom-base",
"event-base",
"pluginhost",
"node",
"event-delegate",
"io-base",
"json-parse",
"transition",
"selector-css3",
"dom-style-ie",
"querystring-stringify-simple"
]
});
var Y = YUI().use('*');
|
src/svg-icons/editor/publish.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorPublish = (props) => (
<SvgIcon {...props}>
<path d="M5 4v2h14V4H5zm0 10h4v6h6v-6h4l-7-7-7 7z"/>
</SvgIcon>
);
EditorPublish = pure(EditorPublish);
EditorPublish.displayName = 'EditorPublish';
EditorPublish.muiName = 'SvgIcon';
export default EditorPublish;
|
ajax/libs/clappr/0.0.79/clappr.js | callumacrae/cdnjs | require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (global){
"use strict";
var Player = require('./components/player');
var IframePlayer = require('./components/iframe_player');
var Mediator = require('mediator');
var version = require('../package.json').version;
global.DEBUG = false;
window.Clappr = {
Player: Player,
Mediator: Mediator,
IframePlayer: IframePlayer
};
window.Clappr.version = version;
module.exports = window.Clappr;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../package.json":6,"./components/iframe_player":17,"./components/player":21,"mediator":"mediator"}],2:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canMutationObserver = typeof window !== 'undefined'
&& window.MutationObserver;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
var queue = [];
if (canMutationObserver) {
var hiddenDiv = document.createElement("div");
var observer = new MutationObserver(function () {
var queueList = queue.slice();
queue.length = 0;
queueList.forEach(function (fn) {
fn();
});
});
observer.observe(hiddenDiv, { attributes: true });
return function nextTick(fn) {
if (!queue.length) {
hiddenDiv.setAttribute('yes', 'no');
}
queue.push(fn);
};
}
if (canPost) {
window.addEventListener('message', function (ev) {
var source = ev.source;
if ((source === window || source === null) && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage('process-tick', '*');
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
},{}],3:[function(require,module,exports){
(function (process,global){
(function(global) {
'use strict';
if (global.$traceurRuntime) {
return;
}
var $Object = Object;
var $TypeError = TypeError;
var $create = $Object.create;
var $defineProperties = $Object.defineProperties;
var $defineProperty = $Object.defineProperty;
var $freeze = $Object.freeze;
var $getOwnPropertyDescriptor = $Object.getOwnPropertyDescriptor;
var $getOwnPropertyNames = $Object.getOwnPropertyNames;
var $keys = $Object.keys;
var $hasOwnProperty = $Object.prototype.hasOwnProperty;
var $toString = $Object.prototype.toString;
var $preventExtensions = Object.preventExtensions;
var $seal = Object.seal;
var $isExtensible = Object.isExtensible;
function nonEnum(value) {
return {
configurable: true,
enumerable: false,
value: value,
writable: true
};
}
var types = {
void: function voidType() {},
any: function any() {},
string: function string() {},
number: function number() {},
boolean: function boolean() {}
};
var method = nonEnum;
var counter = 0;
function newUniqueString() {
return '__$' + Math.floor(Math.random() * 1e9) + '$' + ++counter + '$__';
}
var symbolInternalProperty = newUniqueString();
var symbolDescriptionProperty = newUniqueString();
var symbolDataProperty = newUniqueString();
var symbolValues = $create(null);
var privateNames = $create(null);
function createPrivateName() {
var s = newUniqueString();
privateNames[s] = true;
return s;
}
function isSymbol(symbol) {
return typeof symbol === 'object' && symbol instanceof SymbolValue;
}
function typeOf(v) {
if (isSymbol(v))
return 'symbol';
return typeof v;
}
function Symbol(description) {
var value = new SymbolValue(description);
if (!(this instanceof Symbol))
return value;
throw new TypeError('Symbol cannot be new\'ed');
}
$defineProperty(Symbol.prototype, 'constructor', nonEnum(Symbol));
$defineProperty(Symbol.prototype, 'toString', method(function() {
var symbolValue = this[symbolDataProperty];
if (!getOption('symbols'))
return symbolValue[symbolInternalProperty];
if (!symbolValue)
throw TypeError('Conversion from symbol to string');
var desc = symbolValue[symbolDescriptionProperty];
if (desc === undefined)
desc = '';
return 'Symbol(' + desc + ')';
}));
$defineProperty(Symbol.prototype, 'valueOf', method(function() {
var symbolValue = this[symbolDataProperty];
if (!symbolValue)
throw TypeError('Conversion from symbol to string');
if (!getOption('symbols'))
return symbolValue[symbolInternalProperty];
return symbolValue;
}));
function SymbolValue(description) {
var key = newUniqueString();
$defineProperty(this, symbolDataProperty, {value: this});
$defineProperty(this, symbolInternalProperty, {value: key});
$defineProperty(this, symbolDescriptionProperty, {value: description});
freeze(this);
symbolValues[key] = this;
}
$defineProperty(SymbolValue.prototype, 'constructor', nonEnum(Symbol));
$defineProperty(SymbolValue.prototype, 'toString', {
value: Symbol.prototype.toString,
enumerable: false
});
$defineProperty(SymbolValue.prototype, 'valueOf', {
value: Symbol.prototype.valueOf,
enumerable: false
});
var hashProperty = createPrivateName();
var hashPropertyDescriptor = {value: undefined};
var hashObjectProperties = {
hash: {value: undefined},
self: {value: undefined}
};
var hashCounter = 0;
function getOwnHashObject(object) {
var hashObject = object[hashProperty];
if (hashObject && hashObject.self === object)
return hashObject;
if ($isExtensible(object)) {
hashObjectProperties.hash.value = hashCounter++;
hashObjectProperties.self.value = object;
hashPropertyDescriptor.value = $create(null, hashObjectProperties);
$defineProperty(object, hashProperty, hashPropertyDescriptor);
return hashPropertyDescriptor.value;
}
return undefined;
}
function freeze(object) {
getOwnHashObject(object);
return $freeze.apply(this, arguments);
}
function preventExtensions(object) {
getOwnHashObject(object);
return $preventExtensions.apply(this, arguments);
}
function seal(object) {
getOwnHashObject(object);
return $seal.apply(this, arguments);
}
Symbol.iterator = Symbol();
freeze(SymbolValue.prototype);
function toProperty(name) {
if (isSymbol(name))
return name[symbolInternalProperty];
return name;
}
function getOwnPropertyNames(object) {
var rv = [];
var names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var name = names[i];
if (!symbolValues[name] && !privateNames[name])
rv.push(name);
}
return rv;
}
function getOwnPropertyDescriptor(object, name) {
return $getOwnPropertyDescriptor(object, toProperty(name));
}
function getOwnPropertySymbols(object) {
var rv = [];
var names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var symbol = symbolValues[names[i]];
if (symbol)
rv.push(symbol);
}
return rv;
}
function hasOwnProperty(name) {
return $hasOwnProperty.call(this, toProperty(name));
}
function getOption(name) {
return global.traceur && global.traceur.options[name];
}
function setProperty(object, name, value) {
var sym,
desc;
if (isSymbol(name)) {
sym = name;
name = name[symbolInternalProperty];
}
object[name] = value;
if (sym && (desc = $getOwnPropertyDescriptor(object, name)))
$defineProperty(object, name, {enumerable: false});
return value;
}
function defineProperty(object, name, descriptor) {
if (isSymbol(name)) {
if (descriptor.enumerable) {
descriptor = $create(descriptor, {enumerable: {value: false}});
}
name = name[symbolInternalProperty];
}
$defineProperty(object, name, descriptor);
return object;
}
function polyfillObject(Object) {
$defineProperty(Object, 'defineProperty', {value: defineProperty});
$defineProperty(Object, 'getOwnPropertyNames', {value: getOwnPropertyNames});
$defineProperty(Object, 'getOwnPropertyDescriptor', {value: getOwnPropertyDescriptor});
$defineProperty(Object.prototype, 'hasOwnProperty', {value: hasOwnProperty});
$defineProperty(Object, 'freeze', {value: freeze});
$defineProperty(Object, 'preventExtensions', {value: preventExtensions});
$defineProperty(Object, 'seal', {value: seal});
Object.getOwnPropertySymbols = getOwnPropertySymbols;
}
function exportStar(object) {
for (var i = 1; i < arguments.length; i++) {
var names = $getOwnPropertyNames(arguments[i]);
for (var j = 0; j < names.length; j++) {
var name = names[j];
if (privateNames[name])
continue;
(function(mod, name) {
$defineProperty(object, name, {
get: function() {
return mod[name];
},
enumerable: true
});
})(arguments[i], names[j]);
}
}
return object;
}
function isObject(x) {
return x != null && (typeof x === 'object' || typeof x === 'function');
}
function toObject(x) {
if (x == null)
throw $TypeError();
return $Object(x);
}
function checkObjectCoercible(argument) {
if (argument == null) {
throw new TypeError('Value cannot be converted to an Object');
}
return argument;
}
function setupGlobals(global) {
global.Symbol = Symbol;
global.Reflect = global.Reflect || {};
global.Reflect.global = global.Reflect.global || global;
polyfillObject(global.Object);
}
setupGlobals(global);
global.$traceurRuntime = {
createPrivateName: createPrivateName,
exportStar: exportStar,
getOwnHashObject: getOwnHashObject,
privateNames: privateNames,
setProperty: setProperty,
setupGlobals: setupGlobals,
toObject: toObject,
isObject: isObject,
toProperty: toProperty,
type: types,
typeof: typeOf,
checkObjectCoercible: checkObjectCoercible,
hasOwnProperty: function(o, p) {
return hasOwnProperty.call(o, p);
},
defineProperties: $defineProperties,
defineProperty: $defineProperty,
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
getOwnPropertyNames: $getOwnPropertyNames,
keys: $keys
};
})(typeof global !== 'undefined' ? global : this);
(function() {
'use strict';
function spread() {
var rv = [],
j = 0,
iterResult;
for (var i = 0; i < arguments.length; i++) {
var valueToSpread = $traceurRuntime.checkObjectCoercible(arguments[i]);
if (typeof valueToSpread[$traceurRuntime.toProperty(Symbol.iterator)] !== 'function') {
throw new TypeError('Cannot spread non-iterable object.');
}
var iter = valueToSpread[$traceurRuntime.toProperty(Symbol.iterator)]();
while (!(iterResult = iter.next()).done) {
rv[j++] = iterResult.value;
}
}
return rv;
}
$traceurRuntime.spread = spread;
})();
(function() {
'use strict';
var $Object = Object;
var $TypeError = TypeError;
var $create = $Object.create;
var $defineProperties = $traceurRuntime.defineProperties;
var $defineProperty = $traceurRuntime.defineProperty;
var $getOwnPropertyDescriptor = $traceurRuntime.getOwnPropertyDescriptor;
var $getOwnPropertyNames = $traceurRuntime.getOwnPropertyNames;
var $getPrototypeOf = Object.getPrototypeOf;
function superDescriptor(homeObject, name) {
var proto = $getPrototypeOf(homeObject);
do {
var result = $getOwnPropertyDescriptor(proto, name);
if (result)
return result;
proto = $getPrototypeOf(proto);
} while (proto);
return undefined;
}
function superCall(self, homeObject, name, args) {
return superGet(self, homeObject, name).apply(self, args);
}
function superGet(self, homeObject, name) {
var descriptor = superDescriptor(homeObject, name);
if (descriptor) {
if (!descriptor.get)
return descriptor.value;
return descriptor.get.call(self);
}
return undefined;
}
function superSet(self, homeObject, name, value) {
var descriptor = superDescriptor(homeObject, name);
if (descriptor && descriptor.set) {
descriptor.set.call(self, value);
return value;
}
throw $TypeError("super has no setter '" + name + "'.");
}
function getDescriptors(object) {
var descriptors = {},
name,
names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var name = names[i];
descriptors[name] = $getOwnPropertyDescriptor(object, name);
}
return descriptors;
}
function createClass(ctor, object, staticObject, superClass) {
$defineProperty(object, 'constructor', {
value: ctor,
configurable: true,
enumerable: false,
writable: true
});
if (arguments.length > 3) {
if (typeof superClass === 'function')
ctor.__proto__ = superClass;
ctor.prototype = $create(getProtoParent(superClass), getDescriptors(object));
} else {
ctor.prototype = object;
}
$defineProperty(ctor, 'prototype', {
configurable: false,
writable: false
});
return $defineProperties(ctor, getDescriptors(staticObject));
}
function getProtoParent(superClass) {
if (typeof superClass === 'function') {
var prototype = superClass.prototype;
if ($Object(prototype) === prototype || prototype === null)
return superClass.prototype;
throw new $TypeError('super prototype must be an Object or null');
}
if (superClass === null)
return null;
throw new $TypeError(("Super expression must either be null or a function, not " + typeof superClass + "."));
}
function defaultSuperCall(self, homeObject, args) {
if ($getPrototypeOf(homeObject) !== null)
superCall(self, homeObject, 'constructor', args);
}
$traceurRuntime.createClass = createClass;
$traceurRuntime.defaultSuperCall = defaultSuperCall;
$traceurRuntime.superCall = superCall;
$traceurRuntime.superGet = superGet;
$traceurRuntime.superSet = superSet;
})();
(function() {
'use strict';
var createPrivateName = $traceurRuntime.createPrivateName;
var $defineProperties = $traceurRuntime.defineProperties;
var $defineProperty = $traceurRuntime.defineProperty;
var $create = Object.create;
var $TypeError = TypeError;
function nonEnum(value) {
return {
configurable: true,
enumerable: false,
value: value,
writable: true
};
}
var ST_NEWBORN = 0;
var ST_EXECUTING = 1;
var ST_SUSPENDED = 2;
var ST_CLOSED = 3;
var END_STATE = -2;
var RETHROW_STATE = -3;
function getInternalError(state) {
return new Error('Traceur compiler bug: invalid state in state machine: ' + state);
}
function GeneratorContext() {
this.state = 0;
this.GState = ST_NEWBORN;
this.storedException = undefined;
this.finallyFallThrough = undefined;
this.sent_ = undefined;
this.returnValue = undefined;
this.tryStack_ = [];
}
GeneratorContext.prototype = {
pushTry: function(catchState, finallyState) {
if (finallyState !== null) {
var finallyFallThrough = null;
for (var i = this.tryStack_.length - 1; i >= 0; i--) {
if (this.tryStack_[i].catch !== undefined) {
finallyFallThrough = this.tryStack_[i].catch;
break;
}
}
if (finallyFallThrough === null)
finallyFallThrough = RETHROW_STATE;
this.tryStack_.push({
finally: finallyState,
finallyFallThrough: finallyFallThrough
});
}
if (catchState !== null) {
this.tryStack_.push({catch: catchState});
}
},
popTry: function() {
this.tryStack_.pop();
},
get sent() {
this.maybeThrow();
return this.sent_;
},
set sent(v) {
this.sent_ = v;
},
get sentIgnoreThrow() {
return this.sent_;
},
maybeThrow: function() {
if (this.action === 'throw') {
this.action = 'next';
throw this.sent_;
}
},
end: function() {
switch (this.state) {
case END_STATE:
return this;
case RETHROW_STATE:
throw this.storedException;
default:
throw getInternalError(this.state);
}
},
handleException: function(ex) {
this.GState = ST_CLOSED;
this.state = END_STATE;
throw ex;
}
};
function nextOrThrow(ctx, moveNext, action, x) {
switch (ctx.GState) {
case ST_EXECUTING:
throw new Error(("\"" + action + "\" on executing generator"));
case ST_CLOSED:
if (action == 'next') {
return {
value: undefined,
done: true
};
}
throw x;
case ST_NEWBORN:
if (action === 'throw') {
ctx.GState = ST_CLOSED;
throw x;
}
if (x !== undefined)
throw $TypeError('Sent value to newborn generator');
case ST_SUSPENDED:
ctx.GState = ST_EXECUTING;
ctx.action = action;
ctx.sent = x;
var value = moveNext(ctx);
var done = value === ctx;
if (done)
value = ctx.returnValue;
ctx.GState = done ? ST_CLOSED : ST_SUSPENDED;
return {
value: value,
done: done
};
}
}
var ctxName = createPrivateName();
var moveNextName = createPrivateName();
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
GeneratorFunction.prototype = GeneratorFunctionPrototype;
$defineProperty(GeneratorFunctionPrototype, 'constructor', nonEnum(GeneratorFunction));
GeneratorFunctionPrototype.prototype = {
constructor: GeneratorFunctionPrototype,
next: function(v) {
return nextOrThrow(this[ctxName], this[moveNextName], 'next', v);
},
throw: function(v) {
return nextOrThrow(this[ctxName], this[moveNextName], 'throw', v);
}
};
$defineProperties(GeneratorFunctionPrototype.prototype, {
constructor: {enumerable: false},
next: {enumerable: false},
throw: {enumerable: false}
});
Object.defineProperty(GeneratorFunctionPrototype.prototype, Symbol.iterator, nonEnum(function() {
return this;
}));
function createGeneratorInstance(innerFunction, functionObject, self) {
var moveNext = getMoveNext(innerFunction, self);
var ctx = new GeneratorContext();
var object = $create(functionObject.prototype);
object[ctxName] = ctx;
object[moveNextName] = moveNext;
return object;
}
function initGeneratorFunction(functionObject) {
functionObject.prototype = $create(GeneratorFunctionPrototype.prototype);
functionObject.__proto__ = GeneratorFunctionPrototype;
return functionObject;
}
function AsyncFunctionContext() {
GeneratorContext.call(this);
this.err = undefined;
var ctx = this;
ctx.result = new Promise(function(resolve, reject) {
ctx.resolve = resolve;
ctx.reject = reject;
});
}
AsyncFunctionContext.prototype = $create(GeneratorContext.prototype);
AsyncFunctionContext.prototype.end = function() {
switch (this.state) {
case END_STATE:
this.resolve(this.returnValue);
break;
case RETHROW_STATE:
this.reject(this.storedException);
break;
default:
this.reject(getInternalError(this.state));
}
};
AsyncFunctionContext.prototype.handleException = function() {
this.state = RETHROW_STATE;
};
function asyncWrap(innerFunction, self) {
var moveNext = getMoveNext(innerFunction, self);
var ctx = new AsyncFunctionContext();
ctx.createCallback = function(newState) {
return function(value) {
ctx.state = newState;
ctx.value = value;
moveNext(ctx);
};
};
ctx.errback = function(err) {
handleCatch(ctx, err);
moveNext(ctx);
};
moveNext(ctx);
return ctx.result;
}
function getMoveNext(innerFunction, self) {
return function(ctx) {
while (true) {
try {
return innerFunction.call(self, ctx);
} catch (ex) {
handleCatch(ctx, ex);
}
}
};
}
function handleCatch(ctx, ex) {
ctx.storedException = ex;
var last = ctx.tryStack_[ctx.tryStack_.length - 1];
if (!last) {
ctx.handleException(ex);
return;
}
ctx.state = last.catch !== undefined ? last.catch : last.finally;
if (last.finallyFallThrough !== undefined)
ctx.finallyFallThrough = last.finallyFallThrough;
}
$traceurRuntime.asyncWrap = asyncWrap;
$traceurRuntime.initGeneratorFunction = initGeneratorFunction;
$traceurRuntime.createGeneratorInstance = createGeneratorInstance;
})();
(function() {
function buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
var out = [];
if (opt_scheme) {
out.push(opt_scheme, ':');
}
if (opt_domain) {
out.push('//');
if (opt_userInfo) {
out.push(opt_userInfo, '@');
}
out.push(opt_domain);
if (opt_port) {
out.push(':', opt_port);
}
}
if (opt_path) {
out.push(opt_path);
}
if (opt_queryData) {
out.push('?', opt_queryData);
}
if (opt_fragment) {
out.push('#', opt_fragment);
}
return out.join('');
}
;
var splitRe = new RegExp('^' + '(?:' + '([^:/?#.]+)' + ':)?' + '(?://' + '(?:([^/?#]*)@)?' + '([\\w\\d\\-\\u0100-\\uffff.%]*)' + '(?::([0-9]+))?' + ')?' + '([^?#]+)?' + '(?:\\?([^#]*))?' + '(?:#(.*))?' + '$');
var ComponentIndex = {
SCHEME: 1,
USER_INFO: 2,
DOMAIN: 3,
PORT: 4,
PATH: 5,
QUERY_DATA: 6,
FRAGMENT: 7
};
function split(uri) {
return (uri.match(splitRe));
}
function removeDotSegments(path) {
if (path === '/')
return '/';
var leadingSlash = path[0] === '/' ? '/' : '';
var trailingSlash = path.slice(-1) === '/' ? '/' : '';
var segments = path.split('/');
var out = [];
var up = 0;
for (var pos = 0; pos < segments.length; pos++) {
var segment = segments[pos];
switch (segment) {
case '':
case '.':
break;
case '..':
if (out.length)
out.pop();
else
up++;
break;
default:
out.push(segment);
}
}
if (!leadingSlash) {
while (up-- > 0) {
out.unshift('..');
}
if (out.length === 0)
out.push('.');
}
return leadingSlash + out.join('/') + trailingSlash;
}
function joinAndCanonicalizePath(parts) {
var path = parts[ComponentIndex.PATH] || '';
path = removeDotSegments(path);
parts[ComponentIndex.PATH] = path;
return buildFromEncodedParts(parts[ComponentIndex.SCHEME], parts[ComponentIndex.USER_INFO], parts[ComponentIndex.DOMAIN], parts[ComponentIndex.PORT], parts[ComponentIndex.PATH], parts[ComponentIndex.QUERY_DATA], parts[ComponentIndex.FRAGMENT]);
}
function canonicalizeUrl(url) {
var parts = split(url);
return joinAndCanonicalizePath(parts);
}
function resolveUrl(base, url) {
var parts = split(url);
var baseParts = split(base);
if (parts[ComponentIndex.SCHEME]) {
return joinAndCanonicalizePath(parts);
} else {
parts[ComponentIndex.SCHEME] = baseParts[ComponentIndex.SCHEME];
}
for (var i = ComponentIndex.SCHEME; i <= ComponentIndex.PORT; i++) {
if (!parts[i]) {
parts[i] = baseParts[i];
}
}
if (parts[ComponentIndex.PATH][0] == '/') {
return joinAndCanonicalizePath(parts);
}
var path = baseParts[ComponentIndex.PATH];
var index = path.lastIndexOf('/');
path = path.slice(0, index + 1) + parts[ComponentIndex.PATH];
parts[ComponentIndex.PATH] = path;
return joinAndCanonicalizePath(parts);
}
function isAbsolute(name) {
if (!name)
return false;
if (name[0] === '/')
return true;
var parts = split(name);
if (parts[ComponentIndex.SCHEME])
return true;
return false;
}
$traceurRuntime.canonicalizeUrl = canonicalizeUrl;
$traceurRuntime.isAbsolute = isAbsolute;
$traceurRuntime.removeDotSegments = removeDotSegments;
$traceurRuntime.resolveUrl = resolveUrl;
})();
(function(global) {
'use strict';
var $__2 = $traceurRuntime,
canonicalizeUrl = $__2.canonicalizeUrl,
resolveUrl = $__2.resolveUrl,
isAbsolute = $__2.isAbsolute;
var moduleInstantiators = Object.create(null);
var baseURL;
if (global.location && global.location.href)
baseURL = resolveUrl(global.location.href, './');
else
baseURL = '';
var UncoatedModuleEntry = function UncoatedModuleEntry(url, uncoatedModule) {
this.url = url;
this.value_ = uncoatedModule;
};
($traceurRuntime.createClass)(UncoatedModuleEntry, {}, {});
var ModuleEvaluationError = function ModuleEvaluationError(erroneousModuleName, cause) {
this.message = this.constructor.name + ': ' + this.stripCause(cause) + ' in ' + erroneousModuleName;
if (!(cause instanceof $ModuleEvaluationError) && cause.stack)
this.stack = this.stripStack(cause.stack);
else
this.stack = '';
};
var $ModuleEvaluationError = ModuleEvaluationError;
($traceurRuntime.createClass)(ModuleEvaluationError, {
stripError: function(message) {
return message.replace(/.*Error:/, this.constructor.name + ':');
},
stripCause: function(cause) {
if (!cause)
return '';
if (!cause.message)
return cause + '';
return this.stripError(cause.message);
},
loadedBy: function(moduleName) {
this.stack += '\n loaded by ' + moduleName;
},
stripStack: function(causeStack) {
var stack = [];
causeStack.split('\n').some((function(frame) {
if (/UncoatedModuleInstantiator/.test(frame))
return true;
stack.push(frame);
}));
stack[0] = this.stripError(stack[0]);
return stack.join('\n');
}
}, {}, Error);
var UncoatedModuleInstantiator = function UncoatedModuleInstantiator(url, func) {
$traceurRuntime.superCall(this, $UncoatedModuleInstantiator.prototype, "constructor", [url, null]);
this.func = func;
};
var $UncoatedModuleInstantiator = UncoatedModuleInstantiator;
($traceurRuntime.createClass)(UncoatedModuleInstantiator, {getUncoatedModule: function() {
if (this.value_)
return this.value_;
try {
return this.value_ = this.func.call(global);
} catch (ex) {
if (ex instanceof ModuleEvaluationError) {
ex.loadedBy(this.url);
throw ex;
}
throw new ModuleEvaluationError(this.url, ex);
}
}}, {}, UncoatedModuleEntry);
function getUncoatedModuleInstantiator(name) {
if (!name)
return;
var url = ModuleStore.normalize(name);
return moduleInstantiators[url];
}
;
var moduleInstances = Object.create(null);
var liveModuleSentinel = {};
function Module(uncoatedModule) {
var isLive = arguments[1];
var coatedModule = Object.create(null);
Object.getOwnPropertyNames(uncoatedModule).forEach((function(name) {
var getter,
value;
if (isLive === liveModuleSentinel) {
var descr = Object.getOwnPropertyDescriptor(uncoatedModule, name);
if (descr.get)
getter = descr.get;
}
if (!getter) {
value = uncoatedModule[name];
getter = function() {
return value;
};
}
Object.defineProperty(coatedModule, name, {
get: getter,
enumerable: true
});
}));
Object.preventExtensions(coatedModule);
return coatedModule;
}
var ModuleStore = {
normalize: function(name, refererName, refererAddress) {
if (typeof name !== "string")
throw new TypeError("module name must be a string, not " + typeof name);
if (isAbsolute(name))
return canonicalizeUrl(name);
if (/[^\.]\/\.\.\//.test(name)) {
throw new Error('module name embeds /../: ' + name);
}
if (name[0] === '.' && refererName)
return resolveUrl(refererName, name);
return canonicalizeUrl(name);
},
get: function(normalizedName) {
var m = getUncoatedModuleInstantiator(normalizedName);
if (!m)
return undefined;
var moduleInstance = moduleInstances[m.url];
if (moduleInstance)
return moduleInstance;
moduleInstance = Module(m.getUncoatedModule(), liveModuleSentinel);
return moduleInstances[m.url] = moduleInstance;
},
set: function(normalizedName, module) {
normalizedName = String(normalizedName);
moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, (function() {
return module;
}));
moduleInstances[normalizedName] = module;
},
get baseURL() {
return baseURL;
},
set baseURL(v) {
baseURL = String(v);
},
registerModule: function(name, func) {
var normalizedName = ModuleStore.normalize(name);
if (moduleInstantiators[normalizedName])
throw new Error('duplicate module named ' + normalizedName);
moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, func);
},
bundleStore: Object.create(null),
register: function(name, deps, func) {
if (!deps || !deps.length && !func.length) {
this.registerModule(name, func);
} else {
this.bundleStore[name] = {
deps: deps,
execute: function() {
var $__0 = arguments;
var depMap = {};
deps.forEach((function(dep, index) {
return depMap[dep] = $__0[index];
}));
var registryEntry = func.call(this, depMap);
registryEntry.execute.call(this);
return registryEntry.exports;
}
};
}
},
getAnonymousModule: function(func) {
return new Module(func.call(global), liveModuleSentinel);
},
getForTesting: function(name) {
var $__0 = this;
if (!this.testingPrefix_) {
Object.keys(moduleInstances).some((function(key) {
var m = /(traceur@[^\/]*\/)/.exec(key);
if (m) {
$__0.testingPrefix_ = m[1];
return true;
}
}));
}
return this.get(this.testingPrefix_ + name);
}
};
ModuleStore.set('@traceur/src/runtime/ModuleStore', new Module({ModuleStore: ModuleStore}));
var setupGlobals = $traceurRuntime.setupGlobals;
$traceurRuntime.setupGlobals = function(global) {
setupGlobals(global);
};
$traceurRuntime.ModuleStore = ModuleStore;
global.System = {
register: ModuleStore.register.bind(ModuleStore),
get: ModuleStore.get,
set: ModuleStore.set,
normalize: ModuleStore.normalize
};
$traceurRuntime.getModuleImpl = function(name) {
var instantiator = getUncoatedModuleInstantiator(name);
return instantiator && instantiator.getUncoatedModule();
};
})(typeof global !== 'undefined' ? global : this);
System.register("[email protected]/src/runtime/polyfills/utils", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/utils";
var $ceil = Math.ceil;
var $floor = Math.floor;
var $isFinite = isFinite;
var $isNaN = isNaN;
var $pow = Math.pow;
var $min = Math.min;
var toObject = $traceurRuntime.toObject;
function toUint32(x) {
return x >>> 0;
}
function isObject(x) {
return x && (typeof x === 'object' || typeof x === 'function');
}
function isCallable(x) {
return typeof x === 'function';
}
function isNumber(x) {
return typeof x === 'number';
}
function toInteger(x) {
x = +x;
if ($isNaN(x))
return 0;
if (x === 0 || !$isFinite(x))
return x;
return x > 0 ? $floor(x) : $ceil(x);
}
var MAX_SAFE_LENGTH = $pow(2, 53) - 1;
function toLength(x) {
var len = toInteger(x);
return len < 0 ? 0 : $min(len, MAX_SAFE_LENGTH);
}
function checkIterable(x) {
return !isObject(x) ? undefined : x[Symbol.iterator];
}
function isConstructor(x) {
return isCallable(x);
}
function createIteratorResultObject(value, done) {
return {
value: value,
done: done
};
}
function maybeDefine(object, name, descr) {
if (!(name in object)) {
Object.defineProperty(object, name, descr);
}
}
function maybeDefineMethod(object, name, value) {
maybeDefine(object, name, {
value: value,
configurable: true,
enumerable: false,
writable: true
});
}
function maybeDefineConst(object, name, value) {
maybeDefine(object, name, {
value: value,
configurable: false,
enumerable: false,
writable: false
});
}
function maybeAddFunctions(object, functions) {
for (var i = 0; i < functions.length; i += 2) {
var name = functions[i];
var value = functions[i + 1];
maybeDefineMethod(object, name, value);
}
}
function maybeAddConsts(object, consts) {
for (var i = 0; i < consts.length; i += 2) {
var name = consts[i];
var value = consts[i + 1];
maybeDefineConst(object, name, value);
}
}
function maybeAddIterator(object, func, Symbol) {
if (!Symbol || !Symbol.iterator || object[Symbol.iterator])
return;
if (object['@@iterator'])
func = object['@@iterator'];
Object.defineProperty(object, Symbol.iterator, {
value: func,
configurable: true,
enumerable: false,
writable: true
});
}
var polyfills = [];
function registerPolyfill(func) {
polyfills.push(func);
}
function polyfillAll(global) {
polyfills.forEach((function(f) {
return f(global);
}));
}
return {
get toObject() {
return toObject;
},
get toUint32() {
return toUint32;
},
get isObject() {
return isObject;
},
get isCallable() {
return isCallable;
},
get isNumber() {
return isNumber;
},
get toInteger() {
return toInteger;
},
get toLength() {
return toLength;
},
get checkIterable() {
return checkIterable;
},
get isConstructor() {
return isConstructor;
},
get createIteratorResultObject() {
return createIteratorResultObject;
},
get maybeDefine() {
return maybeDefine;
},
get maybeDefineMethod() {
return maybeDefineMethod;
},
get maybeDefineConst() {
return maybeDefineConst;
},
get maybeAddFunctions() {
return maybeAddFunctions;
},
get maybeAddConsts() {
return maybeAddConsts;
},
get maybeAddIterator() {
return maybeAddIterator;
},
get registerPolyfill() {
return registerPolyfill;
},
get polyfillAll() {
return polyfillAll;
}
};
});
System.register("[email protected]/src/runtime/polyfills/Map", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Map";
var $__3 = System.get("[email protected]/src/runtime/polyfills/utils"),
isObject = $__3.isObject,
maybeAddIterator = $__3.maybeAddIterator,
registerPolyfill = $__3.registerPolyfill;
var getOwnHashObject = $traceurRuntime.getOwnHashObject;
var $hasOwnProperty = Object.prototype.hasOwnProperty;
var deletedSentinel = {};
function lookupIndex(map, key) {
if (isObject(key)) {
var hashObject = getOwnHashObject(key);
return hashObject && map.objectIndex_[hashObject.hash];
}
if (typeof key === 'string')
return map.stringIndex_[key];
return map.primitiveIndex_[key];
}
function initMap(map) {
map.entries_ = [];
map.objectIndex_ = Object.create(null);
map.stringIndex_ = Object.create(null);
map.primitiveIndex_ = Object.create(null);
map.deletedCount_ = 0;
}
var Map = function Map() {
var iterable = arguments[0];
if (!isObject(this))
throw new TypeError('Map called on incompatible type');
if ($hasOwnProperty.call(this, 'entries_')) {
throw new TypeError('Map can not be reentrantly initialised');
}
initMap(this);
if (iterable !== null && iterable !== undefined) {
for (var $__5 = iterable[Symbol.iterator](),
$__6; !($__6 = $__5.next()).done; ) {
var $__7 = $__6.value,
key = $__7[0],
value = $__7[1];
{
this.set(key, value);
}
}
}
};
($traceurRuntime.createClass)(Map, {
get size() {
return this.entries_.length / 2 - this.deletedCount_;
},
get: function(key) {
var index = lookupIndex(this, key);
if (index !== undefined)
return this.entries_[index + 1];
},
set: function(key, value) {
var objectMode = isObject(key);
var stringMode = typeof key === 'string';
var index = lookupIndex(this, key);
if (index !== undefined) {
this.entries_[index + 1] = value;
} else {
index = this.entries_.length;
this.entries_[index] = key;
this.entries_[index + 1] = value;
if (objectMode) {
var hashObject = getOwnHashObject(key);
var hash = hashObject.hash;
this.objectIndex_[hash] = index;
} else if (stringMode) {
this.stringIndex_[key] = index;
} else {
this.primitiveIndex_[key] = index;
}
}
return this;
},
has: function(key) {
return lookupIndex(this, key) !== undefined;
},
delete: function(key) {
var objectMode = isObject(key);
var stringMode = typeof key === 'string';
var index;
var hash;
if (objectMode) {
var hashObject = getOwnHashObject(key);
if (hashObject) {
index = this.objectIndex_[hash = hashObject.hash];
delete this.objectIndex_[hash];
}
} else if (stringMode) {
index = this.stringIndex_[key];
delete this.stringIndex_[key];
} else {
index = this.primitiveIndex_[key];
delete this.primitiveIndex_[key];
}
if (index !== undefined) {
this.entries_[index] = deletedSentinel;
this.entries_[index + 1] = undefined;
this.deletedCount_++;
return true;
}
return false;
},
clear: function() {
initMap(this);
},
forEach: function(callbackFn) {
var thisArg = arguments[1];
for (var i = 0; i < this.entries_.length; i += 2) {
var key = this.entries_[i];
var value = this.entries_[i + 1];
if (key === deletedSentinel)
continue;
callbackFn.call(thisArg, value, key, this);
}
},
entries: $traceurRuntime.initGeneratorFunction(function $__8() {
var i,
key,
value;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
i = 0;
$ctx.state = 12;
break;
case 12:
$ctx.state = (i < this.entries_.length) ? 8 : -2;
break;
case 4:
i += 2;
$ctx.state = 12;
break;
case 8:
key = this.entries_[i];
value = this.entries_[i + 1];
$ctx.state = 9;
break;
case 9:
$ctx.state = (key === deletedSentinel) ? 4 : 6;
break;
case 6:
$ctx.state = 2;
return [key, value];
case 2:
$ctx.maybeThrow();
$ctx.state = 4;
break;
default:
return $ctx.end();
}
}, $__8, this);
}),
keys: $traceurRuntime.initGeneratorFunction(function $__9() {
var i,
key,
value;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
i = 0;
$ctx.state = 12;
break;
case 12:
$ctx.state = (i < this.entries_.length) ? 8 : -2;
break;
case 4:
i += 2;
$ctx.state = 12;
break;
case 8:
key = this.entries_[i];
value = this.entries_[i + 1];
$ctx.state = 9;
break;
case 9:
$ctx.state = (key === deletedSentinel) ? 4 : 6;
break;
case 6:
$ctx.state = 2;
return key;
case 2:
$ctx.maybeThrow();
$ctx.state = 4;
break;
default:
return $ctx.end();
}
}, $__9, this);
}),
values: $traceurRuntime.initGeneratorFunction(function $__10() {
var i,
key,
value;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
i = 0;
$ctx.state = 12;
break;
case 12:
$ctx.state = (i < this.entries_.length) ? 8 : -2;
break;
case 4:
i += 2;
$ctx.state = 12;
break;
case 8:
key = this.entries_[i];
value = this.entries_[i + 1];
$ctx.state = 9;
break;
case 9:
$ctx.state = (key === deletedSentinel) ? 4 : 6;
break;
case 6:
$ctx.state = 2;
return value;
case 2:
$ctx.maybeThrow();
$ctx.state = 4;
break;
default:
return $ctx.end();
}
}, $__10, this);
})
}, {});
Object.defineProperty(Map.prototype, Symbol.iterator, {
configurable: true,
writable: true,
value: Map.prototype.entries
});
function polyfillMap(global) {
var $__7 = global,
Object = $__7.Object,
Symbol = $__7.Symbol;
if (!global.Map)
global.Map = Map;
var mapPrototype = global.Map.prototype;
if (mapPrototype.entries) {
maybeAddIterator(mapPrototype, mapPrototype.entries, Symbol);
maybeAddIterator(Object.getPrototypeOf(new global.Map().entries()), function() {
return this;
}, Symbol);
}
}
registerPolyfill(polyfillMap);
return {
get Map() {
return Map;
},
get polyfillMap() {
return polyfillMap;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Map" + '');
System.register("[email protected]/src/runtime/polyfills/Set", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Set";
var $__11 = System.get("[email protected]/src/runtime/polyfills/utils"),
isObject = $__11.isObject,
maybeAddIterator = $__11.maybeAddIterator,
registerPolyfill = $__11.registerPolyfill;
var Map = System.get("[email protected]/src/runtime/polyfills/Map").Map;
var getOwnHashObject = $traceurRuntime.getOwnHashObject;
var $hasOwnProperty = Object.prototype.hasOwnProperty;
function initSet(set) {
set.map_ = new Map();
}
var Set = function Set() {
var iterable = arguments[0];
if (!isObject(this))
throw new TypeError('Set called on incompatible type');
if ($hasOwnProperty.call(this, 'map_')) {
throw new TypeError('Set can not be reentrantly initialised');
}
initSet(this);
if (iterable !== null && iterable !== undefined) {
for (var $__15 = iterable[Symbol.iterator](),
$__16; !($__16 = $__15.next()).done; ) {
var item = $__16.value;
{
this.add(item);
}
}
}
};
($traceurRuntime.createClass)(Set, {
get size() {
return this.map_.size;
},
has: function(key) {
return this.map_.has(key);
},
add: function(key) {
this.map_.set(key, key);
return this;
},
delete: function(key) {
return this.map_.delete(key);
},
clear: function() {
return this.map_.clear();
},
forEach: function(callbackFn) {
var thisArg = arguments[1];
var $__13 = this;
return this.map_.forEach((function(value, key) {
callbackFn.call(thisArg, key, key, $__13);
}));
},
values: $traceurRuntime.initGeneratorFunction(function $__18() {
var $__19,
$__20;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
$__19 = this.map_.keys()[Symbol.iterator]();
$ctx.sent = void 0;
$ctx.action = 'next';
$ctx.state = 12;
break;
case 12:
$__20 = $__19[$ctx.action]($ctx.sentIgnoreThrow);
$ctx.state = 9;
break;
case 9:
$ctx.state = ($__20.done) ? 3 : 2;
break;
case 3:
$ctx.sent = $__20.value;
$ctx.state = -2;
break;
case 2:
$ctx.state = 12;
return $__20.value;
default:
return $ctx.end();
}
}, $__18, this);
}),
entries: $traceurRuntime.initGeneratorFunction(function $__21() {
var $__22,
$__23;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
$__22 = this.map_.entries()[Symbol.iterator]();
$ctx.sent = void 0;
$ctx.action = 'next';
$ctx.state = 12;
break;
case 12:
$__23 = $__22[$ctx.action]($ctx.sentIgnoreThrow);
$ctx.state = 9;
break;
case 9:
$ctx.state = ($__23.done) ? 3 : 2;
break;
case 3:
$ctx.sent = $__23.value;
$ctx.state = -2;
break;
case 2:
$ctx.state = 12;
return $__23.value;
default:
return $ctx.end();
}
}, $__21, this);
})
}, {});
Object.defineProperty(Set.prototype, Symbol.iterator, {
configurable: true,
writable: true,
value: Set.prototype.values
});
Object.defineProperty(Set.prototype, 'keys', {
configurable: true,
writable: true,
value: Set.prototype.values
});
function polyfillSet(global) {
var $__17 = global,
Object = $__17.Object,
Symbol = $__17.Symbol;
if (!global.Set)
global.Set = Set;
var setPrototype = global.Set.prototype;
if (setPrototype.values) {
maybeAddIterator(setPrototype, setPrototype.values, Symbol);
maybeAddIterator(Object.getPrototypeOf(new global.Set().values()), function() {
return this;
}, Symbol);
}
}
registerPolyfill(polyfillSet);
return {
get Set() {
return Set;
},
get polyfillSet() {
return polyfillSet;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Set" + '');
System.register("[email protected]/node_modules/rsvp/lib/rsvp/asap", [], function() {
"use strict";
var __moduleName = "[email protected]/node_modules/rsvp/lib/rsvp/asap";
var len = 0;
function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
scheduleFlush();
}
}
var $__default = asap;
var browserGlobal = (typeof window !== 'undefined') ? window : {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
function useNextTick() {
return function() {
process.nextTick(flush);
};
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, {characterData: true});
return function() {
node.data = (iterations = ++iterations % 2);
};
}
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function() {
channel.port2.postMessage(0);
};
}
function useSetTimeout() {
return function() {
setTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
var scheduleFlush;
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else {
scheduleFlush = useSetTimeout();
}
return {get default() {
return $__default;
}};
});
System.register("[email protected]/src/runtime/polyfills/Promise", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Promise";
var async = System.get("[email protected]/node_modules/rsvp/lib/rsvp/asap").default;
var registerPolyfill = System.get("[email protected]/src/runtime/polyfills/utils").registerPolyfill;
var promiseRaw = {};
function isPromise(x) {
return x && typeof x === 'object' && x.status_ !== undefined;
}
function idResolveHandler(x) {
return x;
}
function idRejectHandler(x) {
throw x;
}
function chain(promise) {
var onResolve = arguments[1] !== (void 0) ? arguments[1] : idResolveHandler;
var onReject = arguments[2] !== (void 0) ? arguments[2] : idRejectHandler;
var deferred = getDeferred(promise.constructor);
switch (promise.status_) {
case undefined:
throw TypeError;
case 0:
promise.onResolve_.push(onResolve, deferred);
promise.onReject_.push(onReject, deferred);
break;
case +1:
promiseEnqueue(promise.value_, [onResolve, deferred]);
break;
case -1:
promiseEnqueue(promise.value_, [onReject, deferred]);
break;
}
return deferred.promise;
}
function getDeferred(C) {
if (this === $Promise) {
var promise = promiseInit(new $Promise(promiseRaw));
return {
promise: promise,
resolve: (function(x) {
promiseResolve(promise, x);
}),
reject: (function(r) {
promiseReject(promise, r);
})
};
} else {
var result = {};
result.promise = new C((function(resolve, reject) {
result.resolve = resolve;
result.reject = reject;
}));
return result;
}
}
function promiseSet(promise, status, value, onResolve, onReject) {
promise.status_ = status;
promise.value_ = value;
promise.onResolve_ = onResolve;
promise.onReject_ = onReject;
return promise;
}
function promiseInit(promise) {
return promiseSet(promise, 0, undefined, [], []);
}
var Promise = function Promise(resolver) {
if (resolver === promiseRaw)
return;
if (typeof resolver !== 'function')
throw new TypeError;
var promise = promiseInit(this);
try {
resolver((function(x) {
promiseResolve(promise, x);
}), (function(r) {
promiseReject(promise, r);
}));
} catch (e) {
promiseReject(promise, e);
}
};
($traceurRuntime.createClass)(Promise, {
catch: function(onReject) {
return this.then(undefined, onReject);
},
then: function(onResolve, onReject) {
if (typeof onResolve !== 'function')
onResolve = idResolveHandler;
if (typeof onReject !== 'function')
onReject = idRejectHandler;
var that = this;
var constructor = this.constructor;
return chain(this, function(x) {
x = promiseCoerce(constructor, x);
return x === that ? onReject(new TypeError) : isPromise(x) ? x.then(onResolve, onReject) : onResolve(x);
}, onReject);
}
}, {
resolve: function(x) {
if (this === $Promise) {
if (isPromise(x)) {
return x;
}
return promiseSet(new $Promise(promiseRaw), +1, x);
} else {
return new this(function(resolve, reject) {
resolve(x);
});
}
},
reject: function(r) {
if (this === $Promise) {
return promiseSet(new $Promise(promiseRaw), -1, r);
} else {
return new this((function(resolve, reject) {
reject(r);
}));
}
},
all: function(values) {
var deferred = getDeferred(this);
var resolutions = [];
try {
var count = values.length;
if (count === 0) {
deferred.resolve(resolutions);
} else {
for (var i = 0; i < values.length; i++) {
this.resolve(values[i]).then(function(i, x) {
resolutions[i] = x;
if (--count === 0)
deferred.resolve(resolutions);
}.bind(undefined, i), (function(r) {
deferred.reject(r);
}));
}
}
} catch (e) {
deferred.reject(e);
}
return deferred.promise;
},
race: function(values) {
var deferred = getDeferred(this);
try {
for (var i = 0; i < values.length; i++) {
this.resolve(values[i]).then((function(x) {
deferred.resolve(x);
}), (function(r) {
deferred.reject(r);
}));
}
} catch (e) {
deferred.reject(e);
}
return deferred.promise;
}
});
var $Promise = Promise;
var $PromiseReject = $Promise.reject;
function promiseResolve(promise, x) {
promiseDone(promise, +1, x, promise.onResolve_);
}
function promiseReject(promise, r) {
promiseDone(promise, -1, r, promise.onReject_);
}
function promiseDone(promise, status, value, reactions) {
if (promise.status_ !== 0)
return;
promiseEnqueue(value, reactions);
promiseSet(promise, status, value);
}
function promiseEnqueue(value, tasks) {
async((function() {
for (var i = 0; i < tasks.length; i += 2) {
promiseHandle(value, tasks[i], tasks[i + 1]);
}
}));
}
function promiseHandle(value, handler, deferred) {
try {
var result = handler(value);
if (result === deferred.promise)
throw new TypeError;
else if (isPromise(result))
chain(result, deferred.resolve, deferred.reject);
else
deferred.resolve(result);
} catch (e) {
try {
deferred.reject(e);
} catch (e) {}
}
}
var thenableSymbol = '@@thenable';
function isObject(x) {
return x && (typeof x === 'object' || typeof x === 'function');
}
function promiseCoerce(constructor, x) {
if (!isPromise(x) && isObject(x)) {
var then;
try {
then = x.then;
} catch (r) {
var promise = $PromiseReject.call(constructor, r);
x[thenableSymbol] = promise;
return promise;
}
if (typeof then === 'function') {
var p = x[thenableSymbol];
if (p) {
return p;
} else {
var deferred = getDeferred(constructor);
x[thenableSymbol] = deferred.promise;
try {
then.call(x, deferred.resolve, deferred.reject);
} catch (r) {
deferred.reject(r);
}
return deferred.promise;
}
}
}
return x;
}
function polyfillPromise(global) {
if (!global.Promise)
global.Promise = Promise;
}
registerPolyfill(polyfillPromise);
return {
get Promise() {
return Promise;
},
get polyfillPromise() {
return polyfillPromise;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Promise" + '');
System.register("[email protected]/src/runtime/polyfills/StringIterator", [], function() {
"use strict";
var $__29;
var __moduleName = "[email protected]/src/runtime/polyfills/StringIterator";
var $__27 = System.get("[email protected]/src/runtime/polyfills/utils"),
createIteratorResultObject = $__27.createIteratorResultObject,
isObject = $__27.isObject;
var $__30 = $traceurRuntime,
hasOwnProperty = $__30.hasOwnProperty,
toProperty = $__30.toProperty;
var iteratedString = Symbol('iteratedString');
var stringIteratorNextIndex = Symbol('stringIteratorNextIndex');
var StringIterator = function StringIterator() {};
($traceurRuntime.createClass)(StringIterator, ($__29 = {}, Object.defineProperty($__29, "next", {
value: function() {
var o = this;
if (!isObject(o) || !hasOwnProperty(o, iteratedString)) {
throw new TypeError('this must be a StringIterator object');
}
var s = o[toProperty(iteratedString)];
if (s === undefined) {
return createIteratorResultObject(undefined, true);
}
var position = o[toProperty(stringIteratorNextIndex)];
var len = s.length;
if (position >= len) {
o[toProperty(iteratedString)] = undefined;
return createIteratorResultObject(undefined, true);
}
var first = s.charCodeAt(position);
var resultString;
if (first < 0xD800 || first > 0xDBFF || position + 1 === len) {
resultString = String.fromCharCode(first);
} else {
var second = s.charCodeAt(position + 1);
if (second < 0xDC00 || second > 0xDFFF) {
resultString = String.fromCharCode(first);
} else {
resultString = String.fromCharCode(first) + String.fromCharCode(second);
}
}
o[toProperty(stringIteratorNextIndex)] = position + resultString.length;
return createIteratorResultObject(resultString, false);
},
configurable: true,
enumerable: true,
writable: true
}), Object.defineProperty($__29, Symbol.iterator, {
value: function() {
return this;
},
configurable: true,
enumerable: true,
writable: true
}), $__29), {});
function createStringIterator(string) {
var s = String(string);
var iterator = Object.create(StringIterator.prototype);
iterator[toProperty(iteratedString)] = s;
iterator[toProperty(stringIteratorNextIndex)] = 0;
return iterator;
}
return {get createStringIterator() {
return createStringIterator;
}};
});
System.register("[email protected]/src/runtime/polyfills/String", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/String";
var createStringIterator = System.get("[email protected]/src/runtime/polyfills/StringIterator").createStringIterator;
var $__32 = System.get("[email protected]/src/runtime/polyfills/utils"),
maybeAddFunctions = $__32.maybeAddFunctions,
maybeAddIterator = $__32.maybeAddIterator,
registerPolyfill = $__32.registerPolyfill;
var $toString = Object.prototype.toString;
var $indexOf = String.prototype.indexOf;
var $lastIndexOf = String.prototype.lastIndexOf;
function startsWith(search) {
var string = String(this);
if (this == null || $toString.call(search) == '[object RegExp]') {
throw TypeError();
}
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var position = arguments.length > 1 ? arguments[1] : undefined;
var pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
var start = Math.min(Math.max(pos, 0), stringLength);
return $indexOf.call(string, searchString, pos) == start;
}
function endsWith(search) {
var string = String(this);
if (this == null || $toString.call(search) == '[object RegExp]') {
throw TypeError();
}
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var pos = stringLength;
if (arguments.length > 1) {
var position = arguments[1];
if (position !== undefined) {
pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
}
}
var end = Math.min(Math.max(pos, 0), stringLength);
var start = end - searchLength;
if (start < 0) {
return false;
}
return $lastIndexOf.call(string, searchString, start) == start;
}
function contains(search) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var position = arguments.length > 1 ? arguments[1] : undefined;
var pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
var start = Math.min(Math.max(pos, 0), stringLength);
return $indexOf.call(string, searchString, pos) != -1;
}
function repeat(count) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var n = count ? Number(count) : 0;
if (isNaN(n)) {
n = 0;
}
if (n < 0 || n == Infinity) {
throw RangeError();
}
if (n == 0) {
return '';
}
var result = '';
while (n--) {
result += string;
}
return result;
}
function codePointAt(position) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var size = string.length;
var index = position ? Number(position) : 0;
if (isNaN(index)) {
index = 0;
}
if (index < 0 || index >= size) {
return undefined;
}
var first = string.charCodeAt(index);
var second;
if (first >= 0xD800 && first <= 0xDBFF && size > index + 1) {
second = string.charCodeAt(index + 1);
if (second >= 0xDC00 && second <= 0xDFFF) {
return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
}
}
return first;
}
function raw(callsite) {
var raw = callsite.raw;
var len = raw.length >>> 0;
if (len === 0)
return '';
var s = '';
var i = 0;
while (true) {
s += raw[i];
if (i + 1 === len)
return s;
s += arguments[++i];
}
}
function fromCodePoint() {
var codeUnits = [];
var floor = Math.floor;
var highSurrogate;
var lowSurrogate;
var index = -1;
var length = arguments.length;
if (!length) {
return '';
}
while (++index < length) {
var codePoint = Number(arguments[index]);
if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || floor(codePoint) != codePoint) {
throw RangeError('Invalid code point: ' + codePoint);
}
if (codePoint <= 0xFFFF) {
codeUnits.push(codePoint);
} else {
codePoint -= 0x10000;
highSurrogate = (codePoint >> 10) + 0xD800;
lowSurrogate = (codePoint % 0x400) + 0xDC00;
codeUnits.push(highSurrogate, lowSurrogate);
}
}
return String.fromCharCode.apply(null, codeUnits);
}
function stringPrototypeIterator() {
var o = $traceurRuntime.checkObjectCoercible(this);
var s = String(o);
return createStringIterator(s);
}
function polyfillString(global) {
var String = global.String;
maybeAddFunctions(String.prototype, ['codePointAt', codePointAt, 'contains', contains, 'endsWith', endsWith, 'startsWith', startsWith, 'repeat', repeat]);
maybeAddFunctions(String, ['fromCodePoint', fromCodePoint, 'raw', raw]);
maybeAddIterator(String.prototype, stringPrototypeIterator, Symbol);
}
registerPolyfill(polyfillString);
return {
get startsWith() {
return startsWith;
},
get endsWith() {
return endsWith;
},
get contains() {
return contains;
},
get repeat() {
return repeat;
},
get codePointAt() {
return codePointAt;
},
get raw() {
return raw;
},
get fromCodePoint() {
return fromCodePoint;
},
get stringPrototypeIterator() {
return stringPrototypeIterator;
},
get polyfillString() {
return polyfillString;
}
};
});
System.get("[email protected]/src/runtime/polyfills/String" + '');
System.register("[email protected]/src/runtime/polyfills/ArrayIterator", [], function() {
"use strict";
var $__36;
var __moduleName = "[email protected]/src/runtime/polyfills/ArrayIterator";
var $__34 = System.get("[email protected]/src/runtime/polyfills/utils"),
toObject = $__34.toObject,
toUint32 = $__34.toUint32,
createIteratorResultObject = $__34.createIteratorResultObject;
var ARRAY_ITERATOR_KIND_KEYS = 1;
var ARRAY_ITERATOR_KIND_VALUES = 2;
var ARRAY_ITERATOR_KIND_ENTRIES = 3;
var ArrayIterator = function ArrayIterator() {};
($traceurRuntime.createClass)(ArrayIterator, ($__36 = {}, Object.defineProperty($__36, "next", {
value: function() {
var iterator = toObject(this);
var array = iterator.iteratorObject_;
if (!array) {
throw new TypeError('Object is not an ArrayIterator');
}
var index = iterator.arrayIteratorNextIndex_;
var itemKind = iterator.arrayIterationKind_;
var length = toUint32(array.length);
if (index >= length) {
iterator.arrayIteratorNextIndex_ = Infinity;
return createIteratorResultObject(undefined, true);
}
iterator.arrayIteratorNextIndex_ = index + 1;
if (itemKind == ARRAY_ITERATOR_KIND_VALUES)
return createIteratorResultObject(array[index], false);
if (itemKind == ARRAY_ITERATOR_KIND_ENTRIES)
return createIteratorResultObject([index, array[index]], false);
return createIteratorResultObject(index, false);
},
configurable: true,
enumerable: true,
writable: true
}), Object.defineProperty($__36, Symbol.iterator, {
value: function() {
return this;
},
configurable: true,
enumerable: true,
writable: true
}), $__36), {});
function createArrayIterator(array, kind) {
var object = toObject(array);
var iterator = new ArrayIterator;
iterator.iteratorObject_ = object;
iterator.arrayIteratorNextIndex_ = 0;
iterator.arrayIterationKind_ = kind;
return iterator;
}
function entries() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_ENTRIES);
}
function keys() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_KEYS);
}
function values() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_VALUES);
}
return {
get entries() {
return entries;
},
get keys() {
return keys;
},
get values() {
return values;
}
};
});
System.register("[email protected]/src/runtime/polyfills/Array", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Array";
var $__37 = System.get("[email protected]/src/runtime/polyfills/ArrayIterator"),
entries = $__37.entries,
keys = $__37.keys,
values = $__37.values;
var $__38 = System.get("[email protected]/src/runtime/polyfills/utils"),
checkIterable = $__38.checkIterable,
isCallable = $__38.isCallable,
isConstructor = $__38.isConstructor,
maybeAddFunctions = $__38.maybeAddFunctions,
maybeAddIterator = $__38.maybeAddIterator,
registerPolyfill = $__38.registerPolyfill,
toInteger = $__38.toInteger,
toLength = $__38.toLength,
toObject = $__38.toObject;
function from(arrLike) {
var mapFn = arguments[1];
var thisArg = arguments[2];
var C = this;
var items = toObject(arrLike);
var mapping = mapFn !== undefined;
var k = 0;
var arr,
len;
if (mapping && !isCallable(mapFn)) {
throw TypeError();
}
if (checkIterable(items)) {
arr = isConstructor(C) ? new C() : [];
for (var $__39 = items[Symbol.iterator](),
$__40; !($__40 = $__39.next()).done; ) {
var item = $__40.value;
{
if (mapping) {
arr[k] = mapFn.call(thisArg, item, k);
} else {
arr[k] = item;
}
k++;
}
}
arr.length = k;
return arr;
}
len = toLength(items.length);
arr = isConstructor(C) ? new C(len) : new Array(len);
for (; k < len; k++) {
if (mapping) {
arr[k] = typeof thisArg === 'undefined' ? mapFn(items[k], k) : mapFn.call(thisArg, items[k], k);
} else {
arr[k] = items[k];
}
}
arr.length = len;
return arr;
}
function of() {
for (var items = [],
$__41 = 0; $__41 < arguments.length; $__41++)
items[$__41] = arguments[$__41];
var C = this;
var len = items.length;
var arr = isConstructor(C) ? new C(len) : new Array(len);
for (var k = 0; k < len; k++) {
arr[k] = items[k];
}
arr.length = len;
return arr;
}
function fill(value) {
var start = arguments[1] !== (void 0) ? arguments[1] : 0;
var end = arguments[2];
var object = toObject(this);
var len = toLength(object.length);
var fillStart = toInteger(start);
var fillEnd = end !== undefined ? toInteger(end) : len;
fillStart = fillStart < 0 ? Math.max(len + fillStart, 0) : Math.min(fillStart, len);
fillEnd = fillEnd < 0 ? Math.max(len + fillEnd, 0) : Math.min(fillEnd, len);
while (fillStart < fillEnd) {
object[fillStart] = value;
fillStart++;
}
return object;
}
function find(predicate) {
var thisArg = arguments[1];
return findHelper(this, predicate, thisArg);
}
function findIndex(predicate) {
var thisArg = arguments[1];
return findHelper(this, predicate, thisArg, true);
}
function findHelper(self, predicate) {
var thisArg = arguments[2];
var returnIndex = arguments[3] !== (void 0) ? arguments[3] : false;
var object = toObject(self);
var len = toLength(object.length);
if (!isCallable(predicate)) {
throw TypeError();
}
for (var i = 0; i < len; i++) {
if (i in object) {
var value = object[i];
if (predicate.call(thisArg, value, i, object)) {
return returnIndex ? i : value;
}
}
}
return returnIndex ? -1 : undefined;
}
function polyfillArray(global) {
var $__42 = global,
Array = $__42.Array,
Object = $__42.Object,
Symbol = $__42.Symbol;
maybeAddFunctions(Array.prototype, ['entries', entries, 'keys', keys, 'values', values, 'fill', fill, 'find', find, 'findIndex', findIndex]);
maybeAddFunctions(Array, ['from', from, 'of', of]);
maybeAddIterator(Array.prototype, values, Symbol);
maybeAddIterator(Object.getPrototypeOf([].values()), function() {
return this;
}, Symbol);
}
registerPolyfill(polyfillArray);
return {
get from() {
return from;
},
get of() {
return of;
},
get fill() {
return fill;
},
get find() {
return find;
},
get findIndex() {
return findIndex;
},
get polyfillArray() {
return polyfillArray;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Array" + '');
System.register("[email protected]/src/runtime/polyfills/Object", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Object";
var $__43 = System.get("[email protected]/src/runtime/polyfills/utils"),
maybeAddFunctions = $__43.maybeAddFunctions,
registerPolyfill = $__43.registerPolyfill;
var $__44 = $traceurRuntime,
defineProperty = $__44.defineProperty,
getOwnPropertyDescriptor = $__44.getOwnPropertyDescriptor,
getOwnPropertyNames = $__44.getOwnPropertyNames,
keys = $__44.keys,
privateNames = $__44.privateNames;
function is(left, right) {
if (left === right)
return left !== 0 || 1 / left === 1 / right;
return left !== left && right !== right;
}
function assign(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
var props = keys(source);
var p,
length = props.length;
for (p = 0; p < length; p++) {
var name = props[p];
if (privateNames[name])
continue;
target[name] = source[name];
}
}
return target;
}
function mixin(target, source) {
var props = getOwnPropertyNames(source);
var p,
descriptor,
length = props.length;
for (p = 0; p < length; p++) {
var name = props[p];
if (privateNames[name])
continue;
descriptor = getOwnPropertyDescriptor(source, props[p]);
defineProperty(target, props[p], descriptor);
}
return target;
}
function polyfillObject(global) {
var Object = global.Object;
maybeAddFunctions(Object, ['assign', assign, 'is', is, 'mixin', mixin]);
}
registerPolyfill(polyfillObject);
return {
get is() {
return is;
},
get assign() {
return assign;
},
get mixin() {
return mixin;
},
get polyfillObject() {
return polyfillObject;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Object" + '');
System.register("[email protected]/src/runtime/polyfills/Number", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Number";
var $__46 = System.get("[email protected]/src/runtime/polyfills/utils"),
isNumber = $__46.isNumber,
maybeAddConsts = $__46.maybeAddConsts,
maybeAddFunctions = $__46.maybeAddFunctions,
registerPolyfill = $__46.registerPolyfill,
toInteger = $__46.toInteger;
var $abs = Math.abs;
var $isFinite = isFinite;
var $isNaN = isNaN;
var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
var MIN_SAFE_INTEGER = -Math.pow(2, 53) + 1;
var EPSILON = Math.pow(2, -52);
function NumberIsFinite(number) {
return isNumber(number) && $isFinite(number);
}
;
function isInteger(number) {
return NumberIsFinite(number) && toInteger(number) === number;
}
function NumberIsNaN(number) {
return isNumber(number) && $isNaN(number);
}
;
function isSafeInteger(number) {
if (NumberIsFinite(number)) {
var integral = toInteger(number);
if (integral === number)
return $abs(integral) <= MAX_SAFE_INTEGER;
}
return false;
}
function polyfillNumber(global) {
var Number = global.Number;
maybeAddConsts(Number, ['MAX_SAFE_INTEGER', MAX_SAFE_INTEGER, 'MIN_SAFE_INTEGER', MIN_SAFE_INTEGER, 'EPSILON', EPSILON]);
maybeAddFunctions(Number, ['isFinite', NumberIsFinite, 'isInteger', isInteger, 'isNaN', NumberIsNaN, 'isSafeInteger', isSafeInteger]);
}
registerPolyfill(polyfillNumber);
return {
get MAX_SAFE_INTEGER() {
return MAX_SAFE_INTEGER;
},
get MIN_SAFE_INTEGER() {
return MIN_SAFE_INTEGER;
},
get EPSILON() {
return EPSILON;
},
get isFinite() {
return NumberIsFinite;
},
get isInteger() {
return isInteger;
},
get isNaN() {
return NumberIsNaN;
},
get isSafeInteger() {
return isSafeInteger;
},
get polyfillNumber() {
return polyfillNumber;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Number" + '');
System.register("[email protected]/src/runtime/polyfills/polyfills", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/polyfills";
var polyfillAll = System.get("[email protected]/src/runtime/polyfills/utils").polyfillAll;
polyfillAll(this);
var setupGlobals = $traceurRuntime.setupGlobals;
$traceurRuntime.setupGlobals = function(global) {
setupGlobals(global);
polyfillAll(global);
};
return {};
});
System.get("[email protected]/src/runtime/polyfills/polyfills" + '');
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":2}],4:[function(require,module,exports){
/*global define:false */
/**
* Copyright 2013 Craig Campbell
*
* 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.
*
* Mousetrap is a simple keyboard shortcut library for Javascript with
* no external dependencies
*
* @version 1.4.6
* @url craig.is/killing/mice
*/
(function(window, document, undefined) {
/**
* mapping of special keycodes to their corresponding keys
*
* everything in this dictionary cannot use keypress events
* so it has to be here to map to the correct keycodes for
* keyup/keydown events
*
* @type {Object}
*/
var _MAP = {
8: 'backspace',
9: 'tab',
13: 'enter',
16: 'shift',
17: 'ctrl',
18: 'alt',
20: 'capslock',
27: 'esc',
32: 'space',
33: 'pageup',
34: 'pagedown',
35: 'end',
36: 'home',
37: 'left',
38: 'up',
39: 'right',
40: 'down',
45: 'ins',
46: 'del',
91: 'meta',
93: 'meta',
224: 'meta'
},
/**
* mapping for special characters so they can support
*
* this dictionary is only used incase you want to bind a
* keyup or keydown event to one of these keys
*
* @type {Object}
*/
_KEYCODE_MAP = {
106: '*',
107: '+',
109: '-',
110: '.',
111 : '/',
186: ';',
187: '=',
188: ',',
189: '-',
190: '.',
191: '/',
192: '`',
219: '[',
220: '\\',
221: ']',
222: '\''
},
/**
* this is a mapping of keys that require shift on a US keypad
* back to the non shift equivelents
*
* this is so you can use keyup events with these keys
*
* note that this will only work reliably on US keyboards
*
* @type {Object}
*/
_SHIFT_MAP = {
'~': '`',
'!': '1',
'@': '2',
'#': '3',
'$': '4',
'%': '5',
'^': '6',
'&': '7',
'*': '8',
'(': '9',
')': '0',
'_': '-',
'+': '=',
':': ';',
'\"': '\'',
'<': ',',
'>': '.',
'?': '/',
'|': '\\'
},
/**
* this is a list of special strings you can use to map
* to modifier keys when you specify your keyboard shortcuts
*
* @type {Object}
*/
_SPECIAL_ALIASES = {
'option': 'alt',
'command': 'meta',
'return': 'enter',
'escape': 'esc',
'mod': /Mac|iPod|iPhone|iPad/.test(navigator.platform) ? 'meta' : 'ctrl'
},
/**
* variable to store the flipped version of _MAP from above
* needed to check if we should use keypress or not when no action
* is specified
*
* @type {Object|undefined}
*/
_REVERSE_MAP,
/**
* a list of all the callbacks setup via Mousetrap.bind()
*
* @type {Object}
*/
_callbacks = {},
/**
* direct map of string combinations to callbacks used for trigger()
*
* @type {Object}
*/
_directMap = {},
/**
* keeps track of what level each sequence is at since multiple
* sequences can start out with the same sequence
*
* @type {Object}
*/
_sequenceLevels = {},
/**
* variable to store the setTimeout call
*
* @type {null|number}
*/
_resetTimer,
/**
* temporary state where we will ignore the next keyup
*
* @type {boolean|string}
*/
_ignoreNextKeyup = false,
/**
* temporary state where we will ignore the next keypress
*
* @type {boolean}
*/
_ignoreNextKeypress = false,
/**
* are we currently inside of a sequence?
* type of action ("keyup" or "keydown" or "keypress") or false
*
* @type {boolean|string}
*/
_nextExpectedAction = false;
/**
* loop through the f keys, f1 to f19 and add them to the map
* programatically
*/
for (var i = 1; i < 20; ++i) {
_MAP[111 + i] = 'f' + i;
}
/**
* loop through to map numbers on the numeric keypad
*/
for (i = 0; i <= 9; ++i) {
_MAP[i + 96] = i;
}
/**
* cross browser add event method
*
* @param {Element|HTMLDocument} object
* @param {string} type
* @param {Function} callback
* @returns void
*/
function _addEvent(object, type, callback) {
if (object.addEventListener) {
object.addEventListener(type, callback, false);
return;
}
object.attachEvent('on' + type, callback);
}
/**
* takes the event and returns the key character
*
* @param {Event} e
* @return {string}
*/
function _characterFromEvent(e) {
// for keypress events we should return the character as is
if (e.type == 'keypress') {
var character = String.fromCharCode(e.which);
// if the shift key is not pressed then it is safe to assume
// that we want the character to be lowercase. this means if
// you accidentally have caps lock on then your key bindings
// will continue to work
//
// the only side effect that might not be desired is if you
// bind something like 'A' cause you want to trigger an
// event when capital A is pressed caps lock will no longer
// trigger the event. shift+a will though.
if (!e.shiftKey) {
character = character.toLowerCase();
}
return character;
}
// for non keypress events the special maps are needed
if (_MAP[e.which]) {
return _MAP[e.which];
}
if (_KEYCODE_MAP[e.which]) {
return _KEYCODE_MAP[e.which];
}
// if it is not in the special map
// with keydown and keyup events the character seems to always
// come in as an uppercase character whether you are pressing shift
// or not. we should make sure it is always lowercase for comparisons
return String.fromCharCode(e.which).toLowerCase();
}
/**
* checks if two arrays are equal
*
* @param {Array} modifiers1
* @param {Array} modifiers2
* @returns {boolean}
*/
function _modifiersMatch(modifiers1, modifiers2) {
return modifiers1.sort().join(',') === modifiers2.sort().join(',');
}
/**
* resets all sequence counters except for the ones passed in
*
* @param {Object} doNotReset
* @returns void
*/
function _resetSequences(doNotReset) {
doNotReset = doNotReset || {};
var activeSequences = false,
key;
for (key in _sequenceLevels) {
if (doNotReset[key]) {
activeSequences = true;
continue;
}
_sequenceLevels[key] = 0;
}
if (!activeSequences) {
_nextExpectedAction = false;
}
}
/**
* finds all callbacks that match based on the keycode, modifiers,
* and action
*
* @param {string} character
* @param {Array} modifiers
* @param {Event|Object} e
* @param {string=} sequenceName - name of the sequence we are looking for
* @param {string=} combination
* @param {number=} level
* @returns {Array}
*/
function _getMatches(character, modifiers, e, sequenceName, combination, level) {
var i,
callback,
matches = [],
action = e.type;
// if there are no events related to this keycode
if (!_callbacks[character]) {
return [];
}
// if a modifier key is coming up on its own we should allow it
if (action == 'keyup' && _isModifier(character)) {
modifiers = [character];
}
// loop through all callbacks for the key that was pressed
// and see if any of them match
for (i = 0; i < _callbacks[character].length; ++i) {
callback = _callbacks[character][i];
// if a sequence name is not specified, but this is a sequence at
// the wrong level then move onto the next match
if (!sequenceName && callback.seq && _sequenceLevels[callback.seq] != callback.level) {
continue;
}
// if the action we are looking for doesn't match the action we got
// then we should keep going
if (action != callback.action) {
continue;
}
// if this is a keypress event and the meta key and control key
// are not pressed that means that we need to only look at the
// character, otherwise check the modifiers as well
//
// chrome will not fire a keypress if meta or control is down
// safari will fire a keypress if meta or meta+shift is down
// firefox will fire a keypress if meta or control is down
if ((action == 'keypress' && !e.metaKey && !e.ctrlKey) || _modifiersMatch(modifiers, callback.modifiers)) {
// when you bind a combination or sequence a second time it
// should overwrite the first one. if a sequenceName or
// combination is specified in this call it does just that
//
// @todo make deleting its own method?
var deleteCombo = !sequenceName && callback.combo == combination;
var deleteSequence = sequenceName && callback.seq == sequenceName && callback.level == level;
if (deleteCombo || deleteSequence) {
_callbacks[character].splice(i, 1);
}
matches.push(callback);
}
}
return matches;
}
/**
* takes a key event and figures out what the modifiers are
*
* @param {Event} e
* @returns {Array}
*/
function _eventModifiers(e) {
var modifiers = [];
if (e.shiftKey) {
modifiers.push('shift');
}
if (e.altKey) {
modifiers.push('alt');
}
if (e.ctrlKey) {
modifiers.push('ctrl');
}
if (e.metaKey) {
modifiers.push('meta');
}
return modifiers;
}
/**
* prevents default for this event
*
* @param {Event} e
* @returns void
*/
function _preventDefault(e) {
if (e.preventDefault) {
e.preventDefault();
return;
}
e.returnValue = false;
}
/**
* stops propogation for this event
*
* @param {Event} e
* @returns void
*/
function _stopPropagation(e) {
if (e.stopPropagation) {
e.stopPropagation();
return;
}
e.cancelBubble = true;
}
/**
* actually calls the callback function
*
* if your callback function returns false this will use the jquery
* convention - prevent default and stop propogation on the event
*
* @param {Function} callback
* @param {Event} e
* @returns void
*/
function _fireCallback(callback, e, combo, sequence) {
// if this event should not happen stop here
if (Mousetrap.stopCallback(e, e.target || e.srcElement, combo, sequence)) {
return;
}
if (callback(e, combo) === false) {
_preventDefault(e);
_stopPropagation(e);
}
}
/**
* handles a character key event
*
* @param {string} character
* @param {Array} modifiers
* @param {Event} e
* @returns void
*/
function _handleKey(character, modifiers, e) {
var callbacks = _getMatches(character, modifiers, e),
i,
doNotReset = {},
maxLevel = 0,
processedSequenceCallback = false;
// Calculate the maxLevel for sequences so we can only execute the longest callback sequence
for (i = 0; i < callbacks.length; ++i) {
if (callbacks[i].seq) {
maxLevel = Math.max(maxLevel, callbacks[i].level);
}
}
// loop through matching callbacks for this key event
for (i = 0; i < callbacks.length; ++i) {
// fire for all sequence callbacks
// this is because if for example you have multiple sequences
// bound such as "g i" and "g t" they both need to fire the
// callback for matching g cause otherwise you can only ever
// match the first one
if (callbacks[i].seq) {
// only fire callbacks for the maxLevel to prevent
// subsequences from also firing
//
// for example 'a option b' should not cause 'option b' to fire
// even though 'option b' is part of the other sequence
//
// any sequences that do not match here will be discarded
// below by the _resetSequences call
if (callbacks[i].level != maxLevel) {
continue;
}
processedSequenceCallback = true;
// keep a list of which sequences were matches for later
doNotReset[callbacks[i].seq] = 1;
_fireCallback(callbacks[i].callback, e, callbacks[i].combo, callbacks[i].seq);
continue;
}
// if there were no sequence matches but we are still here
// that means this is a regular match so we should fire that
if (!processedSequenceCallback) {
_fireCallback(callbacks[i].callback, e, callbacks[i].combo);
}
}
// if the key you pressed matches the type of sequence without
// being a modifier (ie "keyup" or "keypress") then we should
// reset all sequences that were not matched by this event
//
// this is so, for example, if you have the sequence "h a t" and you
// type "h e a r t" it does not match. in this case the "e" will
// cause the sequence to reset
//
// modifier keys are ignored because you can have a sequence
// that contains modifiers such as "enter ctrl+space" and in most
// cases the modifier key will be pressed before the next key
//
// also if you have a sequence such as "ctrl+b a" then pressing the
// "b" key will trigger a "keypress" and a "keydown"
//
// the "keydown" is expected when there is a modifier, but the
// "keypress" ends up matching the _nextExpectedAction since it occurs
// after and that causes the sequence to reset
//
// we ignore keypresses in a sequence that directly follow a keydown
// for the same character
var ignoreThisKeypress = e.type == 'keypress' && _ignoreNextKeypress;
if (e.type == _nextExpectedAction && !_isModifier(character) && !ignoreThisKeypress) {
_resetSequences(doNotReset);
}
_ignoreNextKeypress = processedSequenceCallback && e.type == 'keydown';
}
/**
* handles a keydown event
*
* @param {Event} e
* @returns void
*/
function _handleKeyEvent(e) {
// normalize e.which for key events
// @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
if (typeof e.which !== 'number') {
e.which = e.keyCode;
}
var character = _characterFromEvent(e);
// no character found then stop
if (!character) {
return;
}
// need to use === for the character check because the character can be 0
if (e.type == 'keyup' && _ignoreNextKeyup === character) {
_ignoreNextKeyup = false;
return;
}
Mousetrap.handleKey(character, _eventModifiers(e), e);
}
/**
* determines if the keycode specified is a modifier key or not
*
* @param {string} key
* @returns {boolean}
*/
function _isModifier(key) {
return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
}
/**
* called to set a 1 second timeout on the specified sequence
*
* this is so after each key press in the sequence you have 1 second
* to press the next key before you have to start over
*
* @returns void
*/
function _resetSequenceTimer() {
clearTimeout(_resetTimer);
_resetTimer = setTimeout(_resetSequences, 1000);
}
/**
* reverses the map lookup so that we can look for specific keys
* to see what can and can't use keypress
*
* @return {Object}
*/
function _getReverseMap() {
if (!_REVERSE_MAP) {
_REVERSE_MAP = {};
for (var key in _MAP) {
// pull out the numeric keypad from here cause keypress should
// be able to detect the keys from the character
if (key > 95 && key < 112) {
continue;
}
if (_MAP.hasOwnProperty(key)) {
_REVERSE_MAP[_MAP[key]] = key;
}
}
}
return _REVERSE_MAP;
}
/**
* picks the best action based on the key combination
*
* @param {string} key - character for key
* @param {Array} modifiers
* @param {string=} action passed in
*/
function _pickBestAction(key, modifiers, action) {
// if no action was picked in we should try to pick the one
// that we think would work best for this key
if (!action) {
action = _getReverseMap()[key] ? 'keydown' : 'keypress';
}
// modifier keys don't work as expected with keypress,
// switch to keydown
if (action == 'keypress' && modifiers.length) {
action = 'keydown';
}
return action;
}
/**
* binds a key sequence to an event
*
* @param {string} combo - combo specified in bind call
* @param {Array} keys
* @param {Function} callback
* @param {string=} action
* @returns void
*/
function _bindSequence(combo, keys, callback, action) {
// start off by adding a sequence level record for this combination
// and setting the level to 0
_sequenceLevels[combo] = 0;
/**
* callback to increase the sequence level for this sequence and reset
* all other sequences that were active
*
* @param {string} nextAction
* @returns {Function}
*/
function _increaseSequence(nextAction) {
return function() {
_nextExpectedAction = nextAction;
++_sequenceLevels[combo];
_resetSequenceTimer();
};
}
/**
* wraps the specified callback inside of another function in order
* to reset all sequence counters as soon as this sequence is done
*
* @param {Event} e
* @returns void
*/
function _callbackAndReset(e) {
_fireCallback(callback, e, combo);
// we should ignore the next key up if the action is key down
// or keypress. this is so if you finish a sequence and
// release the key the final key will not trigger a keyup
if (action !== 'keyup') {
_ignoreNextKeyup = _characterFromEvent(e);
}
// weird race condition if a sequence ends with the key
// another sequence begins with
setTimeout(_resetSequences, 10);
}
// loop through keys one at a time and bind the appropriate callback
// function. for any key leading up to the final one it should
// increase the sequence. after the final, it should reset all sequences
//
// if an action is specified in the original bind call then that will
// be used throughout. otherwise we will pass the action that the
// next key in the sequence should match. this allows a sequence
// to mix and match keypress and keydown events depending on which
// ones are better suited to the key provided
for (var i = 0; i < keys.length; ++i) {
var isFinal = i + 1 === keys.length;
var wrappedCallback = isFinal ? _callbackAndReset : _increaseSequence(action || _getKeyInfo(keys[i + 1]).action);
_bindSingle(keys[i], wrappedCallback, action, combo, i);
}
}
/**
* Converts from a string key combination to an array
*
* @param {string} combination like "command+shift+l"
* @return {Array}
*/
function _keysFromString(combination) {
if (combination === '+') {
return ['+'];
}
return combination.split('+');
}
/**
* Gets info for a specific key combination
*
* @param {string} combination key combination ("command+s" or "a" or "*")
* @param {string=} action
* @returns {Object}
*/
function _getKeyInfo(combination, action) {
var keys,
key,
i,
modifiers = [];
// take the keys from this pattern and figure out what the actual
// pattern is all about
keys = _keysFromString(combination);
for (i = 0; i < keys.length; ++i) {
key = keys[i];
// normalize key names
if (_SPECIAL_ALIASES[key]) {
key = _SPECIAL_ALIASES[key];
}
// if this is not a keypress event then we should
// be smart about using shift keys
// this will only work for US keyboards however
if (action && action != 'keypress' && _SHIFT_MAP[key]) {
key = _SHIFT_MAP[key];
modifiers.push('shift');
}
// if this key is a modifier then add it to the list of modifiers
if (_isModifier(key)) {
modifiers.push(key);
}
}
// depending on what the key combination is
// we will try to pick the best event for it
action = _pickBestAction(key, modifiers, action);
return {
key: key,
modifiers: modifiers,
action: action
};
}
/**
* binds a single keyboard combination
*
* @param {string} combination
* @param {Function} callback
* @param {string=} action
* @param {string=} sequenceName - name of sequence if part of sequence
* @param {number=} level - what part of the sequence the command is
* @returns void
*/
function _bindSingle(combination, callback, action, sequenceName, level) {
// store a direct mapped reference for use with Mousetrap.trigger
_directMap[combination + ':' + action] = callback;
// make sure multiple spaces in a row become a single space
combination = combination.replace(/\s+/g, ' ');
var sequence = combination.split(' '),
info;
// if this pattern is a sequence of keys then run through this method
// to reprocess each pattern one key at a time
if (sequence.length > 1) {
_bindSequence(combination, sequence, callback, action);
return;
}
info = _getKeyInfo(combination, action);
// make sure to initialize array if this is the first time
// a callback is added for this key
_callbacks[info.key] = _callbacks[info.key] || [];
// remove an existing match if there is one
_getMatches(info.key, info.modifiers, {type: info.action}, sequenceName, combination, level);
// add this call back to the array
// if it is a sequence put it at the beginning
// if not put it at the end
//
// this is important because the way these are processed expects
// the sequence ones to come first
_callbacks[info.key][sequenceName ? 'unshift' : 'push']({
callback: callback,
modifiers: info.modifiers,
action: info.action,
seq: sequenceName,
level: level,
combo: combination
});
}
/**
* binds multiple combinations to the same callback
*
* @param {Array} combinations
* @param {Function} callback
* @param {string|undefined} action
* @returns void
*/
function _bindMultiple(combinations, callback, action) {
for (var i = 0; i < combinations.length; ++i) {
_bindSingle(combinations[i], callback, action);
}
}
// start!
_addEvent(document, 'keypress', _handleKeyEvent);
_addEvent(document, 'keydown', _handleKeyEvent);
_addEvent(document, 'keyup', _handleKeyEvent);
var Mousetrap = {
/**
* binds an event to mousetrap
*
* can be a single key, a combination of keys separated with +,
* an array of keys, or a sequence of keys separated by spaces
*
* be sure to list the modifier keys first to make sure that the
* correct key ends up getting bound (the last key in the pattern)
*
* @param {string|Array} keys
* @param {Function} callback
* @param {string=} action - 'keypress', 'keydown', or 'keyup'
* @returns void
*/
bind: function(keys, callback, action) {
keys = keys instanceof Array ? keys : [keys];
_bindMultiple(keys, callback, action);
return this;
},
/**
* unbinds an event to mousetrap
*
* the unbinding sets the callback function of the specified key combo
* to an empty function and deletes the corresponding key in the
* _directMap dict.
*
* TODO: actually remove this from the _callbacks dictionary instead
* of binding an empty function
*
* the keycombo+action has to be exactly the same as
* it was defined in the bind method
*
* @param {string|Array} keys
* @param {string} action
* @returns void
*/
unbind: function(keys, action) {
return Mousetrap.bind(keys, function() {}, action);
},
/**
* triggers an event that has already been bound
*
* @param {string} keys
* @param {string=} action
* @returns void
*/
trigger: function(keys, action) {
if (_directMap[keys + ':' + action]) {
_directMap[keys + ':' + action]({}, keys);
}
return this;
},
/**
* resets the library back to its initial state. this is useful
* if you want to clear out the current keyboard shortcuts and bind
* new ones - for example if you switch to another page
*
* @returns void
*/
reset: function() {
_callbacks = {};
_directMap = {};
return this;
},
/**
* should we stop this event before firing off callbacks
*
* @param {Event} e
* @param {Element} element
* @return {boolean}
*/
stopCallback: function(e, element) {
// if the element has the class "mousetrap" then no need to stop
if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
return false;
}
// stop for input, select, and textarea
return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA' || element.isContentEditable;
},
/**
* exposes _handleKey publicly so it can be overwritten by extensions
*/
handleKey: _handleKey
};
// expose mousetrap to the global object
window.Mousetrap = Mousetrap;
// expose mousetrap as an AMD module
if (typeof define === 'function' && define.amd) {
define(Mousetrap);
}
}) (window, document);
},{}],5:[function(require,module,exports){
(function( factory ) {
if (typeof define !== 'undefined' && define.amd) {
define([], factory);
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = factory();
} else {
window.scrollMonitor = factory();
}
})(function() {
var scrollTop = function() {
return window.pageYOffset ||
(document.documentElement && document.documentElement.scrollTop) ||
document.body.scrollTop;
};
var exports = {};
var watchers = [];
var VISIBILITYCHANGE = 'visibilityChange';
var ENTERVIEWPORT = 'enterViewport';
var FULLYENTERVIEWPORT = 'fullyEnterViewport';
var EXITVIEWPORT = 'exitViewport';
var PARTIALLYEXITVIEWPORT = 'partiallyExitViewport';
var LOCATIONCHANGE = 'locationChange';
var STATECHANGE = 'stateChange';
var eventTypes = [
VISIBILITYCHANGE,
ENTERVIEWPORT,
FULLYENTERVIEWPORT,
EXITVIEWPORT,
PARTIALLYEXITVIEWPORT,
LOCATIONCHANGE,
STATECHANGE
];
var defaultOffsets = {top: 0, bottom: 0};
var getViewportHeight = function() {
return window.innerHeight || document.documentElement.clientHeight;
};
var getDocumentHeight = function() {
// jQuery approach
// whichever is greatest
return Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight,
document.documentElement.clientHeight
);
};
exports.viewportTop = null;
exports.viewportBottom = null;
exports.documentHeight = null;
exports.viewportHeight = getViewportHeight();
var previousDocumentHeight;
var latestEvent;
var calculateViewportI;
function calculateViewport() {
exports.viewportTop = scrollTop();
exports.viewportBottom = exports.viewportTop + exports.viewportHeight;
exports.documentHeight = getDocumentHeight();
if (exports.documentHeight !== previousDocumentHeight) {
calculateViewportI = watchers.length;
while( calculateViewportI-- ) {
watchers[calculateViewportI].recalculateLocation();
}
previousDocumentHeight = exports.documentHeight;
}
}
function recalculateWatchLocationsAndTrigger() {
exports.viewportHeight = getViewportHeight();
calculateViewport();
updateAndTriggerWatchers();
}
var recalculateAndTriggerTimer;
function debouncedRecalcuateAndTrigger() {
clearTimeout(recalculateAndTriggerTimer);
recalculateAndTriggerTimer = setTimeout( recalculateWatchLocationsAndTrigger, 100 );
}
var updateAndTriggerWatchersI;
function updateAndTriggerWatchers() {
// update all watchers then trigger the events so one can rely on another being up to date.
updateAndTriggerWatchersI = watchers.length;
while( updateAndTriggerWatchersI-- ) {
watchers[updateAndTriggerWatchersI].update();
}
updateAndTriggerWatchersI = watchers.length;
while( updateAndTriggerWatchersI-- ) {
watchers[updateAndTriggerWatchersI].triggerCallbacks();
}
}
function ElementWatcher( watchItem, offsets ) {
var self = this;
this.watchItem = watchItem;
if (!offsets) {
this.offsets = defaultOffsets;
} else if (offsets === +offsets) {
this.offsets = {top: offsets, bottom: offsets};
} else {
this.offsets = {
top: offsets.top || defaultOffsets.top,
bottom: offsets.bottom || defaultOffsets.bottom
};
}
this.callbacks = {}; // {callback: function, isOne: true }
for (var i = 0, j = eventTypes.length; i < j; i++) {
self.callbacks[eventTypes[i]] = [];
}
this.locked = false;
var wasInViewport;
var wasFullyInViewport;
var wasAboveViewport;
var wasBelowViewport;
var listenerToTriggerListI;
var listener;
function triggerCallbackArray( listeners ) {
if (listeners.length === 0) {
return;
}
listenerToTriggerListI = listeners.length;
while( listenerToTriggerListI-- ) {
listener = listeners[listenerToTriggerListI];
listener.callback.call( self, latestEvent );
if (listener.isOne) {
listeners.splice(listenerToTriggerListI, 1);
}
}
}
this.triggerCallbacks = function triggerCallbacks() {
if (this.isInViewport && !wasInViewport) {
triggerCallbackArray( this.callbacks[ENTERVIEWPORT] );
}
if (this.isFullyInViewport && !wasFullyInViewport) {
triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] );
}
if (this.isAboveViewport !== wasAboveViewport &&
this.isBelowViewport !== wasBelowViewport) {
triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] );
// if you skip completely past this element
if (!wasFullyInViewport && !this.isFullyInViewport) {
triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] );
triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] );
}
if (!wasInViewport && !this.isInViewport) {
triggerCallbackArray( this.callbacks[ENTERVIEWPORT] );
triggerCallbackArray( this.callbacks[EXITVIEWPORT] );
}
}
if (!this.isFullyInViewport && wasFullyInViewport) {
triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] );
}
if (!this.isInViewport && wasInViewport) {
triggerCallbackArray( this.callbacks[EXITVIEWPORT] );
}
if (this.isInViewport !== wasInViewport) {
triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] );
}
switch( true ) {
case wasInViewport !== this.isInViewport:
case wasFullyInViewport !== this.isFullyInViewport:
case wasAboveViewport !== this.isAboveViewport:
case wasBelowViewport !== this.isBelowViewport:
triggerCallbackArray( this.callbacks[STATECHANGE] );
}
wasInViewport = this.isInViewport;
wasFullyInViewport = this.isFullyInViewport;
wasAboveViewport = this.isAboveViewport;
wasBelowViewport = this.isBelowViewport;
};
this.recalculateLocation = function() {
if (this.locked) {
return;
}
var previousTop = this.top;
var previousBottom = this.bottom;
if (this.watchItem.nodeName) { // a dom element
var cachedDisplay = this.watchItem.style.display;
if (cachedDisplay === 'none') {
this.watchItem.style.display = '';
}
var boundingRect = this.watchItem.getBoundingClientRect();
this.top = boundingRect.top + exports.viewportTop;
this.bottom = boundingRect.bottom + exports.viewportTop;
if (cachedDisplay === 'none') {
this.watchItem.style.display = cachedDisplay;
}
} else if (this.watchItem === +this.watchItem) { // number
if (this.watchItem > 0) {
this.top = this.bottom = this.watchItem;
} else {
this.top = this.bottom = exports.documentHeight - this.watchItem;
}
} else { // an object with a top and bottom property
this.top = this.watchItem.top;
this.bottom = this.watchItem.bottom;
}
this.top -= this.offsets.top;
this.bottom += this.offsets.bottom;
this.height = this.bottom - this.top;
if ( (previousTop !== undefined || previousBottom !== undefined) && (this.top !== previousTop || this.bottom !== previousBottom) ) {
triggerCallbackArray( this.callbacks[LOCATIONCHANGE] );
}
};
this.recalculateLocation();
this.update();
wasInViewport = this.isInViewport;
wasFullyInViewport = this.isFullyInViewport;
wasAboveViewport = this.isAboveViewport;
wasBelowViewport = this.isBelowViewport;
}
ElementWatcher.prototype = {
on: function( event, callback, isOne ) {
// trigger the event if it applies to the element right now.
switch( true ) {
case event === VISIBILITYCHANGE && !this.isInViewport && this.isAboveViewport:
case event === ENTERVIEWPORT && this.isInViewport:
case event === FULLYENTERVIEWPORT && this.isFullyInViewport:
case event === EXITVIEWPORT && this.isAboveViewport && !this.isInViewport:
case event === PARTIALLYEXITVIEWPORT && this.isAboveViewport:
callback.call( this, latestEvent );
if (isOne) {
return;
}
}
if (this.callbacks[event]) {
this.callbacks[event].push({callback: callback, isOne: isOne||false});
} else {
throw new Error('Tried to add a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', '));
}
},
off: function( event, callback ) {
if (this.callbacks[event]) {
for (var i = 0, item; item = this.callbacks[event][i]; i++) {
if (item.callback === callback) {
this.callbacks[event].splice(i, 1);
break;
}
}
} else {
throw new Error('Tried to remove a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', '));
}
},
one: function( event, callback ) {
this.on( event, callback, true);
},
recalculateSize: function() {
this.height = this.watchItem.offsetHeight + this.offsets.top + this.offsets.bottom;
this.bottom = this.top + this.height;
},
update: function() {
this.isAboveViewport = this.top < exports.viewportTop;
this.isBelowViewport = this.bottom > exports.viewportBottom;
this.isInViewport = (this.top <= exports.viewportBottom && this.bottom >= exports.viewportTop);
this.isFullyInViewport = (this.top >= exports.viewportTop && this.bottom <= exports.viewportBottom) ||
(this.isAboveViewport && this.isBelowViewport);
},
destroy: function() {
var index = watchers.indexOf(this),
self = this;
watchers.splice(index, 1);
for (var i = 0, j = eventTypes.length; i < j; i++) {
self.callbacks[eventTypes[i]].length = 0;
}
},
// prevent recalculating the element location
lock: function() {
this.locked = true;
},
unlock: function() {
this.locked = false;
}
};
var eventHandlerFactory = function (type) {
return function( callback, isOne ) {
this.on.call(this, type, callback, isOne);
};
};
for (var i = 0, j = eventTypes.length; i < j; i++) {
var type = eventTypes[i];
ElementWatcher.prototype[type] = eventHandlerFactory(type);
}
try {
calculateViewport();
} catch (e) {
try {
window.$(calculateViewport);
} catch (e) {
throw new Error('If you must put scrollMonitor in the <head>, you must use jQuery.');
}
}
function scrollMonitorListener(event) {
latestEvent = event;
calculateViewport();
updateAndTriggerWatchers();
}
if (window.addEventListener) {
window.addEventListener('scroll', scrollMonitorListener);
window.addEventListener('resize', debouncedRecalcuateAndTrigger);
} else {
// Old IE support
window.attachEvent('onscroll', scrollMonitorListener);
window.attachEvent('onresize', debouncedRecalcuateAndTrigger);
}
exports.beget = exports.create = function( element, offsets ) {
if (typeof element === 'string') {
element = document.querySelector(element);
} else if (element && element.length > 0) {
element = element[0];
}
var watcher = new ElementWatcher( element, offsets );
watchers.push(watcher);
watcher.update();
return watcher;
};
exports.update = function() {
latestEvent = null;
calculateViewport();
updateAndTriggerWatchers();
};
exports.recalculateLocations = function() {
exports.documentHeight = 0;
exports.update();
};
return exports;
});
},{}],6:[function(require,module,exports){
module.exports={
"name": "clappr",
"version": "0.0.79",
"description": "An extensible media player for the web",
"main": "dist/clappr.min.js",
"scripts": {
"test": "./node_modules/.bin/gulp release && ./node_modules/.bin/karma start --single-run --browsers Firefox"
},
"repository": {
"type": "git",
"url": "[email protected]:globocom/clappr.git"
},
"author": "Globo.com",
"license": "BSD",
"bugs": {
"url": "https://github.com/globocom/clappr/issues"
},
"browser": {
"zepto": "clappr-zepto"
},
"homepage": "https://github.com/globocom/clappr",
"devDependencies": {
"browserify": "^8.0.3",
"chai": "1.10.0",
"compass-mixins": "0.12.3",
"dotenv": "^0.4.0",
"es6ify": "~1.4.0",
"exorcist": "^0.1.6",
"express": "^4.6.1",
"express-alias": "0.4.0",
"glob": "^4.0.2",
"gulp": "^3.8.1",
"clappr-zepto": "0.0.3",
"gulp-compressor": "^0.1.0",
"gulp-jshint": "1.9.0",
"gulp-livereload": "^2.1.0",
"gulp-minify-css": "~0.3.5",
"gulp-rename": "^1.2.0",
"gulp-sass": "1.0.0",
"gulp-streamify": "0.0.5",
"gulp-uglify": "^1.0.1",
"gulp-util": "3.0.1",
"karma": "^0.12.17",
"karma-browserify": "^1.0.0",
"karma-chai": "^0.1.0",
"karma-chrome-launcher": "^0.1.4",
"karma-cli": "0.0.4",
"karma-firefox-launcher": "^0.1.3",
"karma-jasmine": "^0.2.2",
"karma-jquery": "^0.1.0",
"karma-mocha": "^0.1.4",
"karma-safari-launcher": "^0.1.1",
"karma-sinon": "^1.0.3",
"karma-sinon-chai": "^0.2.0",
"mkdirp": "^0.5.0",
"s3": "^4.1.1",
"scp": "0.0.3",
"sinon": "^1.10.2",
"traceur": "0.0.72",
"vinyl-source-stream": "^1.0.0",
"vinyl-transform": "0.0.1",
"watchify": "^2.0.0",
"yargs": "1.3.3"
},
"dependencies": {
"underscore": "1.7.0",
"mousetrap": "^1.4.6",
"scrollmonitor": "^1.0.8"
}
}
},{}],7:[function(require,module,exports){
"use strict";
var _ = require('underscore');
module.exports = {
'media_control': _.template('<div class="media-control-background" data-background></div><div class="media-control-layer" data-controls><% var renderBar=function(name) { %><div class="bar-container" data-<%= name %>><div class="bar-background" data-<%= name %>><div class="bar-fill-1" data-<%= name %>></div><div class="bar-fill-2" data-<%= name %>></div><div class="bar-hover" data-<%= name %>></div></div><div class="bar-scrubber" data-<%= name %>><div class="bar-scrubber-icon" data-<%= name %>></div></div></div><% }; %><% var renderSegmentedBar=function(name, segments) { segments=segments || 10; %><div class="bar-container" data-<%= name %>><% for (var i = 0; i < segments; i++) { %><div class="segmented-bar-element" data-<%= name %>></div><% } %></div><% }; %><% var renderDrawer=function(name, renderContent) { %><div class="drawer-container" data-<%= name %>><div class="drawer-icon-container" data-<%= name %>><div class="drawer-icon media-control-icon" data-<%= name %>></div><span class="drawer-text" data-<%= name %>></span></div><% renderContent(name); %></div><% }; %><% var renderIndicator=function(name) { %><div class="media-control-indicator" data-<%= name %>></div><% }; %><% var renderButton=function(name) { %><button class="media-control-button media-control-icon" data-<%= name %>></button><% }; %><% var templates={ bar: renderBar, segmentedBar: renderSegmentedBar, }; var render=function(settingsList) { _.each(settingsList, function(setting) { if(setting === "seekbar") { renderBar(setting); } else if (setting === "volume") { renderDrawer(setting, settings.volumeBarTemplate ? templates[settings.volumeBarTemplate] : function(name) { return renderSegmentedBar(name); }); } else if (setting === "duration" || setting=== "position") { renderIndicator(setting); } else { renderButton(setting); } }); }; %><% if (settings.default && settings.default.length) { %><div class="media-control-center-panel" data-media-control><% render(settings.default); %></div><% } %><% if (settings.left && settings.left.length) { %><div class="media-control-left-panel" data-media-control><% render(settings.left); %></div><% } %><% if (settings.right && settings.right.length) { %><div class="media-control-right-panel" data-media-control><% render(settings.right); %></div><% } %></div>'),
'seek_time': _.template('<span data-seek-time></span>'),
'flash': _.template('<param name="movie" value="<%= swfPath %>"><param name="quality" value="autohigh"><param name="swliveconnect" value="true"><param name="allowScriptAccess" value="always"><param name="bgcolor" value="#001122"><param name="allowFullScreen" value="false"><param name="wmode" value="transparent"><param name="tabindex" value="1"><param name=FlashVars value="playbackId=<%= playbackId %>" /><embed type="application/x-shockwave-flash" disabled tabindex="-1" enablecontextmenu="false" allowScriptAccess="always" quality="autohight" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"></embed>'),
'hls': _.template('<param name="movie" value="<%= swfPath %>?inline=1"><param name="quality" value="autohigh"><param name="swliveconnect" value="true"><param name="allowScriptAccess" value="always"><param name="bgcolor" value="#001122"><param name="allowFullScreen" value="false"><param name="wmode" value="transparent"><param name="tabindex" value="1"><param name=FlashVars value="playbackId=<%= playbackId %>" /><embed type="application/x-shockwave-flash" tabindex="1" enablecontextmenu="false" allowScriptAccess="always" quality="autohigh" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"></embed>'),
'html5_video': _.template('<source src="<%=src%>" type="<%=type%>">'),
'no_op': _.template('<p data-no-op-msg>Something went wrong :(</p>'),
'background_button': _.template('<div class="background-button-wrapper" data-background-button><button class="background-button-icon" data-background-button></button></div>'),
'dvr_controls': _.template('<div class="live-info">LIVE</div><button class="live-button">BACK TO LIVE</button>'),
'poster': _.template('<div class="play-wrapper" data-poster><span class="poster-icon play" data-poster/></div>'),
'spinner_three_bounce': _.template('<div data-bounce1></div><div data-bounce2></div><div data-bounce3></div>'),
'watermark': _.template('<div data-watermark data-watermark-<%=position %>><img src="<%= imageUrl %>"></div>'),
CSS: {
'container': '.container[data-container]{position:absolute;background-color:#000;height:100%;width:100%}.container[data-container].pointer-enabled{cursor:pointer}',
'core': '[data-player]{-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transform:translate3d(0,0,0);-moz-transform:translate3d(0,0,0);-ms-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0);position:relative;margin:0;padding:0;border:0;font-style:normal;font-weight:400;text-align:center;overflow:hidden;font-size:100%;font-family:"lucida grande",tahoma,verdana,arial,sans-serif;text-shadow:0 0 0;box-sizing:border-box}[data-player] a,[data-player] abbr,[data-player] acronym,[data-player] address,[data-player] applet,[data-player] article,[data-player] aside,[data-player] audio,[data-player] b,[data-player] big,[data-player] blockquote,[data-player] canvas,[data-player] caption,[data-player] center,[data-player] cite,[data-player] code,[data-player] dd,[data-player] del,[data-player] details,[data-player] dfn,[data-player] div,[data-player] dl,[data-player] dt,[data-player] em,[data-player] embed,[data-player] fieldset,[data-player] figcaption,[data-player] figure,[data-player] footer,[data-player] form,[data-player] h1,[data-player] h2,[data-player] h3,[data-player] h4,[data-player] h5,[data-player] h6,[data-player] header,[data-player] hgroup,[data-player] i,[data-player] iframe,[data-player] img,[data-player] ins,[data-player] kbd,[data-player] label,[data-player] legend,[data-player] li,[data-player] mark,[data-player] menu,[data-player] nav,[data-player] object,[data-player] ol,[data-player] output,[data-player] p,[data-player] pre,[data-player] q,[data-player] ruby,[data-player] s,[data-player] samp,[data-player] section,[data-player] small,[data-player] span,[data-player] strike,[data-player] strong,[data-player] sub,[data-player] summary,[data-player] sup,[data-player] table,[data-player] tbody,[data-player] td,[data-player] tfoot,[data-player] th,[data-player] thead,[data-player] time,[data-player] tr,[data-player] tt,[data-player] u,[data-player] ul,[data-player] var,[data-player] video{margin:0;padding:0;border:0;font:inherit;font-size:100%;vertical-align:baseline}[data-player] table{border-collapse:collapse;border-spacing:0}[data-player] caption,[data-player] td,[data-player] th{text-align:left;font-weight:400;vertical-align:middle}[data-player] blockquote,[data-player] q{quotes:none}[data-player] blockquote:after,[data-player] blockquote:before,[data-player] q:after,[data-player] q:before{content:"";content:none}[data-player] a img{border:none}[data-player] *{max-width:initial;box-sizing:inherit;float:initial}[data-player].fullscreen{width:100%;height:100%}[data-player].nocursor{cursor:none}[data-player] .clappr-style{display:none!important}@media screen{[data-player]{opacity:.99}}',
'media_control': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.media-control-notransition{-webkit-transition:none!important;-webkit-transition-delay:0s;-moz-transition:none!important;-o-transition:none!important;transition:none!important}.media-control[data-media-control]{position:absolute;width:100%;height:100%;z-index:9999;pointer-events:none}.media-control[data-media-control].dragging{pointer-events:auto;cursor:-webkit-grabbing!important;cursor:grabbing!important}.media-control[data-media-control].dragging *{cursor:-webkit-grabbing!important;cursor:grabbing!important}.media-control[data-media-control] .media-control-background[data-background]{position:absolute;height:40%;width:100%;bottom:0;background-image:-owg(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-webkit(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-moz(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-o(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9));-webkit-transition:opacity .6s;-webkit-transition-delay:ease-out;-moz-transition:opacity .6s ease-out;-o-transition:opacity .6s ease-out;transition:opacity .6s ease-out}.media-control[data-media-control] .media-control-icon{font-family:Player;font-weight:400;font-style:normal;font-size:26px;line-height:32px;letter-spacing:0;speak:none;color:#fff;opacity:.5;vertical-align:middle;text-align:left;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transition:all .1s;-webkit-transition-delay:ease;-moz-transition:all .1s ease;-o-transition:all .1s ease;transition:all .1s ease}.media-control[data-media-control] .media-control-icon:hover{color:#fff;opacity:.75;text-shadow:rgba(255,255,255,.8) 0 0 5px}.media-control[data-media-control].media-control-hide .media-control-background[data-background]{opacity:0}.media-control[data-media-control].media-control-hide .media-control-layer[data-controls]{bottom:-50px}.media-control[data-media-control].media-control-hide .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls]{position:absolute;bottom:7px;width:100%;height:32px;vertical-align:middle;pointer-events:auto;-webkit-transition:bottom .4s;-webkit-transition-delay:ease-out;-moz-transition:bottom .4s ease-out;-o-transition:bottom .4s ease-out;transition:bottom .4s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-left-panel[data-media-control]{position:absolute;top:0;left:4px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-center-panel[data-media-control]{height:100%;text-align:center;line-height:32px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-right-panel[data-media-control]{position:absolute;top:0;right:4px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button{background-color:transparent;border:0;margin:0 6px;padding:0;cursor:pointer;display:inline-block}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button:focus{outline:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]{float:right;background-color:transparent;border:0;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]:before{content:"\\e006"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen].shrink:before{content:"\\e007"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]{cursor:default;float:right;background-color:transparent;border:0;height:100%;opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]:before{content:"\\e008"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled:hover{opacity:1;text-shadow:none}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].playing:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].paused:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].playing:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].stopped:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration],.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position]{display:inline-block;font-size:10px;color:#fff;cursor:default;line-height:32px;position:relative}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position]{margin-left:6px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]{color:rgba(255,255,255,.5);margin-right:6px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]:before{content:"|";margin:0 3px}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]{position:absolute;top:-20px;left:0;display:inline-block;vertical-align:middle;width:100%;height:25px;cursor:pointer}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar]{width:100%;height:1px;position:relative;top:12px;background-color:#666}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-1[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#c2c2c2;-webkit-transition:all .1s;-webkit-transition-delay:ease-out;-moz-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#005aff;-webkit-transition:all .1s;-webkit-transition-delay:ease-out;-moz-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-hover[data-seekbar]{opacity:0;position:absolute;top:-3px;width:5px;height:7px;background-color:rgba(255,255,255,.5);-webkit-transition:opacity .1s;-webkit-transition-delay:ease;-moz-transition:opacity .1s ease;-o-transition:opacity .1s ease;transition:opacity .1s ease}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]:hover .bar-background[data-seekbar] .bar-hover[data-seekbar]{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled{cursor:default}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled:hover .bar-background[data-seekbar] .bar-hover[data-seekbar]{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{position:absolute;top:2px;left:0;width:20px;height:20px;opacity:1;-webkit-transition:all .1s;-webkit-transition-delay:ease-out;-moz-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar] .bar-scrubber-icon[data-seekbar]{position:absolute;left:6px;top:6px;width:8px;height:8px;border-radius:10px;box-shadow:0 0 0 6px rgba(255,255,255,.2);background-color:#fff}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume]{float:right;display:inline-block;height:32px;cursor:pointer;margin:0 6px;box-sizing:border-box}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume]{float:left;bottom:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]{background-color:transparent;border:0;box-sizing:content-box;width:16px;height:32px;margin-right:6px;opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:hover{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:before{content:"\\e004"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted{opacity:.5}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted:hover{opacity:.7}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted:before{content:"\\e005"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume]{float:left;position:relative;top:6px;width:42px;height:18px;padding:3px 0;overflow:hidden;-webkit-transition:width .2s;-webkit-transition-delay:ease-out;-moz-transition:width .2s ease-out;-o-transition:width .2s ease-out;transition:width .2s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]{float:left;width:4px;padding-left:2px;height:12px;opacity:.5;-webkit-box-shadow:inset 2px 0 0 #fff;-moz-box-shadow:inset 2px 0 0 #fff;-ms-box-shadow:inset 2px 0 0 #fff;-o-box-shadow:inset 2px 0 0 #fff;box-shadow:inset 2px 0 0 #fff;-webkit-transition:-webkit-transform .2s;-webkit-transition-delay:ease-out;-moz-transition:-moz-transform .2s ease-out;-o-transition:-o-transform .2s ease-out;transition:transform .2s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume].fill{-webkit-box-shadow:inset 2px 0 0 #fff;-moz-box-shadow:inset 2px 0 0 #fff;-ms-box-shadow:inset 2px 0 0 #fff;-o-box-shadow:inset 2px 0 0 #fff;box-shadow:inset 2px 0 0 #fff;opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]:nth-of-type(1){padding-left:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]:hover{-webkit-transform:scaleY(1.5);-moz-transform:scaleY(1.5);-ms-transform:scaleY(1.5);-o-transform:scaleY(1.5);transform:scaleY(1.5)}.media-control[data-media-control].w320 .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume].volume-bar-hide{height:12px;top:9px;padding:0;width:0}',
'seek_time': '.seek-time[data-seek-time]{position:absolute;width:auto;height:20px;line-height:20px;bottom:55px;background-color:rgba(2,2,2,.5);z-index:9999;-webkit-transition:opacity .1s;-webkit-transition-delay:ease;-moz-transition:opacity .1s ease;-o-transition:opacity .1s ease;transition:opacity .1s ease}.seek-time[data-seek-time].hidden[data-seek-time]{opacity:0}.seek-time[data-seek-time] span[data-seek-time]{position:relative;color:#fff;font-size:10px;padding-left:7px;padding-right:7px}',
'flash': '[data-flash]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none}',
'hls': '[data-hls]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none;top:0}',
'html5_video': '[data-html5-video]{position:absolute;height:100%;width:100%;display:block}',
'html_img': '[data-html-img]{max-width:100%;max-height:100%}',
'no_op': '[data-no-op]{z-index:1000;position:absolute;background-color:#222;height:100%;width:100%}[data-no-op] p[data-no-op-msg]{position:relative;font-size:25px;top:50%;color:#fff}',
'background_button': '.background-button[data-background-button]{font-family:Player;position:absolute;height:100%;width:100%;background-color:rgba(0,0,0,.2);pointer-events:none;-webkit-transition:all .4s;-webkit-transition-delay:ease-out;-moz-transition:all .4s ease-out;-o-transition:all .4s ease-out;transition:all .4s ease-out}.background-button[data-background-button].hide{background-color:transparent}.background-button[data-background-button].hide .background-button-wrapper[data-background-button]{opacity:0}.background-button[data-background-button] .background-button-wrapper[data-background-button]{position:absolute;overflow:hidden;width:100%;height:25%;line-height:100%;font-size:25%;top:50%;text-align:center}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button]{cursor:pointer;pointer-events:auto;font-family:Player;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;color:#fff;opacity:.75;border:0;outline:0;background-color:transparent;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transition:all .1s;-webkit-transition-delay:ease;-moz-transition:all .1s ease;-o-transition:all .1s ease;transition:all .1s ease}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button]:hover{opacity:1;text-shadow:rgba(255,255,255,.8) 0 0 15px}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playing:before{content:"\\e002"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].notplaying:before{content:"\\e001"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playstop.playing:before{content:"\\e003"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playstop.notplaying:before{content:"\\e001"}.media-control.media-control-hide[data-media-control] .background-button[data-background-button]{opacity:0}',
'dvr_controls': '@import url(http://fonts.googleapis.com/css?family=Roboto);.dvr-controls[data-dvr-controls]{display:inline-block;float:left;color:#fff;line-height:32px;font-size:10px;font-weight:700;margin-left:6px}.dvr-controls[data-dvr-controls] .live-info{cursor:default;font-family:Roboto,"Open Sans",Arial,sans-serif}.dvr-controls[data-dvr-controls] .live-info:before{content:"";display:inline-block;position:relative;width:7px;height:7px;border-radius:3.5px;margin-right:3.5px;background-color:#ff0101}.dvr-controls[data-dvr-controls] .live-info.disabled{opacity:.3}.dvr-controls[data-dvr-controls] .live-info.disabled:before{background-color:#fff}.dvr-controls[data-dvr-controls] .live-button{cursor:pointer;outline:0;display:none;border:0;color:#fff;background-color:transparent;height:32px;padding:0;opacity:.7;font-family:Roboto,"Open Sans",Arial,sans-serif;-webkit-transition:all .1s;-webkit-transition-delay:ease;-moz-transition:all .1s ease;-o-transition:all .1s ease;transition:all .1s ease}.dvr-controls[data-dvr-controls] .live-button:before{content:"";display:inline-block;position:relative;width:7px;height:7px;border-radius:3.5px;margin-right:3.5px;background-color:#fff}.dvr-controls[data-dvr-controls] .live-button:hover{opacity:1;text-shadow:rgba(255,255,255,.75) 0 0 5px}.dvr .dvr-controls[data-dvr-controls] .live-info{display:none}.dvr .dvr-controls[data-dvr-controls] .live-button{display:block}.dvr.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{background-color:#005aff}.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{background-color:#ff0101}.seek-time[data-seek-time] span[data-duration]{position:relative;color:rgba(255,255,255,.5);font-size:10px;padding-right:7px}.seek-time[data-seek-time] span[data-duration]:before{content:"|";margin-right:7px}',
'poster': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.player-poster[data-poster]{cursor:pointer;position:absolute;height:100%;width:100%;z-index:998;top:0}.player-poster[data-poster] .poster-background[data-poster]{width:100%;height:100%}.player-poster[data-poster] .play-wrapper[data-poster]{position:absolute;width:100%;height:25%;line-height:100%;font-size:25%;top:50%;text-align:center}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]{font-family:Player;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;color:#fff;opacity:.75;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transition:opacity text-shadow;-webkit-transition-delay:.1s;-moz-transition:opacity text-shadow .1s;-o-transition:opacity text-shadow .1s;transition:opacity text-shadow .1s ease}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster].play[data-poster]:before{content:"\\e001"}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]:hover{opacity:1;text-shadow:rgba(255,255,255,.8) 0 0 15px}',
'spinner_three_bounce': '.spinner-three-bounce[data-spinner]{position:absolute;margin:0 auto;width:70px;text-align:center;z-index:999;top:47%;left:0;right:0}.spinner-three-bounce[data-spinner]>div{width:18px;height:18px;background-color:#FFF;border-radius:100%;display:inline-block;-webkit-animation:bouncedelay 1.4s infinite ease-in-out;-moz-animation:bouncedelay 1.4s infinite ease-in-out;-ms-animation:bouncedelay 1.4s infinite ease-in-out;-o-animation:bouncedelay 1.4s infinite ease-in-out;animation:bouncedelay 1.4s infinite ease-in-out;-webkit-animation-fill-mode:both;-moz-animation-fill-mode:both;-ms-animation-fill-mode:both;-o-animation-fill-mode:both;animation-fill-mode:both}.spinner-three-bounce[data-spinner] [data-bounce1],.spinner-three-bounce[data-spinner] [data-bounce2]{-webkit-animation-delay:-.32s;-moz-animation-delay:-.32s;-ms-animation-delay:-.32s;-o-animation-delay:-.32s;animation-delay:-.32s}@-moz-keyframes bouncedelay{0%,100%,80%{-moz-transform:scale(0);transform:scale(0)}40%{-moz-transform:scale(1);transform:scale(1)}}@-webkit-keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0);transform:scale(0)}40%{-webkit-transform:scale(1);transform:scale(1)}}@-o-keyframes bouncedelay{0%,100%,80%{-o-transform:scale(0);transform:scale(0)}40%{-o-transform:scale(1);transform:scale(1)}}@-ms-keyframes bouncedelay{0%,100%,80%{-ms-transform:scale(0);transform:scale(0)}40%{-ms-transform:scale(1);transform:scale(1)}}@keyframes bouncedelay{0%,100%,80%{transform:scale(0)}40%{transform:scale(1)}}',
'watermark': '[data-watermark]{position:absolute;margin:100px auto 0;width:70px;text-align:center;z-index:10}[data-watermark-bottom-left]{bottom:10px;left:10px}[data-watermark-bottom-right]{bottom:10px;right:42px}[data-watermark-top-left]{top:-95px;left:10px}[data-watermark-top-right]{top:-95px;right:37px}'
}
};
},{"underscore":"underscore"}],8:[function(require,module,exports){
"use strict";
var $ = require('zepto');
var _ = require('underscore');
var JST = require('./jst');
var Styler = {getStyleFor: function(name, options) {
options = options || {};
return $('<style class="clappr-style"></style>').html(_.template(JST.CSS[name])(options))[0];
}};
module.exports = Styler;
},{"./jst":7,"underscore":"underscore","zepto":"zepto"}],9:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var Browser = require('browser');
var extend = function(protoProps, staticProps) {
var parent = this;
var child;
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function() {
return parent.apply(this, arguments);
};
}
_.extend(child, parent, staticProps);
var Surrogate = function() {
this.constructor = child;
};
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate();
if (protoProps)
_.extend(child.prototype, protoProps);
child.__super__ = parent.prototype;
child.super = function(name) {
return parent.prototype[name];
};
child.prototype.getClass = function() {
return child;
};
return child;
};
var formatTime = function(time) {
time = time * 1000;
time = parseInt(time / 1000);
var seconds = time % 60;
time = parseInt(time / 60);
var minutes = time % 60;
time = parseInt(time / 60);
var hours = time % 24;
var out = "";
if (hours && hours > 0)
out += ("0" + hours).slice(-2) + ":";
out += ("0" + minutes).slice(-2) + ":";
out += ("0" + seconds).slice(-2);
return out.trim();
};
var Fullscreen = {
isFullscreen: function() {
return document.webkitIsFullScreen || document.mozFullScreen || !!document.msFullscreenElement || window.iframeFullScreen;
},
requestFullscreen: function(el) {
if (el.requestFullscreen) {
el.requestFullscreen();
} else if (el.webkitRequestFullscreen) {
el.webkitRequestFullscreen();
} else if (el.mozRequestFullScreen) {
el.mozRequestFullScreen();
} else if (el.msRequestFullscreen) {
el.msRequestFullscreen();
}
},
cancelFullscreen: function() {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
}
};
var Config = function Config() {};
($traceurRuntime.createClass)(Config, {}, {
_defaultConfig: function() {
return {volume: {
value: 100,
parse: parseInt
}};
},
_defaultValueFor: function(key) {
try {
return this._defaultConfig()[key]['parse'](this._defaultConfig()[key]['value']);
} catch (e) {
return undefined;
}
},
_create_keyspace: function(key) {
return 'clappr.' + document.domain + '.' + key;
},
restore: function(key) {
if (Browser.hasLocalstorage && localStorage[this._create_keyspace(key)]) {
return this._defaultConfig()[key]['parse'](localStorage[this._create_keyspace(key)]);
}
return this._defaultValueFor(key);
},
persist: function(key, value) {
if (Browser.hasLocalstorage) {
try {
localStorage[this._create_keyspace(key)] = value;
return true;
} catch (e) {
return false;
}
}
}
});
var seekStringToSeconds = function(url) {
var elements = _.rest(_.compact(url.match(/t=([0-9]*)h?([0-9]*)m?([0-9]*)s/))).reverse();
var seconds = 0;
var factor = 1;
_.each(elements, function(el) {
seconds += (parseInt(el) * factor);
factor = factor * 60;
}, this);
return seconds;
};
module.exports = {
extend: extend,
formatTime: formatTime,
Fullscreen: Fullscreen,
Config: Config,
seekStringToSeconds: seekStringToSeconds
};
},{"browser":"browser","underscore":"underscore"}],10:[function(require,module,exports){
"use strict";
var UIObject = require('ui_object');
var Styler = require('../../base/styler');
var _ = require('underscore');
var Events = require('events');
var Container = function Container(options) {
$traceurRuntime.superCall(this, $Container.prototype, "constructor", [options]);
this.playback = options.playback;
this.settings = this.playback.settings;
this.isReady = false;
this.mediaControlDisabled = false;
this.plugins = [this.playback];
this.bindEvents();
};
var $Container = Container;
($traceurRuntime.createClass)(Container, {
get name() {
return 'Container';
},
get attributes() {
return {
class: 'container',
'data-container': ''
};
},
get events() {
return {'click': 'clicked'};
},
bindEvents: function() {
this.listenTo(this.playback, Events.PLAYBACK_PROGRESS, this.progress);
this.listenTo(this.playback, Events.PLAYBACK_TIMEUPDATE, this.timeUpdated);
this.listenTo(this.playback, Events.PLAYBACK_READY, this.ready);
this.listenTo(this.playback, Events.PLAYBACK_BUFFERING, this.buffering);
this.listenTo(this.playback, Events.PLAYBACK_BUFFERFULL, this.bufferfull);
this.listenTo(this.playback, Events.PLAYBACK_SETTINGSUPDATE, this.settingsUpdate);
this.listenTo(this.playback, Events.PLAYBACK_LOADEDMETADATA, this.loadedMetadata);
this.listenTo(this.playback, Events.PLAYBACK_HIGHDEFINITIONUPDATE, this.highDefinitionUpdate);
this.listenTo(this.playback, Events.PLAYBACK_BITRATE, this.updateBitrate);
this.listenTo(this.playback, Events.PLAYBACK_PLAYBACKSTATE, this.playbackStateChanged);
this.listenTo(this.playback, Events.PLAYBACK_DVR, this.playbackDvrStateChanged);
this.listenTo(this.playback, Events.PLAYBACK_MEDIACONTROL_DISABLE, this.disableMediaControl);
this.listenTo(this.playback, Events.PLAYBACK_MEDIACONTROL_ENABLE, this.enableMediaControl);
this.listenTo(this.playback, Events.PLAYBACK_ENDED, this.ended);
this.listenTo(this.playback, Events.PLAYBACK_PLAY, this.playing);
this.listenTo(this.playback, Events.PLAYBACK_ERROR, this.error);
},
with: function(klass) {
_.extend(this, klass);
return this;
},
playbackStateChanged: function() {
this.trigger(Events.CONTAINER_PLAYBACKSTATE);
},
playbackDvrStateChanged: function(dvrInUse) {
this.settings = this.playback.settings;
this.dvrInUse = dvrInUse;
this.trigger(Events.CONTAINER_PLAYBACKDVRSTATECHANGED, dvrInUse);
},
updateBitrate: function(newBitrate) {
this.trigger(Events.CONTAINER_BITRATE, newBitrate);
},
statsReport: function(metrics) {
this.trigger(Events.CONTAINER_STATS_REPORT, metrics);
},
getPlaybackType: function() {
return this.playback.getPlaybackType();
},
isDvrEnabled: function() {
return !!this.playback.dvrEnabled;
},
isDvrInUse: function() {
return !!this.dvrInUse;
},
destroy: function() {
this.trigger(Events.CONTAINER_DESTROYED, this, this.name);
this.playback.destroy();
_(this.plugins).each((function(plugin) {
return plugin.destroy();
}));
this.$el.remove();
},
setStyle: function(style) {
this.$el.css(style);
},
animate: function(style, duration) {
return this.$el.animate(style, duration).promise();
},
ready: function() {
this.isReady = true;
this.trigger(Events.CONTAINER_READY, this.name);
},
isPlaying: function() {
return this.playback.isPlaying();
},
getDuration: function() {
return this.playback.getDuration();
},
error: function(errorObj) {
this.$el.append(errorObj.render().el);
this.trigger(Events.CONTAINER_ERROR, {
error: errorObj,
container: this
}, this.name);
},
loadedMetadata: function(duration) {
this.trigger(Events.CONTAINER_LOADEDMETADATA, duration);
},
timeUpdated: function(position, duration) {
this.trigger(Events.CONTAINER_TIMEUPDATE, position, duration, this.name);
},
progress: function(startPosition, endPosition, duration) {
this.trigger(Events.CONTAINER_PROGRESS, startPosition, endPosition, duration, this.name);
},
playing: function() {
this.trigger(Events.CONTAINER_PLAY, this.name);
},
play: function() {
this.playback.play();
},
stop: function() {
this.trigger(Events.CONTAINER_STOP, this.name);
this.playback.stop();
},
pause: function() {
this.trigger(Events.CONTAINER_PAUSE, this.name);
this.playback.pause();
},
ended: function() {
this.trigger(Events.CONTAINER_ENDED, this, this.name);
},
clicked: function() {
this.trigger(Events.CONTAINER_CLICK, this, this.name);
},
setCurrentTime: function(time) {
this.trigger(Events.CONTAINER_SEEK, time, this.name);
this.playback.seek(time);
},
setVolume: function(value) {
this.trigger(Events.CONTAINER_VOLUME, value, this.name);
this.playback.volume(value);
},
fullscreen: function() {
this.trigger(Events.CONTAINER_FULLSCREEN, this.name);
},
buffering: function() {
this.trigger(Events.CONTAINER_STATE_BUFFERING, this.name);
},
bufferfull: function() {
this.trigger(Events.CONTAINER_STATE_BUFFERFULL, this.name);
},
addPlugin: function(plugin) {
this.plugins.push(plugin);
},
hasPlugin: function(name) {
return !!this.getPlugin(name);
},
getPlugin: function(name) {
return _(this.plugins).find(function(plugin) {
return plugin.name === name;
});
},
settingsUpdate: function() {
this.settings = this.playback.settings;
this.trigger(Events.CONTAINER_SETTINGSUPDATE);
},
highDefinitionUpdate: function() {
this.trigger(Events.CONTAINER_HIGHDEFINITIONUPDATE);
},
isHighDefinitionInUse: function() {
return this.playback.isHighDefinitionInUse();
},
disableMediaControl: function() {
this.mediaControlDisabled = true;
this.trigger(Events.CONTAINER_MEDIACONTROL_DISABLE);
},
enableMediaControl: function() {
this.mediaControlDisabled = false;
this.trigger(Events.CONTAINER_MEDIACONTROL_ENABLE);
},
render: function() {
var style = Styler.getStyleFor('container');
this.$el.append(style);
this.$el.append(this.playback.render().el);
return this;
}
}, {}, UIObject);
module.exports = Container;
},{"../../base/styler":8,"events":"events","ui_object":"ui_object","underscore":"underscore"}],11:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var BaseObject = require('base_object');
var Container = require('container');
var $ = require('zepto');
var Events = require('events');
var ContainerFactory = function ContainerFactory(options, loader) {
$traceurRuntime.superCall(this, $ContainerFactory.prototype, "constructor", [options]);
this.options = options;
this.loader = loader;
};
var $ContainerFactory = ContainerFactory;
($traceurRuntime.createClass)(ContainerFactory, {
createContainers: function() {
var $__0 = this;
return $.Deferred((function(promise) {
promise.resolve(_.map($__0.options.sources, (function(source) {
return $__0.createContainer(source);
}), $__0));
}));
},
findPlaybackPlugin: function(source) {
return _.find(this.loader.playbackPlugins, (function(p) {
return p.canPlay(source.toString());
}), this);
},
createContainer: function(source) {
var playbackPlugin = this.findPlaybackPlugin(source);
var options = _.extend({}, this.options, {
src: source,
autoPlay: !!this.options.autoPlay
});
var playback = new playbackPlugin(options);
var container = new Container({playback: playback});
var defer = $.Deferred();
defer.promise(container);
this.addContainerPlugins(container, source);
this.listenToOnce(container, Events.CONTAINER_READY, (function() {
return defer.resolve(container);
}));
return container;
},
addContainerPlugins: function(container, source) {
_.each(this.loader.containerPlugins, function(Plugin) {
var options = _.extend(this.options, {
container: container,
src: source
});
container.addPlugin(new Plugin(options));
}, this);
}
}, {}, BaseObject);
module.exports = ContainerFactory;
},{"base_object":"base_object","container":"container","events":"events","underscore":"underscore","zepto":"zepto"}],12:[function(require,module,exports){
"use strict";
module.exports = require('./container_factory');
},{"./container_factory":11}],13:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var $ = require('zepto');
var UIObject = require('ui_object');
var ContainerFactory = require('../container_factory');
var Fullscreen = require('../../base/utils').Fullscreen;
var Styler = require('../../base/styler');
var MediaControl = require('media_control');
var PlayerInfo = require('player_info');
var Mediator = require('mediator');
var Events = require('events');
var Core = function Core(options) {
var $__0 = this;
$traceurRuntime.superCall(this, $Core.prototype, "constructor", [options]);
PlayerInfo.options = options;
this.options = options;
this.plugins = [];
this.containers = [];
this.createContainers(options);
$(document).bind('fullscreenchange', (function() {
return $__0.exit();
}));
$(document).bind('MSFullscreenChange', (function() {
return $__0.exit();
}));
$(document).bind('mozfullscreenchange', (function() {
return $__0.exit();
}));
};
var $Core = Core;
($traceurRuntime.createClass)(Core, {
get events() {
return {
'webkitfullscreenchange': 'exit',
'mousemove': 'showMediaControl',
'mouseleave': 'hideMediaControl'
};
},
get attributes() {
return {'data-player': ''};
},
createContainers: function(options) {
var $__0 = this;
this.defer = $.Deferred();
this.defer.promise(this);
this.containerFactory = new ContainerFactory(options, options.loader);
this.containerFactory.createContainers().then((function(containers) {
return $__0.setupContainers(containers);
})).then((function(containers) {
return $__0.resolveOnContainersReady(containers);
}));
},
updateSize: function() {
if (Fullscreen.isFullscreen()) {
this.setFullscreen();
} else {
this.setPlayerSize();
}
Mediator.trigger(Events.PLAYER_RESIZE);
},
setFullscreen: function() {
this.$el.addClass('fullscreen');
this.$el.removeAttr('style');
PlayerInfo.previousSize = PlayerInfo.currentSize;
PlayerInfo.currentSize = {
width: $(window).width(),
height: $(window).height()
};
},
setPlayerSize: function() {
this.$el.removeClass('fullscreen');
PlayerInfo.currentSize = PlayerInfo.previousSize;
PlayerInfo.previousSize = {
width: $(window).width(),
height: $(window).height()
};
this.resize(PlayerInfo.currentSize);
},
resize: function(options) {
var size = _.pick(options, 'width', 'height');
this.$el.css(size);
PlayerInfo.previousSize = PlayerInfo.currentSize;
PlayerInfo.currentSize = size;
Mediator.trigger(Events.PLAYER_RESIZE);
},
resolveOnContainersReady: function(containers) {
var $__0 = this;
$.when.apply($, containers).done((function() {
return $__0.defer.resolve($__0);
}));
},
addPlugin: function(plugin) {
this.plugins.push(plugin);
},
hasPlugin: function(name) {
return !!this.getPlugin(name);
},
getPlugin: function(name) {
return _(this.plugins).find((function(plugin) {
return plugin.name === name;
}));
},
load: function(sources) {
var $__0 = this;
sources = _.isArray(sources) ? sources : [sources.toString()];
_(this.containers).each((function(container) {
return container.destroy();
}));
this.containerFactory.options = _(this.options).extend({sources: sources});
this.containerFactory.createContainers().then((function(containers) {
$__0.setupContainers(containers);
}));
},
destroy: function() {
_(this.containers).each((function(container) {
return container.destroy();
}));
_(this.plugins).each((function(plugin) {
return plugin.destroy();
}));
this.$el.remove();
this.mediaControl.destroy();
$(document).unbind('fullscreenchange');
$(document).unbind('MSFullscreenChange');
$(document).unbind('mozfullscreenchange');
},
exit: function() {
this.updateSize();
this.mediaControl.show();
},
setMediaControlContainer: function(container) {
this.mediaControl.setContainer(container);
this.mediaControl.render();
},
disableMediaControl: function() {
this.mediaControl.disable();
this.$el.removeClass('nocursor');
},
enableMediaControl: function() {
this.mediaControl.enable();
},
removeContainer: function(container) {
this.stopListening(container);
this.containers = _.without(this.containers, container);
},
appendContainer: function(container) {
this.listenTo(container, Events.CONTAINER_DESTROYED, this.removeContainer);
this.el.appendChild(container.render().el);
this.containers.push(container);
},
setupContainers: function(containers) {
_.map(containers, this.appendContainer, this);
this.setupMediaControl(this.getCurrentContainer());
this.render();
this.$el.appendTo(this.options.parentElement);
return containers;
},
createContainer: function(source) {
var container = this.containerFactory.createContainer(source);
this.appendContainer(container);
return container;
},
setupMediaControl: function(container) {
if (this.mediaControl) {
this.mediaControl.setContainer(container);
} else {
this.mediaControl = this.createMediaControl(_.extend({container: container}, this.options));
this.listenTo(this.mediaControl, Events.MEDIACONTROL_FULLSCREEN, this.toggleFullscreen);
this.listenTo(this.mediaControl, Events.MEDIACONTROL_SHOW, this.onMediaControlShow.bind(this, true));
this.listenTo(this.mediaControl, Events.MEDIACONTROL_HIDE, this.onMediaControlShow.bind(this, false));
}
},
createMediaControl: function(options) {
if (options.mediacontrol && options.mediacontrol.external) {
return new options.mediacontrol.external(options);
} else {
return new MediaControl(options);
}
},
getCurrentContainer: function() {
return this.containers[0];
},
toggleFullscreen: function() {
if (!Fullscreen.isFullscreen()) {
Fullscreen.requestFullscreen(this.el);
this.$el.addClass('fullscreen');
} else {
Fullscreen.cancelFullscreen();
this.$el.removeClass('fullscreen nocursor');
}
this.mediaControl.show();
},
showMediaControl: function(event) {
this.mediaControl.show(event);
},
hideMediaControl: function(event) {
this.mediaControl.hide(event);
},
onMediaControlShow: function(showing) {
if (showing)
this.$el.removeClass('nocursor');
else if (Fullscreen.isFullscreen())
this.$el.addClass('nocursor');
},
render: function() {
var style = Styler.getStyleFor('core');
this.$el.append(style);
this.$el.append(this.mediaControl.render().el);
this.options.width = this.options.width || this.$el.width();
this.options.height = this.options.height || this.$el.height();
PlayerInfo.previousSize = PlayerInfo.currentSize = _.pick(this.options, 'width', 'height');
this.updateSize();
return this;
}
}, {}, UIObject);
module.exports = Core;
},{"../../base/styler":8,"../../base/utils":9,"../container_factory":12,"events":"events","media_control":"media_control","mediator":"mediator","player_info":"player_info","ui_object":"ui_object","underscore":"underscore","zepto":"zepto"}],14:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var BaseObject = require('base_object');
var Core = require('core');
var CoreFactory = function CoreFactory(player, loader) {
this.player = player;
this.options = player.options;
this.loader = loader;
this.options.loader = this.loader;
};
($traceurRuntime.createClass)(CoreFactory, {
create: function() {
this.core = new Core(this.options);
this.core.then(this.addCorePlugins.bind(this));
return this.core;
},
addCorePlugins: function() {
_.each(this.loader.corePlugins, function(Plugin) {
var plugin = new Plugin(this.core);
this.core.addPlugin(plugin);
this.setupExternalInterface(plugin);
}, this);
return this.core;
},
setupExternalInterface: function(plugin) {
_.each(plugin.getExternalInterface(), function(value, key) {
this.player[key] = value.bind(plugin);
}, this);
}
}, {}, BaseObject);
module.exports = CoreFactory;
},{"base_object":"base_object","core":"core","underscore":"underscore"}],15:[function(require,module,exports){
"use strict";
module.exports = require('./core_factory');
},{"./core_factory":14}],16:[function(require,module,exports){
"use strict";
var BaseObject = require('base_object');
var $ = require('zepto');
var Player = require('../player');
var IframePlayer = function IframePlayer(options) {
$traceurRuntime.superCall(this, $IframePlayer.prototype, "constructor", [options]);
this.options = options;
this.createIframe();
};
var $IframePlayer = IframePlayer;
($traceurRuntime.createClass)(IframePlayer, {
createIframe: function() {
this.iframe = document.createElement("iframe");
this.iframe.setAttribute("frameborder", 0);
this.iframe.setAttribute("id", this.uniqueId);
this.iframe.setAttribute("allowfullscreen", true);
this.iframe.setAttribute("scrolling", "no");
this.iframe.setAttribute("src", "http://cdn.clappr.io/latest/assets/iframe.htm" + this.buildQueryString());
this.iframe.setAttribute('width', this.options.width);
this.iframe.setAttribute('height', this.options.height);
},
attachTo: function(element) {
element.appendChild(this.iframe);
},
addEventListeners: function() {
var $__0 = this;
this.iframe.contentWindow.addEventListener("fullscreenchange", (function() {
return $__0.updateSize();
}));
this.iframe.contentWindow.addEventListener("webkitfullscreenchange", (function() {
return $__0.updateSize();
}));
this.iframe.contentWindow.addEventListener("mozfullscreenchange", (function() {
return $__0.updateSize();
}));
},
buildQueryString: function() {
var result = "";
for (var param in this.options) {
result += !!result ? "&" : "?";
result += encodeURIComponent(param) + "=" + encodeURIComponent(this.options[param]);
}
return result;
}
}, {}, BaseObject);
module.exports = IframePlayer;
},{"../player":21,"base_object":"base_object","zepto":"zepto"}],17:[function(require,module,exports){
"use strict";
module.exports = require('./iframe_player');
},{"./iframe_player":16}],18:[function(require,module,exports){
"use strict";
module.exports = require('./loader');
},{"./loader":19}],19:[function(require,module,exports){
"use strict";
var BaseObject = require('base_object');
var _ = require('underscore');
var PlayerInfo = require('player_info');
var HTML5VideoPlayback = require('html5_video');
var FlashVideoPlayback = require('flash');
var HTML5AudioPlayback = require('html5_audio');
var HLSVideoPlayback = require('hls');
var HTMLImgPlayback = require('html_img');
var NoOp = require('../../playbacks/no_op');
var SpinnerThreeBouncePlugin = require('../../plugins/spinner_three_bounce');
var StatsPlugin = require('../../plugins/stats');
var WaterMarkPlugin = require('../../plugins/watermark');
var PosterPlugin = require('poster');
var GoogleAnalyticsPlugin = require('../../plugins/google_analytics');
var ClickToPausePlugin = require('../../plugins/click_to_pause');
var BackgroundButton = require('../../plugins/background_button');
var DVRControls = require('../../plugins/dvr_controls');
var Loader = function Loader(externalPlugins) {
$traceurRuntime.superCall(this, $Loader.prototype, "constructor", []);
this.playbackPlugins = [FlashVideoPlayback, HTML5VideoPlayback, HTML5AudioPlayback, HLSVideoPlayback, HTMLImgPlayback, NoOp];
this.containerPlugins = [SpinnerThreeBouncePlugin, WaterMarkPlugin, PosterPlugin, StatsPlugin, GoogleAnalyticsPlugin, ClickToPausePlugin];
this.corePlugins = [BackgroundButton, DVRControls];
if (externalPlugins) {
this.addExternalPlugins(externalPlugins);
}
};
var $Loader = Loader;
($traceurRuntime.createClass)(Loader, {
addExternalPlugins: function(plugins) {
var pluginName = function(plugin) {
return plugin.prototype.name;
};
if (plugins.playback) {
this.playbackPlugins = _.uniq(plugins.playback.concat(this.playbackPlugins), pluginName);
}
if (plugins.container) {
this.containerPlugins = _.uniq(plugins.container.concat(this.containerPlugins), pluginName);
}
if (plugins.core) {
this.corePlugins = _.uniq(plugins.core.concat(this.corePlugins), pluginName);
}
PlayerInfo.playbackPlugins = this.playbackPlugins;
},
getPlugin: function(name) {
var allPlugins = _.union(this.containerPlugins, this.playbackPlugins, this.corePlugins);
return _.find(allPlugins, function(plugin) {
return plugin.prototype.name === name;
});
}
}, {}, BaseObject);
module.exports = Loader;
},{"../../playbacks/no_op":29,"../../plugins/background_button":32,"../../plugins/click_to_pause":34,"../../plugins/dvr_controls":36,"../../plugins/google_analytics":38,"../../plugins/spinner_three_bounce":42,"../../plugins/stats":44,"../../plugins/watermark":46,"base_object":"base_object","flash":"flash","hls":"hls","html5_audio":"html5_audio","html5_video":"html5_video","html_img":"html_img","player_info":"player_info","poster":"poster","underscore":"underscore"}],20:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var $ = require('zepto');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var UIObject = require('ui_object');
var Utils = require('../../base/utils');
var SeekTime = require('../seek_time');
var Mediator = require('mediator');
var PlayerInfo = require('player_info');
var Events = require('events');
require('mousetrap');
var MediaControl = function MediaControl(options) {
var $__0 = this;
$traceurRuntime.superCall(this, $MediaControl.prototype, "constructor", [options]);
this.seekTime = new SeekTime(this);
this.options = options;
this.mute = this.options.mute;
this.persistConfig = this.options.persistConfig;
this.container = options.container;
var initialVolume = (this.persistConfig) ? Utils.Config.restore("volume") : 100;
this.setVolume(this.mute ? 0 : initialVolume);
this.keepVisible = false;
this.addEventListeners();
this.settings = {
left: ['play', 'stop', 'pause'],
right: ['volume'],
default: ['position', 'seekbar', 'duration']
};
this.settings = _.isEmpty(this.container.settings) ? this.settings : this.container.settings;
this.disabled = false;
if (this.container.mediaControlDisabled || this.options.chromeless) {
this.disable();
}
$(document).bind('mouseup', (function(event) {
return $__0.stopDrag(event);
}));
$(document).bind('mousemove', (function(event) {
return $__0.updateDrag(event);
}));
Mediator.on(Events.PLAYER_RESIZE, (function() {
return $__0.playerResize();
}));
};
var $MediaControl = MediaControl;
($traceurRuntime.createClass)(MediaControl, {
get name() {
return 'MediaControl';
},
get attributes() {
return {
class: 'media-control',
'data-media-control': ''
};
},
get events() {
return {
'click [data-play]': 'play',
'click [data-pause]': 'pause',
'click [data-playpause]': 'togglePlayPause',
'click [data-stop]': 'stop',
'click [data-playstop]': 'togglePlayStop',
'click [data-fullscreen]': 'toggleFullscreen',
'click .bar-container[data-seekbar]': 'seek',
'click .bar-container[data-volume]': 'volume',
'click .drawer-icon[data-volume]': 'toggleMute',
'mouseenter .drawer-container[data-volume]': 'showVolumeBar',
'mouseleave .drawer-container[data-volume]': 'hideVolumeBar',
'mousedown .bar-scrubber[data-volume]': 'startVolumeDrag',
'mousedown .bar-scrubber[data-seekbar]': 'startSeekDrag',
'mousemove .bar-container[data-seekbar]': 'mousemoveOnSeekBar',
'mouseleave .bar-container[data-seekbar]': 'mouseleaveOnSeekBar',
'mouseenter .media-control-layer[data-controls]': 'setKeepVisible',
'mouseleave .media-control-layer[data-controls]': 'resetKeepVisible'
};
},
get template() {
return JST.media_control;
},
addEventListeners: function() {
this.listenTo(this.container, Events.CONTAINER_PLAY, this.changeTogglePlay);
this.listenTo(this.container, Events.CONTAINER_TIMEUPDATE, this.updateSeekBar);
this.listenTo(this.container, Events.CONTAINER_PROGRESS, this.updateProgressBar);
this.listenTo(this.container, Events.CONTAINER_SETTINGSUPDATE, this.settingsUpdate);
this.listenTo(this.container, Events.CONTAINER_PLAYBACKDVRSTATECHANGED, this.settingsUpdate);
this.listenTo(this.container, Events.CONTAINER_HIGHDEFINITIONUPDATE, this.highDefinitionUpdate);
this.listenTo(this.container, Events.CONTAINER_MEDIACONTROL_DISABLE, this.disable);
this.listenTo(this.container, Events.CONTAINER_MEDIACONTROL_ENABLE, this.enable);
this.listenTo(this.container, Events.CONTAINER_ENDED, this.ended);
},
disable: function() {
this.disabled = true;
this.hide();
this.$el.hide();
},
enable: function() {
if (this.options.chromeless)
return;
this.disabled = false;
this.show();
},
play: function() {
this.container.play();
},
pause: function() {
this.container.pause();
},
stop: function() {
this.container.stop();
},
changeTogglePlay: function() {
if (this.container.isPlaying()) {
this.$playPauseToggle.removeClass('paused').addClass('playing');
this.$playStopToggle.removeClass('stopped').addClass('playing');
this.trigger(Events.MEDIACONTROL_PLAYING);
} else {
this.$playPauseToggle.removeClass('playing').addClass('paused');
this.$playStopToggle.removeClass('playing').addClass('stopped');
this.trigger(Events.MEDIACONTROL_NOTPLAYING);
}
},
mousemoveOnSeekBar: function(event) {
if (this.container.settings.seekEnabled) {
var offsetX = event.pageX - this.$seekBarContainer.offset().left - (this.$seekBarHover.width() / 2);
this.$seekBarHover.css({left: offsetX});
}
this.trigger(Events.MEDIACONTROL_MOUSEMOVE_SEEKBAR, event);
},
mouseleaveOnSeekBar: function(event) {
this.trigger(Events.MEDIACONTROL_MOUSELEAVE_SEEKBAR, event);
},
playerResize: function() {
if (Utils.Fullscreen.isFullscreen()) {
this.$fullscreenToggle.addClass('shrink');
} else {
this.$fullscreenToggle.removeClass('shrink');
}
this.$el.removeClass('w320');
if (PlayerInfo.currentSize.width <= 320) {
this.$el.addClass('w320');
}
},
togglePlayPause: function() {
if (this.container.isPlaying()) {
this.container.pause();
} else {
this.container.play();
}
this.changeTogglePlay();
},
togglePlayStop: function() {
if (this.container.isPlaying()) {
this.container.stop();
} else {
this.container.play();
}
this.changeTogglePlay();
},
startSeekDrag: function(event) {
if (!this.container.settings.seekEnabled)
return;
this.draggingSeekBar = true;
this.$el.addClass('dragging');
this.$seekBarLoaded.addClass('media-control-notransition');
this.$seekBarPosition.addClass('media-control-notransition');
this.$seekBarScrubber.addClass('media-control-notransition');
if (event) {
event.preventDefault();
}
},
startVolumeDrag: function(event) {
this.draggingVolumeBar = true;
this.$el.addClass('dragging');
if (event) {
event.preventDefault();
}
},
stopDrag: function(event) {
if (this.draggingSeekBar) {
this.seek(event);
}
this.$el.removeClass('dragging');
this.$seekBarLoaded.removeClass('media-control-notransition');
this.$seekBarPosition.removeClass('media-control-notransition');
this.$seekBarScrubber.removeClass('media-control-notransition dragging');
this.draggingSeekBar = false;
this.draggingVolumeBar = false;
},
updateDrag: function(event) {
if (event) {
event.preventDefault();
}
if (this.draggingSeekBar) {
var offsetX = event.pageX - this.$seekBarContainer.offset().left;
var pos = offsetX / this.$seekBarContainer.width() * 100;
pos = Math.min(100, Math.max(pos, 0));
this.setSeekPercentage(pos);
} else if (this.draggingVolumeBar) {
this.volume(event);
}
},
volume: function(event) {
var offsetY = event.pageX - this.$volumeBarContainer.offset().left;
var volumeFromUI = (offsetY / this.$volumeBarContainer.width()) * 100;
this.setVolume(volumeFromUI);
},
toggleMute: function() {
if (this.mute) {
if (this.currentVolume <= 0) {
this.currentVolume = 100;
}
this.setVolume(this.currentVolume);
} else {
this.setVolume(0);
}
},
setVolume: function(value) {
this.currentVolume = Math.min(100, Math.max(value, 0));
this.container.setVolume(this.currentVolume);
this.setVolumeLevel(this.currentVolume);
this.mute = this.currentVolume === 0;
this.persistConfig && Utils.Config.persist("volume", this.currentVolume);
},
toggleFullscreen: function() {
this.trigger(Events.MEDIACONTROL_FULLSCREEN, this.name);
this.container.fullscreen();
this.resetKeepVisible();
},
setContainer: function(container) {
this.stopListening(this.container);
this.container = container;
this.changeTogglePlay();
this.addEventListeners();
this.settingsUpdate();
this.container.trigger(Events.CONTAINER_PLAYBACKDVRSTATECHANGED, this.container.isDvrInUse());
this.setVolume(this.currentVolume);
if (this.container.mediaControlDisabled) {
this.disable();
}
this.trigger(Events.MEDIACONTROL_CONTAINERCHANGED);
},
showVolumeBar: function() {
if (this.hideVolumeId) {
clearTimeout(this.hideVolumeId);
}
this.$volumeBarContainer.removeClass('volume-bar-hide');
},
hideVolumeBar: function() {
var $__0 = this;
var timeout = 400;
if (!this.$volumeBarContainer)
return;
if (this.draggingVolumeBar) {
this.hideVolumeId = setTimeout((function() {
return $__0.hideVolumeBar();
}), timeout);
} else {
if (this.hideVolumeId) {
clearTimeout(this.hideVolumeId);
}
this.hideVolumeId = setTimeout((function() {
return $__0.$volumeBarContainer.addClass('volume-bar-hide');
}), timeout);
}
},
ended: function() {
this.changeTogglePlay();
},
updateProgressBar: function(startPosition, endPosition, duration) {
var loadedStart = startPosition / duration * 100;
var loadedEnd = endPosition / duration * 100;
this.$seekBarLoaded.css({
left: loadedStart + '%',
width: (loadedEnd - loadedStart) + '%'
});
},
updateSeekBar: function(position, duration) {
if (this.draggingSeekBar)
return;
if (position < 0)
position = duration;
this.$seekBarPosition.removeClass('media-control-notransition');
this.$seekBarScrubber.removeClass('media-control-notransition');
var seekbarValue = (100 / duration) * position;
this.setSeekPercentage(seekbarValue);
this.$('[data-position]').html(Utils.formatTime(position));
this.$('[data-duration]').html(Utils.formatTime(duration));
},
seek: function(event) {
if (!this.container.settings.seekEnabled)
return;
var offsetX = event.pageX - this.$seekBarContainer.offset().left;
var pos = offsetX / this.$seekBarContainer.width() * 100;
pos = Math.min(100, Math.max(pos, 0));
this.container.setCurrentTime(pos);
this.setSeekPercentage(pos);
return false;
},
setKeepVisible: function() {
this.keepVisible = true;
},
resetKeepVisible: function() {
this.keepVisible = false;
},
isVisible: function() {
return !this.$el.hasClass('media-control-hide');
},
show: function(event) {
var $__0 = this;
if (this.disabled || this.container.getPlaybackType() === null)
return;
var timeout = 2000;
if (!event || (event.clientX !== this.lastMouseX && event.clientY !== this.lastMouseY) || navigator.userAgent.match(/firefox/i)) {
clearTimeout(this.hideId);
this.$el.show();
this.trigger(Events.MEDIACONTROL_SHOW, this.name);
this.$el.removeClass('media-control-hide');
this.hideId = setTimeout((function() {
return $__0.hide();
}), timeout);
if (event) {
this.lastMouseX = event.clientX;
this.lastMouseY = event.clientY;
}
}
},
hide: function() {
var $__0 = this;
var timeout = 2000;
clearTimeout(this.hideId);
if (!this.isVisible() || this.options.hideMediaControl === false)
return;
if (this.keepVisible || this.draggingSeekBar || this.draggingVolumeBar) {
this.hideId = setTimeout((function() {
return $__0.hide();
}), timeout);
} else {
this.trigger(Events.MEDIACONTROL_HIDE, this.name);
this.$el.addClass('media-control-hide');
this.hideVolumeBar();
}
},
settingsUpdate: function() {
if (this.container.getPlaybackType() !== null && !_.isEmpty(this.container.settings)) {
this.settings = this.container.settings;
this.render();
this.enable();
} else {
this.disable();
}
},
highDefinitionUpdate: function() {
if (this.container.isHighDefinitionInUse()) {
this.$el.find('button[data-hd-indicator]').addClass("enabled");
} else {
this.$el.find('button[data-hd-indicator]').removeClass("enabled");
}
},
createCachedElements: function() {
this.$playPauseToggle = this.$el.find('button.media-control-button[data-playpause]');
this.$playStopToggle = this.$el.find('button.media-control-button[data-playstop]');
this.$fullscreenToggle = this.$el.find('button.media-control-button[data-fullscreen]');
this.$seekBarContainer = this.$el.find('.bar-container[data-seekbar]');
this.$seekBarLoaded = this.$el.find('.bar-fill-1[data-seekbar]');
this.$seekBarPosition = this.$el.find('.bar-fill-2[data-seekbar]');
this.$seekBarScrubber = this.$el.find('.bar-scrubber[data-seekbar]');
this.$seekBarHover = this.$el.find('.bar-hover[data-seekbar]');
this.$volumeBarContainer = this.$el.find('.bar-container[data-volume]');
this.$volumeIcon = this.$el.find('.drawer-icon[data-volume]');
},
setVolumeLevel: function(value) {
var $__0 = this;
if (!this.container.isReady || !this.$volumeBarContainer) {
this.listenToOnce(this.container, Events.CONTAINER_READY, (function() {
return $__0.setVolumeLevel(value);
}));
} else {
this.$volumeBarContainer.find('.segmented-bar-element').removeClass('fill');
var item = Math.ceil(value / 10.0);
this.$volumeBarContainer.find('.segmented-bar-element').slice(0, item).addClass('fill');
if (value > 0) {
this.$volumeIcon.removeClass('muted');
} else {
this.$volumeIcon.addClass('muted');
}
}
},
setSeekPercentage: function(value) {
if (value > 100)
return;
var pos = this.$seekBarContainer.width() * value / 100.0 - (this.$seekBarScrubber.width() / 2.0);
this.currentSeekPercentage = value;
this.$seekBarPosition.css({width: value + '%'});
this.$seekBarScrubber.css({left: pos});
},
bindKeyEvents: function() {
var $__0 = this;
Mousetrap.bind(['space'], (function() {
return $__0.togglePlayPause();
}));
},
unbindKeyEvents: function() {
Mousetrap.unbind('space');
},
parseColors: function() {
if (this.options.mediacontrol) {
var buttonsColor = this.options.mediacontrol.buttons;
var seekbarColor = this.options.mediacontrol.seekbar;
this.$el.find('.bar-fill-2[data-seekbar]').css('background-color', seekbarColor);
this.$el.find('[data-media-control] > .media-control-icon, .drawer-icon').css('color', buttonsColor);
this.$el.find('.segmented-bar-element[data-volume]').css('boxShadow', "inset 2px 0 0 " + buttonsColor);
}
},
render: function() {
var $__0 = this;
var timeout = 1000;
var style = Styler.getStyleFor('media_control');
this.$el.html(this.template({settings: this.settings}));
this.$el.append(style);
this.createCachedElements();
this.$playPauseToggle.addClass('paused');
this.$playStopToggle.addClass('stopped');
this.changeTogglePlay();
this.hideId = setTimeout((function() {
return $__0.hide();
}), timeout);
if (this.disabled) {
this.hide();
}
this.$seekBarPosition.addClass('media-control-notransition');
this.$seekBarScrubber.addClass('media-control-notransition');
if (!this.currentSeekPercentage) {
this.currentSeekPercentage = 0;
}
this.setSeekPercentage(this.currentSeekPercentage);
this.$el.ready((function() {
if (!$__0.container.settings.seekEnabled) {
$__0.$seekBarContainer.addClass('seek-disabled');
}
$__0.setVolume($__0.currentVolume);
$__0.bindKeyEvents();
$__0.hideVolumeBar();
}));
this.parseColors();
this.seekTime.render();
this.trigger(Events.MEDIACONTROL_RENDERED);
return this;
},
destroy: function() {
$(document).unbind('mouseup');
$(document).unbind('mousemove');
this.unbindKeyEvents();
}
}, {}, UIObject);
module.exports = MediaControl;
},{"../../base/jst":7,"../../base/styler":8,"../../base/utils":9,"../seek_time":22,"events":"events","mediator":"mediator","mousetrap":4,"player_info":"player_info","ui_object":"ui_object","underscore":"underscore","zepto":"zepto"}],21:[function(require,module,exports){
"use strict";
var BaseObject = require('base_object');
var CoreFactory = require('./core_factory');
var Loader = require('./loader');
var _ = require('underscore');
var ScrollMonitor = require('scrollmonitor');
var PlayerInfo = require('player_info');
var Player = function Player(options) {
$traceurRuntime.superCall(this, $Player.prototype, "constructor", [options]);
window.p = this;
var defaultOptions = {
persistConfig: true,
width: 640,
height: 360
};
this.options = _.extend(defaultOptions, options);
this.options.sources = this.normalizeSources(options);
this.loader = new Loader(this.options.plugins || {});
this.coreFactory = new CoreFactory(this, this.loader);
PlayerInfo.currentSize = {
width: options.width,
height: options.height
};
if (this.options.parentId) {
this.setParentId(this.options.parentId);
}
};
var $Player = Player;
($traceurRuntime.createClass)(Player, {
setParentId: function(parentId) {
var el = document.querySelector(parentId);
if (el) {
this.attachTo(el);
}
},
attachTo: function(element) {
this.options.parentElement = element;
this.core = this.coreFactory.create();
if (this.options.autoPlayVisible) {
this.bindAutoPlayVisible(this.options.autoPlayVisible);
}
},
bindAutoPlayVisible: function(option) {
var $__0 = this;
this.elementWatcher = ScrollMonitor.create(this.core.$el);
if (option === 'full') {
this.elementWatcher.fullyEnterViewport((function() {
return $__0.enterViewport();
}));
} else if (option === 'partial') {
this.elementWatcher.enterViewport((function() {
return $__0.enterViewport();
}));
}
},
enterViewport: function() {
if (this.elementWatcher.top !== 0 && !this.isPlaying()) {
this.play();
}
},
normalizeSources: function(options) {
var sources = _.compact(_.flatten([options.source, options.sources]));
return _.isEmpty(sources) ? ['no.op'] : sources;
},
resize: function(size) {
this.core.resize(size);
},
load: function(sources) {
this.core.load(sources);
},
destroy: function() {
this.core.destroy();
},
play: function() {
this.core.mediaControl.container.play();
},
pause: function() {
this.core.mediaControl.container.pause();
},
stop: function() {
this.core.mediaControl.container.stop();
},
seek: function(time) {
this.core.mediaControl.container.setCurrentTime(time);
},
setVolume: function(volume) {
this.core.mediaControl.container.setVolume(volume);
},
mute: function() {
this.core.mediaControl.container.setVolume(0);
},
unmute: function() {
this.core.mediaControl.container.setVolume(100);
},
isPlaying: function() {
return this.core.mediaControl.container.isPlaying();
}
}, {}, BaseObject);
module.exports = Player;
},{"./core_factory":15,"./loader":18,"base_object":"base_object","player_info":"player_info","scrollmonitor":5,"underscore":"underscore"}],22:[function(require,module,exports){
"use strict";
module.exports = require('./seek_time');
},{"./seek_time":23}],23:[function(require,module,exports){
"use strict";
var UIObject = require('ui_object');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var formatTime = require('../../base/utils').formatTime;
var Events = require('events');
var SeekTime = function SeekTime(mediaControl) {
$traceurRuntime.superCall(this, $SeekTime.prototype, "constructor", []);
this.mediaControl = mediaControl;
this.addEventListeners();
};
var $SeekTime = SeekTime;
($traceurRuntime.createClass)(SeekTime, {
get name() {
return 'seek_time';
},
get template() {
return JST.seek_time;
},
get attributes() {
return {
'class': 'seek-time hidden',
'data-seek-time': ''
};
},
addEventListeners: function() {
this.listenTo(this.mediaControl, Events.MEDIACONTROL_MOUSEMOVE_SEEKBAR, this.showTime);
this.listenTo(this.mediaControl, Events.MEDIACONTROL_MOUSELEAVE_SEEKBAR, this.hideTime);
},
showTime: function(event) {
var offset = event.pageX - this.mediaControl.$seekBarContainer.offset().left;
var timePosition = Math.min(100, Math.max((offset) / this.mediaControl.$seekBarContainer.width() * 100, 0));
var pointerPosition = event.pageX - this.mediaControl.$el.offset().left - (this.$el.width() / 2);
pointerPosition = Math.min(Math.max(0, pointerPosition), this.mediaControl.$el.width() - this.$el.width());
var currentTime = timePosition * this.mediaControl.container.getDuration() / 100;
var options = {
timestamp: currentTime,
formattedTime: formatTime(currentTime),
pointerPosition: pointerPosition
};
this.update(options);
},
hideTime: function() {
this.$el.addClass('hidden');
this.$el.css('left', '-100%');
},
update: function(options) {
if (this.mediaControl.container.getPlaybackType() === 'vod' || this.mediaControl.container.isDvrInUse()) {
this.$el.find('[data-seek-time]').text(options.formattedTime);
this.$el.css('left', options.pointerPosition);
this.$el.removeClass('hidden');
}
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
this.mediaControl.$el.append(this.el);
}
}, {}, UIObject);
module.exports = SeekTime;
},{"../../base/jst":7,"../../base/styler":8,"../../base/utils":9,"events":"events","ui_object":"ui_object"}],24:[function(require,module,exports){
"use strict";
var Playback = require('playback');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var Mediator = require('mediator');
var _ = require('underscore');
var $ = require('zepto');
var Browser = require('browser');
var seekStringToSeconds = require('../../base/utils').seekStringToSeconds;
var Events = require('events');
require('mousetrap');
var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-flash-vod=""><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="gpu"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> </object>';
var Flash = function Flash(options) {
$traceurRuntime.superCall(this, $Flash.prototype, "constructor", [options]);
this.src = options.src;
this.defaultBaseSwfPath = "http://cdn.clappr.io/" + Clappr.version + "/assets/";
this.swfPath = (options.swfBasePath || this.defaultBaseSwfPath) + "Player.swf";
this.autoPlay = options.autoPlay;
this.settings = {default: ['seekbar']};
this.settings.left = ["playpause", "position", "duration"];
this.settings.right = ["fullscreen", "volume"];
this.settings.seekEnabled = true;
this.isReady = false;
this.addListeners();
};
var $Flash = Flash;
($traceurRuntime.createClass)(Flash, {
get name() {
return 'flash';
},
get tagName() {
return 'object';
},
get template() {
return JST.flash;
},
bootstrap: function() {
this.el.width = "100%";
this.el.height = "100%";
this.isReady = true;
if (this.currentState === 'PLAYING') {
this.firstPlay();
} else {
this.currentState = "IDLE";
this.autoPlay && this.play();
}
$('<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%" />').insertAfter(this.$el);
this.trigger(Events.PLAYBACK_READY, this.name);
},
getPlaybackType: function() {
return 'vod';
},
setupFirefox: function() {
var $el = this.$('embed');
$el.attr('data-flash', '');
this.setElement($el[0]);
},
isHighDefinitionInUse: function() {
return false;
},
updateTime: function() {
this.trigger(Events.PLAYBACK_TIMEUPDATE, this.el.getPosition(), this.el.getDuration(), this.name);
},
addListeners: function() {
Mediator.on(this.uniqueId + ':progress', this.progress, this);
Mediator.on(this.uniqueId + ':timeupdate', this.updateTime, this);
Mediator.on(this.uniqueId + ':statechanged', this.checkState, this);
Mediator.on(this.uniqueId + ':flashready', this.bootstrap, this);
_.each(_.range(1, 10), function(i) {
var $__0 = this;
Mousetrap.bind([i.toString()], (function() {
return $__0.seek(i * 10);
}));
}.bind(this));
},
stopListening: function() {
$traceurRuntime.superCall(this, $Flash.prototype, "stopListening", []);
Mediator.off(this.uniqueId + ':progress');
Mediator.off(this.uniqueId + ':timeupdate');
Mediator.off(this.uniqueId + ':statechanged');
Mediator.off(this.uniqueId + ':flashready');
_.each(_.range(1, 10), function(i) {
var $__0 = this;
Mousetrap.unbind([i.toString()], (function() {
return $__0.seek(i * 10);
}));
}.bind(this));
},
checkState: function() {
if (this.currentState === "PAUSED") {
return;
} else if (this.currentState !== "PLAYING_BUFFERING" && this.el.getState() === "PLAYING_BUFFERING") {
this.trigger(Events.PLAYBACK_BUFFERING, this.name);
this.currentState = "PLAYING_BUFFERING";
} else if (this.el.getState() === "PLAYING") {
this.trigger(Events.PLAYBACK_BUFFERFULL, this.name);
this.currentState = "PLAYING";
} else if (this.el.getState() === "IDLE") {
this.currentState = "IDLE";
} else if (this.el.getState() === "ENDED") {
this.trigger(Events.PLAYBACK_ENDED, this.name);
this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.el.getDuration(), this.name);
this.currentState = "ENDED";
}
},
progress: function() {
if (this.currentState !== "IDLE" && this.currentState !== "ENDED") {
this.trigger(Events.PLAYBACK_PROGRESS, 0, this.el.getBytesLoaded(), this.el.getBytesTotal(), this.name);
}
},
firstPlay: function() {
var $__0 = this;
if (this.el.playerPlay) {
this.el.playerPlay(this.src);
this.listenToOnce(this, Events.PLAYBACK_BUFFERFULL, (function() {
return $__0.checkInitialSeek();
}));
this.currentState = "PLAYING";
} else {
this.listenToOnce(this, Events.PLAYBACK_READY, this.firstPlay);
}
},
checkInitialSeek: function() {
var seekTime = seekStringToSeconds(window.location.href);
this.seekSeconds(seekTime);
},
play: function() {
if (this.el.getState() === 'PAUSED' || this.el.getState() === 'PLAYING_BUFFERING') {
this.currentState = "PLAYING";
this.el.playerResume();
} else if (this.el.getState() !== 'PLAYING') {
this.firstPlay();
}
this.trigger(Events.PLAYBACK_PLAY, this.name);
},
volume: function(value) {
var $__0 = this;
if (this.isReady) {
this.el.playerVolume(value);
} else {
this.listenToOnce(this, Events.PLAYBACK_BUFFERFULL, (function() {
return $__0.volume(value);
}));
}
},
pause: function() {
this.currentState = "PAUSED";
this.el.playerPause();
},
stop: function() {
this.el.playerStop();
this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.name);
},
isPlaying: function() {
return !!(this.isReady && this.currentState.indexOf("PLAYING") > -1);
},
getDuration: function() {
return this.el.getDuration();
},
seek: function(seekBarValue) {
var seekTo = this.el.getDuration() * (seekBarValue / 100);
this.seekSeconds(seekTo);
},
seekSeconds: function(seekTo) {
this.el.playerSeek(seekTo);
this.trigger(Events.PLAYBACK_TIMEUPDATE, seekTo, this.el.getDuration(), this.name);
if (this.currentState === "PAUSED") {
this.el.playerPause();
}
},
destroy: function() {
clearInterval(this.bootstrapId);
this.stopListening();
this.$el.remove();
},
setupIE: function() {
this.setElement($(_.template(objectIE)({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
})));
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
}));
if (Browser.isFirefox) {
this.setupFirefox();
} else if (Browser.isLegacyIE) {
this.setupIE();
}
this.$el.append(style);
return this;
}
}, {}, Playback);
Flash.canPlay = function(resource) {
if ((!Browser.isMobile && Browser.isFirefox) || Browser.isLegacyIE) {
return _.isString(resource) && !!resource.match(/(.*)\.(mp4|mov|f4v|3gpp|3gp)/);
} else {
return _.isString(resource) && !!resource.match(/(.*)\.(mov|f4v|3gpp|3gp)/);
}
};
module.exports = Flash;
},{"../../base/jst":7,"../../base/styler":8,"../../base/utils":9,"browser":"browser","events":"events","mediator":"mediator","mousetrap":4,"playback":"playback","underscore":"underscore","zepto":"zepto"}],25:[function(require,module,exports){
"use strict";
var Playback = require('playback');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var _ = require("underscore");
var Mediator = require('mediator');
var Browser = require('browser');
var Events = require('events');
var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" class="hls-playback" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-hls="" width="100%" height="100%"><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> </object>';
var HLS = function HLS(options) {
$traceurRuntime.superCall(this, $HLS.prototype, "constructor", [options]);
this.src = options.src;
this.defaultBaseSwfPath = "http://cdn.clappr.io/" + Clappr.version + "/assets/";
this.swfPath = (options.swfBasePath || this.defaultBaseSwfPath) + "HLSPlayer.swf";
this.flushLiveURLCache = (options.flushLiveURLCache === undefined) ? true : options.flushLiveURLCache;
this.capLevelToStage = (options.capLevelToStage === undefined) ? false : options.capLevelToStage;
this.highDefinition = false;
this.autoPlay = options.autoPlay;
this.defaultSettings = {
left: ["playstop"],
default: ['seekbar'],
right: ["fullscreen", "volume", "hd-indicator"],
seekEnabled: false
};
this.settings = _.extend({}, this.defaultSettings);
this.playbackType = 'live';
this.addListeners();
};
var $HLS = HLS;
($traceurRuntime.createClass)(HLS, {
get name() {
return 'hls';
},
get tagName() {
return 'object';
},
get template() {
return JST.hls;
},
get attributes() {
return {
'class': 'hls-playback',
'data-hls': '',
'type': 'application/x-shockwave-flash'
};
},
addListeners: function() {
var $__0 = this;
Mediator.on(this.uniqueId + ':flashready', (function() {
return $__0.bootstrap();
}));
Mediator.on(this.uniqueId + ':timeupdate', (function() {
return $__0.updateTime();
}));
Mediator.on(this.uniqueId + ':playbackstate', (function(state) {
return $__0.setPlaybackState(state);
}));
Mediator.on(this.uniqueId + ':highdefinition', (function(isHD) {
return $__0.updateHighDefinition(isHD);
}));
Mediator.on(this.uniqueId + ':playbackerror', (function() {
return $__0.flashPlaybackError();
}));
},
stopListening: function() {
$traceurRuntime.superCall(this, $HLS.prototype, "stopListening", []);
Mediator.off(this.uniqueId + ':flashready');
Mediator.off(this.uniqueId + ':timeupdate');
Mediator.off(this.uniqueId + ':playbackstate');
Mediator.off(this.uniqueId + ':highdefinition');
Mediator.off(this.uniqueId + ':playbackerror');
},
bootstrap: function() {
this.el.width = "100%";
this.el.height = "100%";
this.isReady = true;
this.trigger(Events.PLAYBACK_READY, this.name);
this.currentState = "IDLE";
this.setFlashSettings();
this.autoPlay && this.play();
},
setFlashSettings: function() {
this.el.globoPlayerSetflushLiveURLCache(this.flushLiveURLCache);
this.el.globoPlayerCapLeveltoStage(this.capLevelToStage);
this.el.globoPlayerSetmaxBufferLength(0);
},
updateHighDefinition: function(isHD) {
this.highDefinition = (isHD === "true");
this.trigger(Events.PLAYBACK_HIGHDEFINITIONUPDATE);
this.trigger(Events.PLAYBACK_BITRATE, {'bitrate': this.getCurrentBitrate()});
},
updateTime: function() {
var duration = this.getDuration();
var position = Math.min(Math.max(this.el.globoGetPosition(), 0), duration);
var previousDVRStatus = this.dvrEnabled;
var livePlayback = (this.playbackType === 'live');
this.dvrEnabled = (livePlayback && duration > 240);
if (duration === 100 || livePlayback === undefined) {
return;
}
if (this.dvrEnabled !== previousDVRStatus) {
this.updateSettings();
this.trigger(Events.PLAYBACK_SETTINGSUPDATE, this.name);
}
if (livePlayback && (!this.dvrEnabled || !this.dvrInUse)) {
position = duration;
}
this.trigger(Events.PLAYBACK_TIMEUPDATE, position, duration, this.name);
},
play: function() {
if (this.currentState === 'PAUSED') {
this.el.globoPlayerResume();
} else if (this.currentState !== "PLAYING") {
this.firstPlay();
}
this.trigger(Events.PLAYBACK_PLAY, this.name);
},
getPlaybackType: function() {
return this.playbackType ? this.playbackType : null;
},
getCurrentBitrate: function() {
var currentLevel = this.getLevels()[this.el.globoGetLevel()];
return currentLevel.bitrate;
},
getLastProgramDate: function() {
var programDate = this.el.globoGetLastProgramDate();
return programDate - 1.08e+7;
},
isHighDefinitionInUse: function() {
return this.highDefinition;
},
getLevels: function() {
if (!this.levels || this.levels.length === 0) {
this.levels = this.el.globoGetLevels();
}
return this.levels;
},
setPlaybackState: function(state) {
var bufferLength = this.el.globoGetbufferLength();
if (state === "PLAYING_BUFFERING" && bufferLength < 1) {
this.trigger(Events.PLAYBACK_BUFFERING, this.name);
this.updateCurrentState(state);
} else if (state === "PLAYING") {
if (_.contains(["PLAYING_BUFFERING", "PAUSED", "IDLE"], this.currentState)) {
this.trigger(Events.PLAYBACK_BUFFERFULL, this.name);
this.updateCurrentState(state);
}
} else if (state === "PAUSED") {
this.updateCurrentState(state);
} else if (state === "IDLE") {
this.trigger(Events.PLAYBACK_ENDED, this.name);
this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.el.globoGetDuration(), this.name);
this.updateCurrentState(state);
}
this.lastBufferLength = bufferLength;
},
updateCurrentState: function(state) {
this.currentState = state;
this.updatePlaybackType();
},
updatePlaybackType: function() {
this.playbackType = this.el.globoGetType();
if (this.playbackType) {
this.playbackType = this.playbackType.toLowerCase();
if (this.playbackType === 'vod') {
this.startReportingProgress();
} else {
this.stopReportingProgress();
}
}
this.trigger(Events.PLAYBACK_PLAYBACKSTATE);
},
startReportingProgress: function() {
if (!this.reportingProgress) {
this.reportingProgress = true;
Mediator.on(this.uniqueId + ':fragmentloaded', this.onFragmentLoaded);
}
},
stopReportingProgress: function() {
Mediator.off(this.uniqueId + ':fragmentloaded', this.onFragmentLoaded, this);
},
onFragmentLoaded: function() {
var buffered = this.el.globoGetPosition() + this.el.globoGetbufferLength();
this.trigger(Events.PLAYBACK_PROGRESS, this.el.globoGetPosition(), buffered, this.getDuration(), this.name);
},
firstPlay: function() {
this.el.globoPlayerLoad(this.src);
this.el.globoPlayerPlay();
},
volume: function(value) {
var $__0 = this;
if (this.isReady) {
this.el.globoPlayerVolume(value);
} else {
this.listenToOnce(this, Events.PLAYBACK_BUFFERFULL, (function() {
return $__0.volume(value);
}));
}
},
pause: function() {
if (this.playbackType !== 'live' || this.dvrEnabled) {
this.el.globoPlayerPause();
if (this.playbackType === 'live' && this.dvrEnabled) {
this.updateDvr(true);
}
}
},
stop: function() {
this.el.globoPlayerStop();
this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.name);
},
isPlaying: function() {
if (this.currentState) {
return !!(this.currentState.match(/playing/i));
}
return false;
},
getDuration: function() {
var duration = this.el.globoGetDuration();
if (this.playbackType === 'live') {
duration = duration - 10;
}
return duration;
},
seek: function(time) {
var duration = this.getDuration();
if (time > 0) {
time = duration * time / 100;
}
if (this.playbackType === 'live') {
var dvrInUse = (time >= 0 && duration - time > 5);
if (!dvrInUse) {
time = -1;
}
this.updateDvr(dvrInUse);
}
this.el.globoPlayerSeek(time);
this.trigger(Events.PLAYBACK_TIMEUPDATE, time, duration, this.name);
},
updateDvr: function(dvrInUse) {
var previousDvrInUse = !!this.dvrInUse;
this.dvrInUse = dvrInUse;
if (this.dvrInUse !== previousDvrInUse) {
this.updateSettings();
this.trigger(Events.PLAYBACK_DVR, this.dvrInUse);
this.trigger(Events.PLAYBACK_STATS_ADD, {'dvr': this.dvrInUse});
}
},
flashPlaybackError: function() {
this.trigger(Events.PLAYBACK_STOP);
},
timeUpdate: function(time, duration) {
this.trigger(Events.PLAYBACK_TIMEUPDATE, time, duration, this.name);
},
destroy: function() {
this.stopListening();
this.$el.remove();
},
setupFirefox: function() {
var $el = this.$('embed');
$el.attr('data-hls', '');
this.setElement($el);
},
setupIE: function() {
this.setElement($(_.template(objectIE)({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
})));
},
updateSettings: function() {
this.settings = _.extend({}, this.defaultSettings);
if (this.playbackType === "vod" || this.dvrInUse) {
this.settings.left = ["playpause", "position", "duration"];
this.settings.seekEnabled = true;
} else if (this.dvrEnabled) {
this.settings.left = ["playpause"];
this.settings.seekEnabled = true;
} else {
this.settings.seekEnabled = false;
}
},
setElement: function(element) {
this.$el = element;
this.el = element[0];
},
render: function() {
var style = Styler.getStyleFor(this.name);
if (Browser.isLegacyIE) {
this.setupIE();
} else {
this.$el.html(this.template({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
}));
if (Browser.isFirefox) {
this.setupFirefox();
} else if (Browser.isIE) {
this.$('embed').remove();
}
}
this.el.id = this.cid;
this.$el.append(style);
return this;
}
}, {}, Playback);
HLS.canPlay = function(resource) {
return !!resource.match(/^http(.*).m3u8?/);
};
module.exports = HLS;
},{"../../base/jst":7,"../../base/styler":8,"browser":"browser","events":"events","mediator":"mediator","playback":"playback","underscore":"underscore"}],26:[function(require,module,exports){
"use strict";
var Playback = require('playback');
var Events = require('events');
var HTML5Audio = function HTML5Audio(params) {
$traceurRuntime.superCall(this, $HTML5Audio.prototype, "constructor", [params]);
this.el.src = params.src;
this.settings = {
left: ['playpause', 'position', 'duration'],
right: ['fullscreen', 'volume'],
default: ['seekbar']
};
this.render();
params.autoPlay && this.play();
};
var $HTML5Audio = HTML5Audio;
($traceurRuntime.createClass)(HTML5Audio, {
get name() {
return 'html5_audio';
},
get tagName() {
return 'audio';
},
get events() {
return {
'timeupdate': 'timeUpdated',
'ended': 'ended',
'canplaythrough': 'bufferFull'
};
},
bindEvents: function() {
this.listenTo(this.container, Events.CONTAINER_PLAY, this.play);
this.listenTo(this.container, Events.CONTAINER_PAUSE, this.pause);
this.listenTo(this.container, Events.CONTAINER_SEEK, this.seek);
this.listenTo(this.container, Events.CONTAINER_VOLUME, this.volume);
this.listenTo(this.container, Events.CONTAINER_STOP, this.stop);
},
getPlaybackType: function() {
return "aod";
},
play: function() {
this.el.play();
this.trigger(Events.PLAYBACK_PLAY);
},
pause: function() {
this.el.pause();
},
stop: function() {
this.pause();
this.el.currentTime = 0;
},
volume: function(value) {
this.el.volume = value / 100;
},
mute: function() {
this.el.volume = 0;
},
unmute: function() {
this.el.volume = 1;
},
isMuted: function() {
return !!this.el.volume;
},
ended: function() {
this.trigger(Events.CONTAINER_TIMEUPDATE, 0);
},
seek: function(seekBarValue) {
var time = this.el.duration * (seekBarValue / 100);
this.el.currentTime = time;
},
getCurrentTime: function() {
return this.el.currentTime;
},
getDuration: function() {
return this.el.duration;
},
isPlaying: function() {
return !this.el.paused && !this.el.ended;
},
timeUpdated: function() {
this.trigger(Events.PLAYBACK_TIMEUPDATE, this.el.currentTime, this.el.duration, this.name);
},
bufferFull: function() {
this.trigger(Events.PLAYBACK_TIMEUPDATE, this.el.currentTime, this.el.duration, this.name);
this.trigger(Events.PLAYBACK_BUFFERFULL);
},
render: function() {
this.trigger(Events.PLAYBACK_READY, this.name);
return this;
}
}, {}, Playback);
HTML5Audio.canPlay = function(resource) {
return !!resource.match(/(.*).mp3/);
};
module.exports = HTML5Audio;
},{"events":"events","playback":"playback"}],27:[function(require,module,exports){
(function (process){
"use strict";
var Playback = require('playback');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var Browser = require('browser');
var seekStringToSeconds = require('../../base/utils').seekStringToSeconds;
var Events = require('events');
var _ = require('underscore');
require('mousetrap');
var HTML5Video = function HTML5Video(options) {
$traceurRuntime.superCall(this, $HTML5Video.prototype, "constructor", [options]);
this.options = options;
this.src = options.src;
this.el.src = options.src;
this.el.loop = options.loop;
this.firstBuffer = true;
this.isHLS = (this.src.indexOf('m3u8') > -1);
this.settings = {default: ['seekbar']};
if (this.isHLS && Browser.isSafari) {
this.settings.left = ["playstop"];
this.settings.right = ["fullscreen", "volume"];
} else {
this.el.preload = options.preload ? options.preload : 'metadata';
this.settings.left = ["playpause", "position", "duration"];
this.settings.right = ["fullscreen", "volume"];
this.settings.seekEnabled = true;
}
this.bindEvents();
};
var $HTML5Video = HTML5Video;
($traceurRuntime.createClass)(HTML5Video, {
get name() {
return 'html5_video';
},
get tagName() {
return 'video';
},
get template() {
return JST.html5_video;
},
get attributes() {
return {'data-html5-video': ''};
},
get events() {
return {
'timeupdate': 'timeUpdated',
'progress': 'progress',
'ended': 'ended',
'stalled': 'stalled',
'waiting': 'waiting',
'canplaythrough': 'bufferFull',
'loadedmetadata': 'loadedMetadata'
};
},
bindEvents: function() {
_.each(_.range(1, 10), function(i) {
var $__0 = this;
Mousetrap.bind([i.toString()], (function() {
return $__0.seek(i * 10);
}));
}.bind(this));
},
loadedMetadata: function(e) {
this.trigger(Events.PLAYBACK_LOADEDMETADATA, e.target.duration);
this.trigger(Events.PLAYBACK_SETTINGSUPDATE);
this.checkInitialSeek();
},
getPlaybackType: function() {
return this.isHLS && _.contains([0, undefined, Infinity], this.el.duration) ? 'live' : 'vod';
},
isHighDefinitionInUse: function() {
return false;
},
play: function() {
this.el.play();
this.trigger(Events.PLAYBACK_PLAY);
if (this.isHLS) {
this.trigger(Events.PLAYBACK_TIMEUPDATE, 1, 1, this.name);
}
},
pause: function() {
this.el.pause();
},
stop: function() {
this.pause();
if (this.el.readyState !== 0) {
this.el.currentTime = 0;
}
},
volume: function(value) {
this.el.volume = value / 100;
},
mute: function() {
this.el.volume = 0;
},
unmute: function() {
this.el.volume = 1;
},
isMuted: function() {
return !!this.el.volume;
},
isPlaying: function() {
return !this.el.paused && !this.el.ended;
},
ended: function() {
this.trigger(Events.PLAYBACK_ENDED, this.name);
this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.el.duration, this.name);
},
stalled: function() {
if (this.getPlaybackType() === 'vod' && this.el.readyState < this.el.HAVE_FUTURE_DATA) {
this.trigger(Events.PLAYBACK_BUFFERING, this.name);
}
},
waiting: function() {
if (this.el.readyState < this.el.HAVE_FUTURE_DATA) {
this.trigger(Events.PLAYBACK_BUFFERING, this.name);
}
},
bufferFull: function() {
if (this.options.poster && this.firstBuffer) {
this.firstBuffer = false;
if (!this.isPlaying()) {
this.el.poster = this.options.poster;
}
} else {
this.el.poster = '';
}
this.trigger(Events.PLAYBACK_BUFFERFULL, this.name);
},
destroy: function() {
this.stop();
this.el.src = '';
this.$el.remove();
},
seek: function(seekBarValue) {
var time = this.el.duration * (seekBarValue / 100);
this.seekSeconds(time);
},
seekSeconds: function(time) {
this.el.currentTime = time;
},
checkInitialSeek: function() {
var seekTime = seekStringToSeconds(window.location.href);
this.seekSeconds(seekTime);
},
getCurrentTime: function() {
return this.el.currentTime;
},
getDuration: function() {
return this.el.duration;
},
timeUpdated: function() {
if (this.getPlaybackType() !== 'live') {
this.trigger(Events.PLAYBACK_TIMEUPDATE, this.el.currentTime, this.el.duration, this.name);
}
},
progress: function() {
if (!this.el.buffered.length)
return;
var bufferedPos = 0;
for (var i = 0; i < this.el.buffered.length; i++) {
if (this.el.currentTime >= this.el.buffered.start(i) && this.el.currentTime <= this.el.buffered.end(i)) {
bufferedPos = i;
break;
}
}
this.trigger(Events.PLAYBACK_PROGRESS, this.el.buffered.start(bufferedPos), this.el.buffered.end(bufferedPos), this.el.duration, this.name);
},
typeFor: function(src) {
return (src.indexOf('.m3u8') > 0) ? 'application/vnd.apple.mpegurl' : 'video/mp4';
},
render: function() {
var $__0 = this;
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template({
src: this.src,
type: this.typeFor(this.src)
}));
this.$el.append(style);
this.trigger(Events.PLAYBACK_READY, this.name);
process.nextTick((function() {
return $__0.options.autoPlay && $__0.play();
}));
return this;
}
}, {}, Playback);
HTML5Video.canPlay = function(resource) {
var mimetypes = {
'mp4': _.map(["avc1.42E01E", "avc1.58A01E", "avc1.4D401E", "avc1.64001E", "mp4v.20.8", "mp4v.20.240"], function(codec) {
return 'video/mp4; codecs=' + codec + ', mp4a.40.2';
}),
'ogg': ['video/ogg; codecs="theora, vorbis"', 'video/ogg; codecs="dirac"', 'video/ogg; codecs="theora, speex"'],
'3gpp': ['video/3gpp; codecs="mp4v.20.8, samr"'],
'webm': ['video/webm; codecs="vp8, vorbis"'],
'mkv': ['video/x-matroska; codecs="theora, vorbis"'],
'm3u8': ['application/x-mpegURL']
};
mimetypes['ogv'] = mimetypes['ogg'];
mimetypes['3gp'] = mimetypes['3gpp'];
var extension = resource.split('?')[0].match(/.*\.(.*)$/)[1];
if (_.has(mimetypes, extension)) {
var v = document.createElement('video');
return !!_.find(mimetypes[extension], function(ext) {
return !!v.canPlayType(ext).replace(/no/, '');
});
}
return false;
};
module.exports = HTML5Video;
}).call(this,require('_process'))
},{"../../base/jst":7,"../../base/styler":8,"../../base/utils":9,"_process":2,"browser":"browser","events":"events","mousetrap":4,"playback":"playback","underscore":"underscore"}],28:[function(require,module,exports){
"use strict";
var Playback = require('playback');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var Events = require('events');
var HTMLImg = function HTMLImg(params) {
$traceurRuntime.superCall(this, $HTMLImg.prototype, "constructor", [params]);
this.el.src = params.src;
setTimeout(function() {
this.trigger(Events.PLAYBACK_BUFFERFULL, this.name);
}.bind(this), 1);
};
var $HTMLImg = HTMLImg;
($traceurRuntime.createClass)(HTMLImg, {
get name() {
return 'html_img';
},
get tagName() {
return 'img';
},
get attributes() {
return {'data-html-img': ''};
},
getPlaybackType: function() {
return null;
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.append(style);
return this;
}
}, {}, Playback);
HTMLImg.canPlay = function(resource) {
return !!resource.match(/(.*).(png|jpg|jpeg|gif|bmp)/);
};
module.exports = HTMLImg;
},{"../../base/jst":7,"../../base/styler":8,"events":"events","playback":"playback"}],29:[function(require,module,exports){
"use strict";
module.exports = require('./no_op');
},{"./no_op":30}],30:[function(require,module,exports){
"use strict";
var Playback = require('playback');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var NoOp = function NoOp(options) {
$traceurRuntime.superCall(this, $NoOp.prototype, "constructor", [options]);
};
var $NoOp = NoOp;
($traceurRuntime.createClass)(NoOp, {
get name() {
return 'no_op';
},
get template() {
return JST.no_op;
},
get attributes() {
return {'data-no-op': ''};
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
return this;
}
}, {}, Playback);
NoOp.canPlay = (function(source) {
return true;
});
module.exports = NoOp;
},{"../../base/jst":7,"../../base/styler":8,"playback":"playback"}],31:[function(require,module,exports){
(function (process){
"use strict";
var UICorePlugin = require('ui_core_plugin');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var Events = require('events');
var Browser = require('browser');
var Mediator = require('mediator');
var PlayerInfo = require('player_info');
var BackgroundButton = function BackgroundButton(core) {
$traceurRuntime.superCall(this, $BackgroundButton.prototype, "constructor", [core]);
this.core = core;
this.settingsUpdate();
};
var $BackgroundButton = BackgroundButton;
($traceurRuntime.createClass)(BackgroundButton, {
get template() {
return JST.background_button;
},
get name() {
return 'background_button';
},
get attributes() {
return {
'class': 'background-button',
'data-background-button': ''
};
},
get events() {
return {'click .background-button-icon': 'click'};
},
bindEvents: function() {
this.listenTo(this.core.mediaControl.container, Events.CONTAINER_STATE_BUFFERING, this.hide);
this.listenTo(this.core.mediaControl.container, Events.CONTAINER_STATE_BUFFERFULL, this.show);
this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_RENDERED, this.settingsUpdate);
this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_SHOW, this.updateSize);
this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_PLAYING, this.playing);
this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_NOTPLAYING, this.notplaying);
Mediator.on(Events.PLAYER_RESIZE, this.updateSize, this);
},
stopListening: function() {
$traceurRuntime.superCall(this, $BackgroundButton.prototype, "stopListening", []);
Mediator.off(Events.PLAYER_RESIZE, this.updateSize, this);
},
settingsUpdate: function() {
this.stopListening();
if (this.shouldRender()) {
this.render();
this.bindEvents();
if (this.core.mediaControl.container.isPlaying()) {
this.playing();
} else {
this.notplaying();
}
} else {
this.$el.remove();
this.$playPauseButton.show();
this.$playStopButton.show();
this.listenTo(this.core.mediaControl.container, Events.CONTAINER_SETTINGSUPDATE, this.settingsUpdate);
this.listenTo(this.core.mediaControl.container, Events.CONTAINER_PLAYBACKDVRSTATECHANGED, this.settingsUpdate);
this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_CONTAINERCHANGED, this.settingsUpdate);
}
},
shouldRender: function() {
var useBackgroundButton = (this.core.options.useBackgroundButton === undefined && Browser.isMobile) || !!this.core.options.useBackgroundButton;
return useBackgroundButton && (this.core.mediaControl.$el.find('[data-playstop]').length > 0 || this.core.mediaControl.$el.find('[data-playpause]').length > 0);
},
click: function() {
this.core.mediaControl.show();
if (this.shouldStop) {
this.core.mediaControl.togglePlayStop();
} else {
this.core.mediaControl.togglePlayPause();
}
},
show: function() {
this.$el.removeClass('hide');
},
hide: function() {
this.$el.addClass('hide');
},
enable: function() {
this.stopListening();
$traceurRuntime.superCall(this, $BackgroundButton.prototype, "enable", []);
this.settingsUpdate();
},
disable: function() {
$traceurRuntime.superCall(this, $BackgroundButton.prototype, "disable", []);
this.$playPauseButton.show();
this.$playStopButton.show();
},
playing: function() {
this.$buttonIcon.removeClass('notplaying').addClass('playing');
},
notplaying: function() {
this.$buttonIcon.removeClass('playing').addClass('notplaying');
},
getExternalInterface: function() {},
updateSize: function() {
if (!this.$el)
return;
var height = PlayerInfo.currentSize ? PlayerInfo.currentSize.height : this.$el.height();
this.$el.css({fontSize: height});
this.$buttonWrapper.css({marginTop: -(this.$buttonWrapper.height() / 2)});
},
render: function() {
var $__0 = this;
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
this.$playPauseButton = this.core.mediaControl.$el.find('[data-playpause]');
this.$playStopButton = this.core.mediaControl.$el.find('[data-playstop]');
this.$buttonWrapper = this.$el.find('.background-button-wrapper[data-background-button]');
this.$buttonIcon = this.$el.find('.background-button-icon[data-background-button]');
this.shouldStop = this.$playStopButton.length > 0;
this.$el.insertBefore(this.core.mediaControl.$el.find('.media-control-layer[data-controls]'));
this.$el.click((function() {
return $__0.click($__0.$el);
}));
process.nextTick((function() {
return $__0.updateSize();
}));
if (this.core.options.useBackgroundButton) {
this.$playPauseButton.hide();
this.$playStopButton.hide();
}
if (this.shouldStop) {
this.$buttonIcon.addClass('playstop');
}
if (this.core.mediaControl.isVisible()) {
this.show();
}
return this;
}
}, {}, UICorePlugin);
module.exports = BackgroundButton;
}).call(this,require('_process'))
},{"../../base/jst":7,"../../base/styler":8,"_process":2,"browser":"browser","events":"events","mediator":"mediator","player_info":"player_info","ui_core_plugin":"ui_core_plugin"}],32:[function(require,module,exports){
"use strict";
module.exports = require('./background_button');
},{"./background_button":31}],33:[function(require,module,exports){
"use strict";
var ContainerPlugin = require('container_plugin');
var Events = require('events');
var ClickToPausePlugin = function ClickToPausePlugin() {
$traceurRuntime.defaultSuperCall(this, $ClickToPausePlugin.prototype, arguments);
};
var $ClickToPausePlugin = ClickToPausePlugin;
($traceurRuntime.createClass)(ClickToPausePlugin, {
get name() {
return 'click_to_pause';
},
bindEvents: function() {
this.listenTo(this.container, Events.CONTAINER_CLICK, this.click);
this.listenTo(this.container, Events.CONTAINER_SETTINGSUPDATE, this.settingsUpdate);
},
click: function() {
if (this.container.getPlaybackType() !== 'live' || this.container.isDvrEnabled()) {
if (this.container.isPlaying()) {
this.container.pause();
} else {
this.container.play();
}
}
},
settingsUpdate: function() {
this.container.$el.removeClass('pointer-enabled');
if (this.container.getPlaybackType() !== 'live' || this.container.isDvrEnabled()) {
this.container.$el.addClass('pointer-enabled');
}
}
}, {}, ContainerPlugin);
module.exports = ClickToPausePlugin;
},{"container_plugin":"container_plugin","events":"events"}],34:[function(require,module,exports){
"use strict";
module.exports = require('./click_to_pause');
},{"./click_to_pause":33}],35:[function(require,module,exports){
"use strict";
var UICorePlugin = require('ui_core_plugin');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var Events = require('events');
var DVRControls = function DVRControls(core) {
$traceurRuntime.superCall(this, $DVRControls.prototype, "constructor", [core]);
this.core = core;
this.settingsUpdate();
};
var $DVRControls = DVRControls;
($traceurRuntime.createClass)(DVRControls, {
get template() {
return JST.dvr_controls;
},
get name() {
return 'dvr_controls';
},
get events() {
return {'click .live-button': 'click'};
},
get attributes() {
return {
'class': 'dvr-controls',
'data-dvr-controls': ''
};
},
bindEvents: function() {
this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_RENDERED, this.settingsUpdate);
this.listenTo(this.core.mediaControl.container, Events.CONTAINER_PLAYBACKDVRSTATECHANGED, this.dvrChanged);
},
dvrChanged: function(dvrEnabled) {
this.settingsUpdate();
this.core.mediaControl.$el.addClass('live');
if (dvrEnabled) {
this.core.mediaControl.$el.addClass('dvr');
this.core.mediaControl.$el.find('.media-control-indicator[data-position], .media-control-indicator[data-duration]').hide();
} else {
this.core.mediaControl.$el.removeClass('dvr');
}
},
click: function() {
if (!this.core.mediaControl.container.isPlaying()) {
this.core.mediaControl.container.play();
}
if (this.core.mediaControl.$el.hasClass('dvr')) {
this.core.mediaControl.container.setCurrentTime(-1);
}
},
settingsUpdate: function() {
var $__0 = this;
this.stopListening();
if (this.shouldRender()) {
this.render();
this.$el.click((function() {
return $__0.click();
}));
}
this.bindEvents();
},
shouldRender: function() {
var useDvrControls = this.core.options.useDvrControls === undefined || !!this.core.options.useDvrControls;
return useDvrControls && this.core.mediaControl.container.getPlaybackType() === 'live';
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
if (this.shouldRender()) {
this.core.mediaControl.$el.addClass('live');
this.core.mediaControl.$('.media-control-left-panel[data-media-control]').append(this.$el);
if (this.$duration) {
this.$duration.remove();
}
this.$duration = $('<span data-duration></span>');
this.core.mediaControl.seekTime.$el.append(this.$duration);
}
return this;
}
}, {}, UICorePlugin);
module.exports = DVRControls;
},{"../../base/jst":7,"../../base/styler":8,"events":"events","ui_core_plugin":"ui_core_plugin"}],36:[function(require,module,exports){
"use strict";
module.exports = require('./dvr_controls');
},{"./dvr_controls":35}],37:[function(require,module,exports){
"use strict";
var ContainerPlugin = require('container_plugin');
var Events = require('events');
var GoogleAnalytics = function GoogleAnalytics(options) {
$traceurRuntime.superCall(this, $GoogleAnalytics.prototype, "constructor", [options]);
if (options.gaAccount) {
this.embedScript();
this.account = options.gaAccount;
this.trackerName = options.gaTrackerName + "." || 'Clappr.';
this.currentHDState = undefined;
}
};
var $GoogleAnalytics = GoogleAnalytics;
($traceurRuntime.createClass)(GoogleAnalytics, {
get name() {
return 'google_analytics';
},
embedScript: function() {
var $__0 = this;
if (!window._gat) {
var script = document.createElement('script');
script.setAttribute("type", "text/javascript");
script.setAttribute("async", "async");
script.setAttribute("src", "http://www.google-analytics.com/ga.js");
script.onload = (function() {
return $__0.addEventListeners();
});
document.body.appendChild(script);
} else {
this.addEventListeners();
}
},
addEventListeners: function() {
var $__0 = this;
this.listenTo(this.container, Events.CONTAINER_PLAY, this.onPlay);
this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop);
this.listenTo(this.container, Events.CONTAINER_PAUSE, this.onPause);
this.listenTo(this.container, Events.CONTAINER_ENDED, this.onEnded);
this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERING, this.onBuffering);
this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERFULL, this.onBufferFull);
this.listenTo(this.container, Events.CONTAINER_ENDED, this.onEnded);
this.listenTo(this.container, Events.CONTAINER_ERROR, this.onError);
this.listenTo(this.container, Events.CONTAINER_PLAYBACKSTATE, this.onPlaybackChanged);
this.listenTo(this.container, Events.CONTAINER_VOLUME, (function(event) {
return $__0.onVolumeChanged(event);
}));
this.listenTo(this.container, Events.CONTAINER_SEEK, (function(event) {
return $__0.onSeek(event);
}));
this.listenTo(this.container, Events.CONTAINER_FULL_SCREEN, this.onFullscreen);
this.listenTo(this.container, Events.CONTAINER_HIGHDEFINITIONUPDATE, this.onHD);
this.listenTo(this.container.playback, Events.PLAYBACK_DVR, this.onDVR);
_gaq.push([this.trackerName + '_setAccount', this.account]);
},
onPlay: function() {
this.push(["Video", "Play", this.container.playback.src]);
},
onStop: function() {
this.push(["Video", "Stop", this.container.playback.src]);
},
onEnded: function() {
this.push(["Video", "Ended", this.container.playback.src]);
},
onBuffering: function() {
this.push(["Video", "Buffering", this.container.playback.src]);
},
onBufferFull: function() {
this.push(["Video", "Bufferfull", this.container.playback.src]);
},
onError: function() {
this.push(["Video", "Error", this.container.playback.src]);
},
onHD: function() {
var status = this.container.isHighDefinitionInUse() ? "ON" : "OFF";
if (status !== this.currentHDState) {
this.currentHDState = status;
this.push(["Video", "HD - " + status, this.container.playback.src]);
}
},
onPlaybackChanged: function() {
var type = this.container.getPlaybackType();
if (type !== null) {
this.push(["Video", "Playback Type - " + type, this.container.playback.src]);
}
},
onDVR: function() {
var status = this.container.isHighDefinitionInUse();
this.push(["Interaction", "DVR - " + status, this.container.playback.src]);
},
onPause: function() {
this.push(["Video", "Pause", this.container.playback.src]);
},
onSeek: function() {
this.push(["Video", "Seek", this.container.playback.src]);
},
onVolumeChanged: function() {
this.push(["Interaction", "Volume", this.container.playback.src]);
},
onFullscreen: function() {
this.push(["Interaction", "Fullscreen", this.container.playback.src]);
},
push: function(array) {
var res = [this.trackerName + "_trackEvent"].concat(array);
_gaq.push(res);
}
}, {}, ContainerPlugin);
module.exports = GoogleAnalytics;
},{"container_plugin":"container_plugin","events":"events"}],38:[function(require,module,exports){
"use strict";
module.exports = require('./google_analytics');
},{"./google_analytics":37}],39:[function(require,module,exports){
"use strict";
module.exports = require('./log');
},{"./log":40}],40:[function(require,module,exports){
"use strict";
var _ = require('underscore');
require('mousetrap');
var Log = function Log() {
var $__0 = this;
Mousetrap.bind(['ctrl+shift+d'], (function() {
return $__0.onOff();
}));
this.BLACKLIST = ['playback:timeupdate', 'playback:progress', 'container:hover', 'container:timeupdate', 'container:progress'];
};
($traceurRuntime.createClass)(Log, {
info: function(klass, message) {
this.log(klass, 'info', message);
},
warn: function(klass, message) {
this.log(klass, 'warn', message);
},
debug: function(klass, message) {
this.log(klass, 'debug', message);
},
onOff: function() {
window.DEBUG = !window.DEBUG;
if (window.DEBUG) {
console.log('log enabled');
} else {
console.log('log disabled');
}
},
log: function(klass, level, message) {
if (!window.DEBUG || _.contains(this.BLACKLIST, message))
return;
var color;
if (level === 'warn') {
color = '#FF8000';
} else if (level === 'info') {
color = '#006600';
} else if (level === 'error') {
color = '#FF0000';
}
console.log("%c [" + klass + "] [" + level + "] " + message, 'color: ' + color);
}
}, {});
Log.getInstance = function() {
if (this._instance === undefined) {
this._instance = new this();
}
return this._instance;
};
module.exports = Log;
},{"mousetrap":4,"underscore":"underscore"}],41:[function(require,module,exports){
(function (process){
"use strict";
var UIContainerPlugin = require('ui_container_plugin');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var Events = require('events');
var Mediator = require('mediator');
var PlayerInfo = require('player_info');
var $ = require('zepto');
var _ = require('underscore');
var PosterPlugin = function PosterPlugin(options) {
$traceurRuntime.superCall(this, $PosterPlugin.prototype, "constructor", [options]);
this.options = options;
_.defaults(this.options, {disableControlsOnPoster: true});
if (this.options.disableControlsOnPoster) {
this.container.disableMediaControl();
}
this.render();
};
var $PosterPlugin = PosterPlugin;
($traceurRuntime.createClass)(PosterPlugin, {
get name() {
return 'poster';
},
get template() {
return JST.poster;
},
get attributes() {
return {
'class': 'player-poster',
'data-poster': ''
};
},
get events() {
return {'click': 'clicked'};
},
bindEvents: function() {
this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERING, this.onBuffering);
this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERFULL, this.onBufferfull);
this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop);
this.listenTo(this.container, Events.CONTAINER_ENDED, this.onStop);
Mediator.on(Events.PLAYER_RESIZE, this.updateSize, this);
},
stopListening: function() {
$traceurRuntime.superCall(this, $PosterPlugin.prototype, "stopListening", []);
Mediator.off(Events.PLAYER_RESIZE, this.updateSize, this);
},
onBuffering: function() {
this.hidePlayButton();
},
onBufferfull: function() {
this.$el.hide();
if (this.options.disableControlsOnPoster) {
this.container.enableMediaControl();
}
},
onStop: function() {
this.$el.show();
if (this.options.disableControlsOnPoster) {
this.container.disableMediaControl();
}
if (!this.options.hidePlayButton) {
this.showPlayButton();
}
},
hidePlayButton: function() {
this.$playButton.hide();
},
showPlayButton: function() {
this.$playButton.show();
this.updateSize();
},
clicked: function() {
this.container.play();
return false;
},
updateSize: function() {
if (!this.$el)
return;
var height = PlayerInfo.currentSize ? PlayerInfo.currentSize.height : this.$el.height();
this.$el.css({fontSize: height});
if (this.$playWrapper.is(':visible')) {
this.$playWrapper.css({marginTop: -(this.$playWrapper.height() / 2)});
if (!this.options.hidePlayButton) {
this.$playButton.show();
}
} else {
this.$playButton.hide();
}
},
render: function() {
var $__0 = this;
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
this.$playButton = this.$el.find('.poster-icon');
this.$playWrapper = this.$el.find('.play-wrapper');
if (this.options.poster !== undefined) {
var imgEl = $('<img data-poster class="poster-background"></img>');
imgEl.attr('src', this.options.poster);
this.$el.prepend(imgEl);
}
this.container.$el.append(this.el);
if (!!this.options.hidePlayButton) {
this.hidePlayButton();
}
process.nextTick((function() {
return $__0.updateSize();
}));
return this;
}
}, {}, UIContainerPlugin);
module.exports = PosterPlugin;
}).call(this,require('_process'))
},{"../../base/jst":7,"../../base/styler":8,"_process":2,"events":"events","mediator":"mediator","player_info":"player_info","ui_container_plugin":"ui_container_plugin","underscore":"underscore","zepto":"zepto"}],42:[function(require,module,exports){
"use strict";
module.exports = require('./spinner_three_bounce');
},{"./spinner_three_bounce":43}],43:[function(require,module,exports){
"use strict";
var UIContainerPlugin = require('ui_container_plugin');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var Events = require('events');
var SpinnerThreeBouncePlugin = function SpinnerThreeBouncePlugin(options) {
$traceurRuntime.superCall(this, $SpinnerThreeBouncePlugin.prototype, "constructor", [options]);
this.template = JST.spinner_three_bounce;
this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERING, this.onBuffering);
this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERFULL, this.onBufferFull);
this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop);
this.render();
};
var $SpinnerThreeBouncePlugin = SpinnerThreeBouncePlugin;
($traceurRuntime.createClass)(SpinnerThreeBouncePlugin, {
get name() {
return 'spinner';
},
get attributes() {
return {
'data-spinner': '',
'class': 'spinner-three-bounce'
};
},
onBuffering: function() {
this.$el.show();
},
onBufferFull: function() {
this.$el.hide();
},
onStop: function() {
this.$el.hide();
},
render: function() {
this.$el.html(this.template());
var style = Styler.getStyleFor('spinner_three_bounce');
this.container.$el.append(style);
this.container.$el.append(this.$el);
this.$el.hide();
return this;
}
}, {}, UIContainerPlugin);
module.exports = SpinnerThreeBouncePlugin;
},{"../../base/jst":7,"../../base/styler":8,"events":"events","ui_container_plugin":"ui_container_plugin"}],44:[function(require,module,exports){
"use strict";
module.exports = require('./stats');
},{"./stats":45}],45:[function(require,module,exports){
"use strict";
var ContainerPlugin = require('container_plugin');
var $ = require("zepto");
var Events = require('events');
var StatsPlugin = function StatsPlugin(options) {
$traceurRuntime.superCall(this, $StatsPlugin.prototype, "constructor", [options]);
this.setInitialAttrs();
this.reportInterval = options.reportInterval || 5000;
this.state = "IDLE";
};
var $StatsPlugin = StatsPlugin;
($traceurRuntime.createClass)(StatsPlugin, {
get name() {
return 'stats';
},
bindEvents: function() {
this.listenTo(this.container.playback, Events.PLAYBACK_PLAY, this.onPlay);
this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop);
this.listenTo(this.container, Events.CONTAINER_DESTROYED, this.onStop);
this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERING, this.onBuffering);
this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERFULL, this.onBufferFull);
this.listenTo(this.container, Events.CONTAINER_STATS_ADD, this.onStatsAdd);
this.listenTo(this.container, Events.CONTAINER_BITRATE, this.onStatsAdd);
this.listenTo(this.container.playback, Events.PLAYBACK_STATS_ADD, this.onStatsAdd);
},
setInitialAttrs: function() {
this.firstPlay = true;
this.startupTime = 0;
this.rebufferingTime = 0;
this.watchingTime = 0;
this.rebuffers = 0;
this.externalMetrics = {};
},
onPlay: function() {
this.state = "PLAYING";
this.watchingTimeInit = Date.now();
if (!this.intervalId) {
this.intervalId = setInterval(this.report.bind(this), this.reportInterval);
}
},
onStop: function() {
clearInterval(this.intervalId);
this.intervalId = undefined;
this.state = "STOPPED";
},
onBuffering: function() {
if (this.firstPlay) {
this.startupTimeInit = Date.now();
} else {
this.rebufferingTimeInit = Date.now();
}
this.state = "BUFFERING";
this.rebuffers++;
},
onBufferFull: function() {
if (this.firstPlay && !!this.startupTimeInit) {
this.firstPlay = false;
this.startupTime = Date.now() - this.startupTimeInit;
this.watchingTimeInit = Date.now();
} else if (!!this.rebufferingTimeInit) {
this.rebufferingTime += this.getRebufferingTime();
}
this.rebufferingTimeInit = undefined;
this.state = "PLAYING";
},
getRebufferingTime: function() {
return Date.now() - this.rebufferingTimeInit;
},
getWatchingTime: function() {
var totalTime = (Date.now() - this.watchingTimeInit);
return totalTime - this.rebufferingTime;
},
isRebuffering: function() {
return !!this.rebufferingTimeInit;
},
onStatsAdd: function(metric) {
$.extend(this.externalMetrics, metric);
},
getStats: function() {
var metrics = {
startupTime: this.startupTime,
rebuffers: this.rebuffers,
rebufferingTime: this.isRebuffering() ? this.rebufferingTime + this.getRebufferingTime() : this.rebufferingTime,
watchingTime: this.isRebuffering() ? this.getWatchingTime() - this.getRebufferingTime() : this.getWatchingTime()
};
$.extend(metrics, this.externalMetrics);
return metrics;
},
report: function() {
this.container.statsReport(this.getStats());
}
}, {}, ContainerPlugin);
module.exports = StatsPlugin;
},{"container_plugin":"container_plugin","events":"events","zepto":"zepto"}],46:[function(require,module,exports){
"use strict";
module.exports = require('./watermark');
},{"./watermark":47}],47:[function(require,module,exports){
"use strict";
var UIContainerPlugin = require('ui_container_plugin');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var Events = require('events');
var WaterMarkPlugin = function WaterMarkPlugin(options) {
$traceurRuntime.superCall(this, $WaterMarkPlugin.prototype, "constructor", [options]);
this.template = JST[this.name];
this.position = options.position || "bottom-right";
if (options.watermark) {
this.imageUrl = options.watermark;
this.render();
} else {
this.$el.remove();
}
};
var $WaterMarkPlugin = WaterMarkPlugin;
($traceurRuntime.createClass)(WaterMarkPlugin, {
get name() {
return 'watermark';
},
bindEvents: function() {
this.listenTo(this.container, Events.CONTAINER_PLAY, this.onPlay);
this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop);
},
onPlay: function() {
if (!this.hidden)
this.$el.show();
},
onStop: function() {
this.$el.hide();
},
render: function() {
this.$el.hide();
var templateOptions = {
position: this.position,
imageUrl: this.imageUrl
};
this.$el.html(this.template(templateOptions));
var style = Styler.getStyleFor(this.name);
this.container.$el.append(style);
this.container.$el.append(this.$el);
return this;
}
}, {}, UIContainerPlugin);
module.exports = WaterMarkPlugin;
},{"../../base/jst":7,"../../base/styler":8,"events":"events","ui_container_plugin":"ui_container_plugin"}],"base_object":[function(require,module,exports){
"use strict";
var _ = require('underscore');
var extend = require('./utils').extend;
var Events = require('events');
var pluginOptions = ['container'];
var BaseObject = function BaseObject(options) {
this.uniqueId = _.uniqueId('o');
options || (options = {});
_.extend(this, _.pick(options, pluginOptions));
};
($traceurRuntime.createClass)(BaseObject, {}, {}, Events);
BaseObject.extend = extend;
module.exports = BaseObject;
},{"./utils":9,"events":"events","underscore":"underscore"}],"browser":[function(require,module,exports){
"use strict";
var Browser = function Browser() {};
($traceurRuntime.createClass)(Browser, {}, {});
var hasLocalstorage = function() {
try {
localStorage.setItem('clappr', 'clappr');
localStorage.removeItem('clappr');
return true;
} catch (e) {
return false;
}
};
Browser.isSafari = (!!navigator.userAgent.match(/safari/i) && navigator.userAgent.indexOf('Chrome') === -1);
Browser.isChrome = !!(navigator.userAgent.match(/chrome/i));
Browser.isFirefox = !!(navigator.userAgent.match(/firefox/i));
Browser.isLegacyIE = !!(window.ActiveXObject);
Browser.isIE = Browser.isLegacyIE || !!(navigator.userAgent.match(/trident.*rv:1\d/i));
Browser.isIE11 = !!(navigator.userAgent.match(/trident.*rv:11/i));
Browser.isMobile = !!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone|IEMobile|Opera Mini/i.test(navigator.userAgent));
Browser.isWin8App = !!(/MSAppHost/i.test(navigator.userAgent));
Browser.isWiiU = !!(/WiiU/i.test(navigator.userAgent));
Browser.isPS4 = !!(/PlayStation 4/i.test(navigator.userAgent));
Browser.hasLocalstorage = hasLocalstorage();
module.exports = Browser;
},{}],"container_plugin":[function(require,module,exports){
"use strict";
var BaseObject = require('base_object');
var ContainerPlugin = function ContainerPlugin(options) {
$traceurRuntime.superCall(this, $ContainerPlugin.prototype, "constructor", [options]);
this.bindEvents();
};
var $ContainerPlugin = ContainerPlugin;
($traceurRuntime.createClass)(ContainerPlugin, {
enable: function() {
this.bindEvents();
},
disable: function() {
this.stopListening();
},
bindEvents: function() {},
destroy: function() {
this.stopListening();
}
}, {}, BaseObject);
module.exports = ContainerPlugin;
},{"base_object":"base_object"}],"container":[function(require,module,exports){
"use strict";
module.exports = require('./container');
},{"./container":10}],"core_plugin":[function(require,module,exports){
"use strict";
var BaseObject = require('base_object');
var CorePlugin = function CorePlugin(core) {
$traceurRuntime.superCall(this, $CorePlugin.prototype, "constructor", [core]);
this.core = core;
};
var $CorePlugin = CorePlugin;
($traceurRuntime.createClass)(CorePlugin, {
getExternalInterface: function() {
return {};
},
destroy: function() {}
}, {}, BaseObject);
module.exports = CorePlugin;
},{"base_object":"base_object"}],"core":[function(require,module,exports){
"use strict";
module.exports = require('./core');
},{"./core":13}],"events":[function(require,module,exports){
"use strict";
var _ = require('underscore');
var Log = require('../plugins/log').getInstance();
var slice = Array.prototype.slice;
var Events = function Events() {};
($traceurRuntime.createClass)(Events, {
on: function(name, callback, context) {
if (!eventsApi(this, 'on', name, [callback, context]) || !callback)
return this;
this._events || (this._events = {});
var events = this._events[name] || (this._events[name] = []);
events.push({
callback: callback,
context: context,
ctx: context || this
});
return this;
},
once: function(name, callback, context) {
if (!eventsApi(this, 'once', name, [callback, context]) || !callback)
return this;
var self = this;
var once = _.once(function() {
self.off(name, once);
callback.apply(this, arguments);
});
once._callback = callback;
return this.on(name, once, context);
},
off: function(name, callback, context) {
var retain,
ev,
events,
names,
i,
l,
j,
k;
if (!this._events || !eventsApi(this, 'off', name, [callback, context]))
return this;
if (!name && !callback && !context) {
this._events = void 0;
return this;
}
names = name ? [name] : _.keys(this._events);
for (i = 0, l = names.length; i < l; i++) {
name = names[i];
events = this._events[name];
if (events) {
this._events[name] = retain = [];
if (callback || context) {
for (j = 0, k = events.length; j < k; j++) {
ev = events[j];
if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) {
retain.push(ev);
}
}
}
if (!retain.length)
delete this._events[name];
}
}
return this;
},
trigger: function(name) {
var klass = arguments[arguments.length - 1];
Log.info(klass, name);
if (!this._events)
return this;
var args = slice.call(arguments, 1);
if (!eventsApi(this, 'trigger', name, args))
return this;
var events = this._events[name];
var allEvents = this._events.all;
if (events)
triggerEvents(events, args);
if (allEvents)
triggerEvents(allEvents, arguments);
return this;
},
stopListening: function(obj, name, callback) {
var listeningTo = this._listeningTo;
if (!listeningTo)
return this;
var remove = !name && !callback;
if (!callback && typeof name === 'object')
callback = this;
if (obj)
(listeningTo = {})[obj._listenId] = obj;
for (var id in listeningTo) {
obj = listeningTo[id];
obj.off(name, callback, this);
if (remove || _.isEmpty(obj._events))
delete this._listeningTo[id];
}
return this;
}
}, {});
var eventSplitter = /\s+/;
var eventsApi = function(obj, action, name, rest) {
if (!name)
return true;
if (typeof name === 'object') {
for (var key in name) {
obj[action].apply(obj, [key, name[key]].concat(rest));
}
return false;
}
if (eventSplitter.test(name)) {
var names = name.split(eventSplitter);
for (var i = 0,
l = names.length; i < l; i++) {
obj[action].apply(obj, [names[i]].concat(rest));
}
return false;
}
return true;
};
var triggerEvents = function(events, args) {
var ev,
i = -1,
l = events.length,
a1 = args[0],
a2 = args[1],
a3 = args[2];
switch (args.length) {
case 0:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx);
return;
case 1:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx, a1);
return;
case 2:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx, a1, a2);
return;
case 3:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx, a1, a2, a3);
return;
default:
while (++i < l)
(ev = events[i]).callback.apply(ev.ctx, args);
return;
}
};
var listenMethods = {
listenTo: 'on',
listenToOnce: 'once'
};
_.each(listenMethods, function(implementation, method) {
Events.prototype[method] = function(obj, name, callback) {
var listeningTo = this._listeningTo || (this._listeningTo = {});
var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
listeningTo[id] = obj;
if (!callback && typeof name === 'object')
callback = this;
obj[implementation](name, callback, this);
return this;
};
});
Events.PLAYER_RESIZE = 'player:resize';
Events.PLAYBACK_PROGRESS = 'playback:progress';
Events.PLAYBACK_TIMEUPDATE = 'playback:timeupdate';
Events.PLAYBACK_READY = 'playback:ready';
Events.PLAYBACK_BUFFERING = 'playback:buffering';
Events.PLAYBACK_BUFFERFULL = 'playback:bufferfull';
Events.PLAYBACK_SETTINGSUPDATE = 'playback:settingsupdate';
Events.PLAYBACK_LOADEDMETADATA = 'playback:loadedmetadata';
Events.PLAYBACK_HIGHDEFINITIONUPDATE = 'playback:highdefinitionupdate';
Events.PLAYBACK_BITRATE = 'playback:bitrate';
Events.PLAYBACK_PLAYBACKSTATE = 'playback:playbackstate';
Events.PLAYBACK_DVR = 'playback:dvr';
Events.PLAYBACK_MEDIACONTROL_DISABLE = 'playback:mediacontrol:disable';
Events.PLAYBACK_MEDIACONTROL_ENABLE = 'playback:mediacontrol:enable';
Events.PLAYBACK_ENDED = 'playback:ended';
Events.PLAYBACK_PLAY = 'playback:play';
Events.PLAYBACK_ERROR = 'playback:error';
Events.PLAYBACK_STATS_ADD = 'playback:stats:add';
Events.CONTAINER_PLAYBACKSTATE = 'container:playbackstate';
Events.CONTAINER_PLAYBACKDVRSTATECHANGED = 'container:dvr';
Events.CONTAINER_BITRATE = 'container:bitrate';
Events.CONTAINER_STATS_REPORT = 'container:stats:report';
Events.CONTAINER_DESTROYED = 'container:destroyed';
Events.CONTAINER_READY = 'container:ready';
Events.CONTAINER_ERROR = 'container:error';
Events.CONTAINER_LOADEDMETADATA = 'container:loadedmetadata';
Events.CONTAINER_TIMEUPDATE = 'container:timeupdate';
Events.CONTAINER_PROGRESS = 'container:progress';
Events.CONTAINER_PLAY = 'container:play';
Events.CONTAINER_STOP = 'container:stop';
Events.CONTAINER_PAUSE = 'container:pause';
Events.CONTAINER_ENDED = 'container:ended';
Events.CONTAINER_CLICK = 'container:click';
Events.CONTAINER_SEEK = 'container:seek';
Events.CONTAINER_VOLUME = 'container:volume';
Events.CONTAINER_FULLSCREEN = 'container:fullscreen';
Events.CONTAINER_STATE_BUFFERING = 'container:state:buffering';
Events.CONTAINER_STATE_BUFFERFULL = 'container:state:bufferfull';
Events.CONTAINER_SETTINGSUPDATE = 'container:settingsupdate';
Events.CONTAINER_HIGHDEFINITIONUPDATE = 'container:highdefinitionupdate';
Events.CONTAINER_MEDIACONTROL_DISABLE = 'container:mediacontrol:disable';
Events.CONTAINER_MEDIACONTROL_ENABLE = 'container:mediacontrol:enable';
Events.CONTAINER_STATS_ADD = 'container:stats:add';
Events.MEDIACONTROL_RENDERED = 'mediacontrol:rendered';
Events.MEDIACONTROL_FULLSCREEN = 'mediacontrol:fullscreen';
Events.MEDIACONTROL_SHOW = 'mediacontrol:show';
Events.MEDIACONTROL_HIDE = 'mediacontrol:hide';
Events.MEDIACONTROL_MOUSEMOVE_SEEKBAR = 'mediacontrol:mousemove:seekbar';
Events.MEDIACONTROL_MOUSELEAVE_SEEKBAR = 'mediacontrol:mouseleave:seekbar';
Events.MEDIACONTROL_PLAYING = 'mediacontrol:playing';
Events.MEDIACONTROL_NOTPLAYING = 'mediacontrol:notplaying';
Events.MEDIACONTROL_CONTAINERCHANGED = 'mediacontrol:containerchanged';
module.exports = Events;
},{"../plugins/log":39,"underscore":"underscore"}],"flash":[function(require,module,exports){
"use strict";
module.exports = require('./flash');
},{"./flash":24}],"hls":[function(require,module,exports){
"use strict";
module.exports = require('./hls');
},{"./hls":25}],"html5_audio":[function(require,module,exports){
"use strict";
module.exports = require('./html5_audio');
},{"./html5_audio":26}],"html5_video":[function(require,module,exports){
"use strict";
module.exports = require('./html5_video');
},{"./html5_video":27}],"html_img":[function(require,module,exports){
"use strict";
module.exports = require('./html_img');
},{"./html_img":28}],"media_control":[function(require,module,exports){
"use strict";
module.exports = require('./media_control');
},{"./media_control":20}],"mediator":[function(require,module,exports){
"use strict";
var Events = require('events');
var events = new Events();
var Mediator = function Mediator() {};
($traceurRuntime.createClass)(Mediator, {}, {});
Mediator.on = function(name, callback, context) {
events.on(name, callback, context);
return;
};
Mediator.once = function(name, callback, context) {
events.once(name, callback, context);
return;
};
Mediator.off = function(name, callback, context) {
events.off(name, callback, context);
return;
};
Mediator.trigger = function(name, opts) {
events.trigger(name, opts);
return;
};
Mediator.stopListening = function(obj, name, callback) {
events.stopListening(obj, name, callback);
return;
};
module.exports = Mediator;
},{"events":"events"}],"playback":[function(require,module,exports){
"use strict";
var UIObject = require('ui_object');
var Playback = function Playback(options) {
$traceurRuntime.superCall(this, $Playback.prototype, "constructor", [options]);
this.settings = {};
};
var $Playback = Playback;
($traceurRuntime.createClass)(Playback, {
play: function() {},
pause: function() {},
stop: function() {},
seek: function(time) {},
getDuration: function() {
return 0;
},
isPlaying: function() {
return false;
},
getPlaybackType: function() {
return 'no_op';
},
isHighDefinitionInUse: function() {
return false;
},
volume: function(value) {},
destroy: function() {
this.$el.remove();
}
}, {}, UIObject);
Playback.canPlay = (function(source) {
return false;
});
module.exports = Playback;
},{"ui_object":"ui_object"}],"player_info":[function(require,module,exports){
"use strict";
var PlayerInfo = {
options: {},
playbackPlugins: [],
currentSize: {
width: 0,
height: 0
}
};
module.exports = PlayerInfo;
},{}],"poster":[function(require,module,exports){
"use strict";
module.exports = require('./poster');
},{"./poster":41}],"ui_container_plugin":[function(require,module,exports){
"use strict";
var UIObject = require('ui_object');
var UIContainerPlugin = function UIContainerPlugin(options) {
$traceurRuntime.superCall(this, $UIContainerPlugin.prototype, "constructor", [options]);
this.enabled = true;
this.bindEvents();
};
var $UIContainerPlugin = UIContainerPlugin;
($traceurRuntime.createClass)(UIContainerPlugin, {
enable: function() {
this.bindEvents();
this.$el.show();
this.enabled = true;
},
disable: function() {
this.stopListening();
this.$el.hide();
this.enabled = false;
},
bindEvents: function() {},
destroy: function() {
this.remove();
}
}, {}, UIObject);
module.exports = UIContainerPlugin;
},{"ui_object":"ui_object"}],"ui_core_plugin":[function(require,module,exports){
"use strict";
var UIObject = require('ui_object');
var UICorePlugin = function UICorePlugin(core) {
$traceurRuntime.superCall(this, $UICorePlugin.prototype, "constructor", [core]);
this.core = core;
this.enabled = true;
this.bindEvents();
this.render();
};
var $UICorePlugin = UICorePlugin;
($traceurRuntime.createClass)(UICorePlugin, {
bindEvents: function() {},
getExternalInterface: function() {
return {};
},
enable: function() {
this.bindEvents();
this.$el.show();
this.enabled = true;
},
disable: function() {
this.stopListening();
this.$el.hide();
this.enabled = false;
},
destroy: function() {
this.remove();
},
render: function() {
this.$el.html(this.template());
this.$el.append(this.styler.getStyleFor(this.name));
this.core.$el.append(this.el);
return this;
}
}, {}, UIObject);
module.exports = UICorePlugin;
},{"ui_object":"ui_object"}],"ui_object":[function(require,module,exports){
"use strict";
var $ = require('zepto');
var _ = require('underscore');
var extend = require('./utils').extend;
var BaseObject = require('base_object');
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
var UIObject = function UIObject(options) {
$traceurRuntime.superCall(this, $UIObject.prototype, "constructor", [options]);
this.cid = _.uniqueId('c');
this._ensureElement();
this.delegateEvents();
};
var $UIObject = UIObject;
($traceurRuntime.createClass)(UIObject, {
get tagName() {
return 'div';
},
$: function(selector) {
return this.$el.find(selector);
},
render: function() {
return this;
},
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
setElement: function(element, delegate) {
if (this.$el)
this.undelegateEvents();
this.$el = element instanceof $ ? element : $(element);
this.el = this.$el[0];
if (delegate !== false)
this.delegateEvents();
return this;
},
delegateEvents: function(events) {
if (!(events || (events = _.result(this, 'events'))))
return this;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method))
method = this[events[key]];
if (!method)
continue;
var match = key.match(delegateEventSplitter);
var eventName = match[1],
selector = match[2];
method = _.bind(method, this);
eventName += '.delegateEvents' + this.cid;
if (selector === '') {
this.$el.on(eventName, method);
} else {
this.$el.on(eventName, selector, method);
}
}
return this;
},
undelegateEvents: function() {
this.$el.off('.delegateEvents' + this.cid);
return this;
},
_ensureElement: function() {
if (!this.el) {
var attrs = _.extend({}, _.result(this, 'attributes'));
if (this.id)
attrs.id = _.result(this, 'id');
if (this.className)
attrs['class'] = _.result(this, 'className');
var $el = $('<' + _.result(this, 'tagName') + '>').attr(attrs);
this.setElement($el, false);
} else {
this.setElement(_.result(this, 'el'), false);
}
}
}, {}, BaseObject);
UIObject.extend = extend;
module.exports = UIObject;
},{"./utils":9,"base_object":"base_object","underscore":"underscore","zepto":"zepto"}],"underscore":[function(require,module,exports){
// Underscore.js 1.7.0
// http://underscorejs.org
// (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var
push = ArrayProto.push,
slice = ArrayProto.slice,
concat = ArrayProto.concat,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.7.0';
// Internal function that returns an efficient (for current engines) version
// of the passed-in callback, to be repeatedly applied in other Underscore
// functions.
var createCallback = function(func, context, argCount) {
if (context === void 0) return func;
switch (argCount == null ? 3 : argCount) {
case 1: return function(value) {
return func.call(context, value);
};
case 2: return function(value, other) {
return func.call(context, value, other);
};
case 3: return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
};
// A mostly-internal function to generate callbacks that can be applied
// to each element in a collection, returning the desired result — either
// identity, an arbitrary callback, a property matcher, or a property accessor.
_.iteratee = function(value, context, argCount) {
if (value == null) return _.identity;
if (_.isFunction(value)) return createCallback(value, context, argCount);
if (_.isObject(value)) return _.matches(value);
return _.property(value);
};
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles raw objects in addition to array-likes. Treats all
// sparse array-likes as if they were dense.
_.each = _.forEach = function(obj, iteratee, context) {
if (obj == null) return obj;
iteratee = createCallback(iteratee, context);
var i, length = obj.length;
if (length === +length) {
for (i = 0; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
// Return the results of applying the iteratee to each element.
_.map = _.collect = function(obj, iteratee, context) {
if (obj == null) return [];
iteratee = _.iteratee(iteratee, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
results = Array(length),
currentKey;
for (var index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
results[index] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
var reduceError = 'Reduce of empty array with no initial value';
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`.
_.reduce = _.foldl = _.inject = function(obj, iteratee, memo, context) {
if (obj == null) obj = [];
iteratee = createCallback(iteratee, context, 4);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
index = 0, currentKey;
if (arguments.length < 3) {
if (!length) throw new TypeError(reduceError);
memo = obj[keys ? keys[index++] : index++];
}
for (; index < length; index++) {
currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
_.reduceRight = _.foldr = function(obj, iteratee, memo, context) {
if (obj == null) obj = [];
iteratee = createCallback(iteratee, context, 4);
var keys = obj.length !== + obj.length && _.keys(obj),
index = (keys || obj).length,
currentKey;
if (arguments.length < 3) {
if (!index) throw new TypeError(reduceError);
memo = obj[keys ? keys[--index] : --index];
}
while (index--) {
currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, predicate, context) {
var result;
predicate = _.iteratee(predicate, context);
_.some(obj, function(value, index, list) {
if (predicate(value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Aliased as `select`.
_.filter = _.select = function(obj, predicate, context) {
var results = [];
if (obj == null) return results;
predicate = _.iteratee(predicate, context);
_.each(obj, function(value, index, list) {
if (predicate(value, index, list)) results.push(value);
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, predicate, context) {
return _.filter(obj, _.negate(_.iteratee(predicate)), context);
};
// Determine whether all of the elements match a truth test.
// Aliased as `all`.
_.every = _.all = function(obj, predicate, context) {
if (obj == null) return true;
predicate = _.iteratee(predicate, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
index, currentKey;
for (index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
if (!predicate(obj[currentKey], currentKey, obj)) return false;
}
return true;
};
// Determine if at least one element in the object matches a truth test.
// Aliased as `any`.
_.some = _.any = function(obj, predicate, context) {
if (obj == null) return false;
predicate = _.iteratee(predicate, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
index, currentKey;
for (index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
if (predicate(obj[currentKey], currentKey, obj)) return true;
}
return false;
};
// Determine if the array or object contains a given value (using `===`).
// Aliased as `include`.
_.contains = _.include = function(obj, target) {
if (obj == null) return false;
if (obj.length !== +obj.length) obj = _.values(obj);
return _.indexOf(obj, target) >= 0;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
return (isFunc ? method : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, _.property(key));
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs) {
return _.filter(obj, _.matches(attrs));
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.find(obj, _.matches(attrs));
};
// Return the maximum element (or element-based computation).
_.max = function(obj, iteratee, context) {
var result = -Infinity, lastComputed = -Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = obj.length === +obj.length ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value > result) {
result = value;
}
}
} else {
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iteratee, context) {
var result = Infinity, lastComputed = Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = obj.length === +obj.length ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value < result) {
result = value;
}
}
} else {
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed < lastComputed || computed === Infinity && result === Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Shuffle a collection, using the modern version of the
// [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
_.shuffle = function(obj) {
var set = obj && obj.length === +obj.length ? obj : _.values(obj);
var length = set.length;
var shuffled = Array(length);
for (var index = 0, rand; index < length; index++) {
rand = _.random(0, index);
if (rand !== index) shuffled[index] = shuffled[rand];
shuffled[rand] = set[index];
}
return shuffled;
};
// Sample **n** random values from a collection.
// If **n** is not specified, returns a single random element.
// The internal `guard` argument allows it to work with `map`.
_.sample = function(obj, n, guard) {
if (n == null || guard) {
if (obj.length !== +obj.length) obj = _.values(obj);
return obj[_.random(obj.length - 1)];
}
return _.shuffle(obj).slice(0, Math.max(0, n));
};
// Sort the object's values by a criterion produced by an iteratee.
_.sortBy = function(obj, iteratee, context) {
iteratee = _.iteratee(iteratee, context);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value: value,
index: index,
criteria: iteratee(value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index - right.index;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(behavior) {
return function(obj, iteratee, context) {
var result = {};
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index) {
var key = iteratee(value, index, obj);
behavior(result, value, key);
});
return result;
};
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = group(function(result, value, key) {
if (_.has(result, key)) result[key].push(value); else result[key] = [value];
});
// Indexes the object's values by a criterion, similar to `groupBy`, but for
// when you know that your index values will be unique.
_.indexBy = group(function(result, value, key) {
result[key] = value;
});
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = group(function(result, value, key) {
if (_.has(result, key)) result[key]++; else result[key] = 1;
});
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iteratee, context) {
iteratee = _.iteratee(iteratee, context, 1);
var value = iteratee(obj);
var low = 0, high = array.length;
while (low < high) {
var mid = low + high >>> 1;
if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
}
return low;
};
// Safely create a real, live array from anything iterable.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (obj.length === +obj.length) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return obj.length === +obj.length ? obj.length : _.keys(obj).length;
};
// Split a collection into two arrays: one whose elements all satisfy the given
// predicate, and one whose elements all do not satisfy the predicate.
_.partition = function(obj, predicate, context) {
predicate = _.iteratee(predicate, context);
var pass = [], fail = [];
_.each(obj, function(value, key, obj) {
(predicate(value, key, obj) ? pass : fail).push(value);
});
return [pass, fail];
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[0];
if (n < 0) return [];
return slice.call(array, 0, n);
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N. The **guard** check allows it to work with
// `_.map`.
_.initial = function(array, n, guard) {
return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[array.length - 1];
return slice.call(array, Math.max(array.length - n, 0));
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, n == null || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, strict, output) {
if (shallow && _.every(input, _.isArray)) {
return concat.apply(output, input);
}
for (var i = 0, length = input.length; i < length; i++) {
var value = input[i];
if (!_.isArray(value) && !_.isArguments(value)) {
if (!strict) output.push(value);
} else if (shallow) {
push.apply(output, value);
} else {
flatten(value, shallow, strict, output);
}
}
return output;
};
// Flatten out an array, either recursively (by default), or just one level.
_.flatten = function(array, shallow) {
return flatten(array, shallow, false, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iteratee, context) {
if (array == null) return [];
if (!_.isBoolean(isSorted)) {
context = iteratee;
iteratee = isSorted;
isSorted = false;
}
if (iteratee != null) iteratee = _.iteratee(iteratee, context);
var result = [];
var seen = [];
for (var i = 0, length = array.length; i < length; i++) {
var value = array[i];
if (isSorted) {
if (!i || seen !== value) result.push(value);
seen = value;
} else if (iteratee) {
var computed = iteratee(value, i, array);
if (_.indexOf(seen, computed) < 0) {
seen.push(computed);
result.push(value);
}
} else if (_.indexOf(result, value) < 0) {
result.push(value);
}
}
return result;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(flatten(arguments, true, true, []));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
if (array == null) return [];
var result = [];
var argsLength = arguments.length;
for (var i = 0, length = array.length; i < length; i++) {
var item = array[i];
if (_.contains(result, item)) continue;
for (var j = 1; j < argsLength; j++) {
if (!_.contains(arguments[j], item)) break;
}
if (j === argsLength) result.push(item);
}
return result;
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = flatten(slice.call(arguments, 1), true, true, []);
return _.filter(array, function(value){
return !_.contains(rest, value);
});
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function(array) {
if (array == null) return [];
var length = _.max(arguments, 'length').length;
var results = Array(length);
for (var i = 0; i < length; i++) {
results[i] = _.pluck(arguments, i);
}
return results;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
if (list == null) return {};
var result = {};
for (var i = 0, length = list.length; i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// Return the position of the first occurrence of an item in an array,
// or -1 if the item is not included in the array.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, length = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted;
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
for (; i < length; i++) if (array[i] === item) return i;
return -1;
};
_.lastIndexOf = function(array, item, from) {
if (array == null) return -1;
var idx = array.length;
if (typeof from == 'number') {
idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1);
}
while (--idx >= 0) if (array[idx] === item) return idx;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = step || 1;
var length = Math.max(Math.ceil((stop - start) / step), 0);
var range = Array(length);
for (var idx = 0; idx < length; idx++, start += step) {
range[idx] = start;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Reusable constructor function for prototype setting.
var Ctor = function(){};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
_.bind = function(func, context) {
var args, bound;
if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
args = slice.call(arguments, 2);
bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
Ctor.prototype = func.prototype;
var self = new Ctor;
Ctor.prototype = null;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (_.isObject(result)) return result;
return self;
};
return bound;
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context. _ acts
// as a placeholder, allowing any combination of arguments to be pre-filled.
_.partial = function(func) {
var boundArgs = slice.call(arguments, 1);
return function() {
var position = 0;
var args = boundArgs.slice();
for (var i = 0, length = args.length; i < length; i++) {
if (args[i] === _) args[i] = arguments[position++];
}
while (position < arguments.length) args.push(arguments[position++]);
return func.apply(this, args);
};
};
// Bind a number of an object's methods to that object. Remaining arguments
// are the method names to be bound. Useful for ensuring that all callbacks
// defined on an object belong to it.
_.bindAll = function(obj) {
var i, length = arguments.length, key;
if (length <= 1) throw new Error('bindAll must be passed function names');
for (i = 1; i < length; i++) {
key = arguments[i];
obj[key] = _.bind(obj[key], obj);
}
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memoize = function(key) {
var cache = memoize.cache;
var address = hasher ? hasher.apply(this, arguments) : key;
if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
return cache[address];
};
memoize.cache = {};
return memoize;
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){
return func.apply(null, args);
}, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
_.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = _.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function() {
var last = _.now() - timestamp;
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = _.now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return _.partial(wrapper, func);
};
// Returns a negated version of the passed-in predicate.
_.negate = function(predicate) {
return function() {
return !predicate.apply(this, arguments);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var args = arguments;
var start = args.length - 1;
return function() {
var i = start;
var result = args[start].apply(this, arguments);
while (i--) result = args[i].call(this, result);
return result;
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Returns a function that will only be executed before being called N times.
_.before = function(times, func) {
var memo;
return function() {
if (--times > 0) {
memo = func.apply(this, arguments);
} else {
func = null;
}
return memo;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = _.partial(_.before, 2);
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = function(obj) {
if (!_.isObject(obj)) return [];
if (nativeKeys) return nativeKeys(obj);
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys.push(key);
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var values = Array(length);
for (var i = 0; i < length; i++) {
values[i] = obj[keys[i]];
}
return values;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var pairs = Array(length);
for (var i = 0; i < length; i++) {
pairs[i] = [keys[i], obj[keys[i]]];
}
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
var keys = _.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
result[obj[keys[i]]] = keys[i];
}
return result;
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
if (!_.isObject(obj)) return obj;
var source, prop;
for (var i = 1, length = arguments.length; i < length; i++) {
source = arguments[i];
for (prop in source) {
if (hasOwnProperty.call(source, prop)) {
obj[prop] = source[prop];
}
}
}
return obj;
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(obj, iteratee, context) {
var result = {}, key;
if (obj == null) return result;
if (_.isFunction(iteratee)) {
iteratee = createCallback(iteratee, context);
for (key in obj) {
var value = obj[key];
if (iteratee(value, key, obj)) result[key] = value;
}
} else {
var keys = concat.apply([], slice.call(arguments, 1));
obj = new Object(obj);
for (var i = 0, length = keys.length; i < length; i++) {
key = keys[i];
if (key in obj) result[key] = obj[key];
}
}
return result;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj, iteratee, context) {
if (_.isFunction(iteratee)) {
iteratee = _.negate(iteratee);
} else {
var keys = _.map(concat.apply([], slice.call(arguments, 1)), String);
iteratee = function(value, key) {
return !_.contains(keys, key);
};
}
return _.pick(obj, iteratee, context);
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
if (!_.isObject(obj)) return obj;
for (var i = 1, length = arguments.length; i < length; i++) {
var source = arguments[i];
for (var prop in source) {
if (obj[prop] === void 0) obj[prop] = source[prop];
}
}
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
if (a === b) return a !== 0 || 1 / a === 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className !== toString.call(b)) return false;
switch (className) {
// Strings, numbers, regular expressions, dates, and booleans are compared by value.
case '[object RegExp]':
// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return '' + a === '' + b;
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive.
// Object(NaN) is equivalent to NaN
if (+a !== +a) return +b !== +b;
// An `egal` comparison is performed for other numeric values.
return +a === 0 ? 1 / +a === 1 / b : +a === +b;
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a === +b;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] === a) return bStack[length] === b;
}
// Objects with different constructors are not equivalent, but `Object`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (
aCtor !== bCtor &&
// Handle Object.create(x) cases
'constructor' in a && 'constructor' in b &&
!(_.isFunction(aCtor) && aCtor instanceof aCtor &&
_.isFunction(bCtor) && bCtor instanceof bCtor)
) {
return false;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
var size, result;
// Recursively compare objects and arrays.
if (className === '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size === b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
if (!(result = eq(a[size], b[size], aStack, bStack))) break;
}
}
} else {
// Deep compare objects.
var keys = _.keys(a), key;
size = keys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
result = _.keys(b).length === size;
if (result) {
while (size--) {
// Deep compare each member
key = keys[size];
if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
}
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return result;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b, [], []);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (_.isArray(obj) || _.isString(obj) || _.isArguments(obj)) return obj.length === 0;
for (var key in obj) if (_.has(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
_.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) === '[object ' + name + ']';
};
});
// Define a fallback version of the method in browsers (ahem, IE), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return _.has(obj, 'callee');
};
}
// Optimize `isFunction` if appropriate. Work around an IE 11 bug.
if (typeof /./ !== 'function') {
_.isFunction = function(obj) {
return typeof obj == 'function' || false;
};
}
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj !== +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return obj != null && hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iteratees.
_.identity = function(value) {
return value;
};
_.constant = function(value) {
return function() {
return value;
};
};
_.noop = function(){};
_.property = function(key) {
return function(obj) {
return obj[key];
};
};
// Returns a predicate for checking whether an object has a given set of `key:value` pairs.
_.matches = function(attrs) {
var pairs = _.pairs(attrs), length = pairs.length;
return function(obj) {
if (obj == null) return !length;
obj = new Object(obj);
for (var i = 0; i < length; i++) {
var pair = pairs[i], key = pair[0];
if (pair[1] !== obj[key] || !(key in obj)) return false;
}
return true;
};
};
// Run a function **n** times.
_.times = function(n, iteratee, context) {
var accum = Array(Math.max(0, n));
iteratee = createCallback(iteratee, context, 1);
for (var i = 0; i < n; i++) accum[i] = iteratee(i);
return accum;
};
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
// A (possibly faster) way to get the current timestamp as an integer.
_.now = Date.now || function() {
return new Date().getTime();
};
// List of HTML entities for escaping.
var escapeMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'`': '`'
};
var unescapeMap = _.invert(escapeMap);
// Functions for escaping and unescaping strings to/from HTML interpolation.
var createEscaper = function(map) {
var escaper = function(match) {
return map[match];
};
// Regexes for identifying a key that needs to be escaped
var source = '(?:' + _.keys(map).join('|') + ')';
var testRegexp = RegExp(source);
var replaceRegexp = RegExp(source, 'g');
return function(string) {
string = string == null ? '' : '' + string;
return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
};
};
_.escape = createEscaper(escapeMap);
_.unescape = createEscaper(unescapeMap);
// If the value of the named `property` is a function then invoke it with the
// `object` as context; otherwise, return it.
_.result = function(object, property) {
if (object == null) return void 0;
var value = object[property];
return _.isFunction(value) ? object[property]() : value;
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
var escapeChar = function(match) {
return '\\' + escapes[match];
};
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
// NB: `oldSettings` only exists for backwards compatibility.
_.template = function(text, settings, oldSettings) {
if (!settings && oldSettings) settings = oldSettings;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset).replace(escaper, escapeChar);
index = offset + match.length;
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
} else if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
} else if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
// Adobe VMs need the match returned to produce the correct offest.
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + 'return __p;\n';
try {
var render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled source as a convenience for precompilation.
var argument = settings.variable || 'obj';
template.source = 'function(' + argument + '){\n' + source + '}';
return template;
};
// Add a "chain" function. Start chaining a wrapped Underscore object.
_.chain = function(obj) {
var instance = _(obj);
instance._chain = true;
return instance;
};
// OOP
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
// Helper function to continue chaining intermediate results.
var result = function(obj) {
return this._chain ? _(obj).chain() : obj;
};
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
_.each(_.functions(obj), function(name) {
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return result.call(this, func.apply(_, args));
};
});
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
_.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
var obj = this._wrapped;
method.apply(obj, arguments);
if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
return result.call(this, obj);
};
});
// Add all accessor Array functions to the wrapper.
_.each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
return result.call(this, method.apply(this._wrapped, arguments));
};
});
// Extracts the result from a wrapped and chained object.
_.prototype.value = function() {
return this._wrapped;
};
// AMD registration happens at the end for compatibility with AMD loaders
// that may not enforce next-turn semantics on modules. Even though general
// practice for AMD registration is to be anonymous, underscore registers
// as a named module because, like jQuery, it is a base library that is
// popular enough to be bundled in a third party lib, but not be part of
// an AMD load request. Those cases could generate an error when an
// anonymous define() is called outside of a loader request.
if (typeof define === 'function' && define.amd) {
define('underscore', [], function() {
return _;
});
}
}.call(this));
},{}],"zepto":[function(require,module,exports){
/* Zepto v1.1.4-76-g2bd5d7a - zepto event ajax callbacks deferred touch selector - zeptojs.com/license */
var Zepto=function(){function D(t){return null==t?String(t):j[S.call(t)]||"object"}function L(t){return"function"==D(t)}function k(t){return null!=t&&t==t.window}function Z(t){return null!=t&&t.nodeType==t.DOCUMENT_NODE}function $(t){return"object"==D(t)}function F(t){return $(t)&&!k(t)&&Object.getPrototypeOf(t)==Object.prototype}function R(t){return"number"==typeof t.length}function q(t){return s.call(t,function(t){return null!=t})}function W(t){return t.length>0?n.fn.concat.apply([],t):t}function z(t){return t.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function H(t){return t in c?c[t]:c[t]=new RegExp("(^|\\s)"+t+"(\\s|$)")}function _(t,e){return"number"!=typeof e||l[z(t)]?e:e+"px"}function I(t){var e,n;return f[t]||(e=u.createElement(t),u.body.appendChild(e),n=getComputedStyle(e,"").getPropertyValue("display"),e.parentNode.removeChild(e),"none"==n&&(n="block"),f[t]=n),f[t]}function U(t){return"children"in t?a.call(t.children):n.map(t.childNodes,function(t){return 1==t.nodeType?t:void 0})}function X(t,e){var n,i=t?t.length:0;for(n=0;i>n;n++)this[n]=t[n];this.length=i,this.selector=e||""}function B(n,i,r){for(e in i)r&&(F(i[e])||A(i[e]))?(F(i[e])&&!F(n[e])&&(n[e]={}),A(i[e])&&!A(n[e])&&(n[e]=[]),B(n[e],i[e],r)):i[e]!==t&&(n[e]=i[e])}function V(t,e){return null==e?n(t):n(t).filter(e)}function Y(t,e,n,i){return L(e)?e.call(t,n,i):e}function J(t,e,n){null==n?t.removeAttribute(e):t.setAttribute(e,n)}function G(e,n){var i=e.className||"",r=i&&i.baseVal!==t;return n===t?r?i.baseVal:i:void(r?i.baseVal=n:e.className=n)}function K(t){try{return t?"true"==t||("false"==t?!1:"null"==t?null:+t+""==t?+t:/^[\[\{]/.test(t)?n.parseJSON(t):t):t}catch(e){return t}}function Q(t,e){e(t);for(var n=0,i=t.childNodes.length;i>n;n++)Q(t.childNodes[n],e)}var t,e,n,i,N,P,r=[],o=r.concat,s=r.filter,a=r.slice,u=window.document,f={},c={},l={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},h=/^\s*<(\w+|!)[^>]*>/,p=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,d=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,m=/^(?:body|html)$/i,g=/([A-Z])/g,v=["val","css","html","text","data","width","height","offset"],y=["after","prepend","before","append"],w=u.createElement("table"),x=u.createElement("tr"),b={tr:u.createElement("tbody"),tbody:w,thead:w,tfoot:w,td:x,th:x,"*":u.createElement("div")},E=/complete|loaded|interactive/,T=/^[\w-]*$/,j={},S=j.toString,C={},O=u.createElement("div"),M={tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},A=Array.isArray||function(t){return t instanceof Array};return C.matches=function(t,e){if(!e||!t||1!==t.nodeType)return!1;var n=t.webkitMatchesSelector||t.mozMatchesSelector||t.oMatchesSelector||t.matchesSelector;if(n)return n.call(t,e);var i,r=t.parentNode,o=!r;return o&&(r=O).appendChild(t),i=~C.qsa(r,e).indexOf(t),o&&O.removeChild(t),i},N=function(t){return t.replace(/-+(.)?/g,function(t,e){return e?e.toUpperCase():""})},P=function(t){return s.call(t,function(e,n){return t.indexOf(e)==n})},C.fragment=function(e,i,r){var o,s,f;return p.test(e)&&(o=n(u.createElement(RegExp.$1))),o||(e.replace&&(e=e.replace(d,"<$1></$2>")),i===t&&(i=h.test(e)&&RegExp.$1),i in b||(i="*"),f=b[i],f.innerHTML=""+e,o=n.each(a.call(f.childNodes),function(){f.removeChild(this)})),F(r)&&(s=n(o),n.each(r,function(t,e){v.indexOf(t)>-1?s[t](e):s.attr(t,e)})),o},C.Z=function(t,e){return new X(t,e)},C.isZ=function(t){return t instanceof C.Z},C.init=function(e,i){var r;if(!e)return C.Z();if("string"==typeof e)if(e=e.trim(),"<"==e[0]&&h.test(e))r=C.fragment(e,RegExp.$1,i),e=null;else{if(i!==t)return n(i).find(e);r=C.qsa(u,e)}else{if(L(e))return n(u).ready(e);if(C.isZ(e))return e;if(A(e))r=q(e);else if($(e))r=[e],e=null;else if(h.test(e))r=C.fragment(e.trim(),RegExp.$1,i),e=null;else{if(i!==t)return n(i).find(e);r=C.qsa(u,e)}}return C.Z(r,e)},n=function(t,e){return C.init(t,e)},n.extend=function(t){var e,n=a.call(arguments,1);return"boolean"==typeof t&&(e=t,t=n.shift()),n.forEach(function(n){B(t,n,e)}),t},C.qsa=function(t,e){var n,i="#"==e[0],r=!i&&"."==e[0],o=i||r?e.slice(1):e,s=T.test(o);return t.getElementById&&s&&i?(n=t.getElementById(o))?[n]:[]:1!==t.nodeType&&9!==t.nodeType&&11!==t.nodeType?[]:a.call(s&&!i&&t.getElementsByClassName?r?t.getElementsByClassName(o):t.getElementsByTagName(e):t.querySelectorAll(e))},n.contains=u.documentElement.contains?function(t,e){return t!==e&&t.contains(e)}:function(t,e){for(;e&&(e=e.parentNode);)if(e===t)return!0;return!1},n.type=D,n.isFunction=L,n.isWindow=k,n.isArray=A,n.isPlainObject=F,n.isEmptyObject=function(t){var e;for(e in t)return!1;return!0},n.inArray=function(t,e,n){return r.indexOf.call(e,t,n)},n.camelCase=N,n.trim=function(t){return null==t?"":String.prototype.trim.call(t)},n.uuid=0,n.support={},n.expr={},n.noop=function(){},n.map=function(t,e){var n,r,o,i=[];if(R(t))for(r=0;r<t.length;r++)n=e(t[r],r),null!=n&&i.push(n);else for(o in t)n=e(t[o],o),null!=n&&i.push(n);return W(i)},n.each=function(t,e){var n,i;if(R(t)){for(n=0;n<t.length;n++)if(e.call(t[n],n,t[n])===!1)return t}else for(i in t)if(e.call(t[i],i,t[i])===!1)return t;return t},n.grep=function(t,e){return s.call(t,e)},window.JSON&&(n.parseJSON=JSON.parse),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(t,e){j["[object "+e+"]"]=e.toLowerCase()}),n.fn={constructor:C.Z,length:0,forEach:r.forEach,reduce:r.reduce,push:r.push,sort:r.sort,splice:r.splice,indexOf:r.indexOf,concat:function(){var t,e,n=[];for(t=0;t<arguments.length;t++)e=arguments[t],n[t]=C.isZ(e)?e.toArray():e;return o.apply(C.isZ(this)?this.toArray():this,n)},map:function(t){return n(n.map(this,function(e,n){return t.call(e,n,e)}))},slice:function(){return n(a.apply(this,arguments))},ready:function(t){return E.test(u.readyState)&&u.body?t(n):u.addEventListener("DOMContentLoaded",function(){t(n)},!1),this},get:function(e){return e===t?a.call(this):this[e>=0?e:e+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){null!=this.parentNode&&this.parentNode.removeChild(this)})},each:function(t){return r.every.call(this,function(e,n){return t.call(e,n,e)!==!1}),this},filter:function(t){return L(t)?this.not(this.not(t)):n(s.call(this,function(e){return C.matches(e,t)}))},add:function(t,e){return n(P(this.concat(n(t,e))))},is:function(t){return this.length>0&&C.matches(this[0],t)},not:function(e){var i=[];if(L(e)&&e.call!==t)this.each(function(t){e.call(this,t)||i.push(this)});else{var r="string"==typeof e?this.filter(e):R(e)&&L(e.item)?a.call(e):n(e);this.forEach(function(t){r.indexOf(t)<0&&i.push(t)})}return n(i)},has:function(t){return this.filter(function(){return $(t)?n.contains(this,t):n(this).find(t).size()})},eq:function(t){return-1===t?this.slice(t):this.slice(t,+t+1)},first:function(){var t=this[0];return t&&!$(t)?t:n(t)},last:function(){var t=this[this.length-1];return t&&!$(t)?t:n(t)},find:function(t){var e,i=this;return e=t?"object"==typeof t?n(t).filter(function(){var t=this;return r.some.call(i,function(e){return n.contains(e,t)})}):1==this.length?n(C.qsa(this[0],t)):this.map(function(){return C.qsa(this,t)}):n()},closest:function(t,e){var i=this[0],r=!1;for("object"==typeof t&&(r=n(t));i&&!(r?r.indexOf(i)>=0:C.matches(i,t));)i=i!==e&&!Z(i)&&i.parentNode;return n(i)},parents:function(t){for(var e=[],i=this;i.length>0;)i=n.map(i,function(t){return(t=t.parentNode)&&!Z(t)&&e.indexOf(t)<0?(e.push(t),t):void 0});return V(e,t)},parent:function(t){return V(P(this.pluck("parentNode")),t)},children:function(t){return V(this.map(function(){return U(this)}),t)},contents:function(){return this.map(function(){return this.contentDocument||a.call(this.childNodes)})},siblings:function(t){return V(this.map(function(t,e){return s.call(U(e.parentNode),function(t){return t!==e})}),t)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(t){return n.map(this,function(e){return e[t]})},show:function(){return this.each(function(){"none"==this.style.display&&(this.style.display=""),"none"==getComputedStyle(this,"").getPropertyValue("display")&&(this.style.display=I(this.nodeName))})},replaceWith:function(t){return this.before(t).remove()},wrap:function(t){var e=L(t);if(this[0]&&!e)var i=n(t).get(0),r=i.parentNode||this.length>1;return this.each(function(o){n(this).wrapAll(e?t.call(this,o):r?i.cloneNode(!0):i)})},wrapAll:function(t){if(this[0]){n(this[0]).before(t=n(t));for(var e;(e=t.children()).length;)t=e.first();n(t).append(this)}return this},wrapInner:function(t){var e=L(t);return this.each(function(i){var r=n(this),o=r.contents(),s=e?t.call(this,i):t;o.length?o.wrapAll(s):r.append(s)})},unwrap:function(){return this.parent().each(function(){n(this).replaceWith(n(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(e){return this.each(function(){var i=n(this);(e===t?"none"==i.css("display"):e)?i.show():i.hide()})},prev:function(t){return n(this.pluck("previousElementSibling")).filter(t||"*")},next:function(t){return n(this.pluck("nextElementSibling")).filter(t||"*")},html:function(t){return 0 in arguments?this.each(function(e){var i=this.innerHTML;n(this).empty().append(Y(this,t,e,i))}):0 in this?this[0].innerHTML:null},text:function(t){return 0 in arguments?this.each(function(e){var n=Y(this,t,e,this.textContent);this.textContent=null==n?"":""+n}):0 in this?this[0].textContent:null},attr:function(n,i){var r;return"string"!=typeof n||1 in arguments?this.each(function(t){if(1===this.nodeType)if($(n))for(e in n)J(this,e,n[e]);else J(this,n,Y(this,i,t,this.getAttribute(n)))}):this.length&&1===this[0].nodeType?!(r=this[0].getAttribute(n))&&n in this[0]?this[0][n]:r:t},removeAttr:function(t){return this.each(function(){1===this.nodeType&&t.split(" ").forEach(function(t){J(this,t)},this)})},prop:function(t,e){return t=M[t]||t,1 in arguments?this.each(function(n){this[t]=Y(this,e,n,this[t])}):this[0]&&this[0][t]},data:function(e,n){var i="data-"+e.replace(g,"-$1").toLowerCase(),r=1 in arguments?this.attr(i,n):this.attr(i);return null!==r?K(r):t},val:function(t){return 0 in arguments?this.each(function(e){this.value=Y(this,t,e,this.value)}):this[0]&&(this[0].multiple?n(this[0]).find("option").filter(function(){return this.selected}).pluck("value"):this[0].value)},offset:function(t){if(t)return this.each(function(e){var i=n(this),r=Y(this,t,e,i.offset()),o=i.offsetParent().offset(),s={top:r.top-o.top,left:r.left-o.left};"static"==i.css("position")&&(s.position="relative"),i.css(s)});if(!this.length)return null;var e=this[0].getBoundingClientRect();return{left:e.left+window.pageXOffset,top:e.top+window.pageYOffset,width:Math.round(e.width),height:Math.round(e.height)}},css:function(t,i){if(arguments.length<2){var r,o=this[0];if(!o)return;if(r=getComputedStyle(o,""),"string"==typeof t)return o.style[N(t)]||r.getPropertyValue(t);if(A(t)){var s={};return n.each(t,function(t,e){s[e]=o.style[N(e)]||r.getPropertyValue(e)}),s}}var a="";if("string"==D(t))i||0===i?a=z(t)+":"+_(t,i):this.each(function(){this.style.removeProperty(z(t))});else for(e in t)t[e]||0===t[e]?a+=z(e)+":"+_(e,t[e])+";":this.each(function(){this.style.removeProperty(z(e))});return this.each(function(){this.style.cssText+=";"+a})},index:function(t){return t?this.indexOf(n(t)[0]):this.parent().children().indexOf(this[0])},hasClass:function(t){return t?r.some.call(this,function(t){return this.test(G(t))},H(t)):!1},addClass:function(t){return t?this.each(function(e){if("className"in this){i=[];var r=G(this),o=Y(this,t,e,r);o.split(/\s+/g).forEach(function(t){n(this).hasClass(t)||i.push(t)},this),i.length&&G(this,r+(r?" ":"")+i.join(" "))}}):this},removeClass:function(e){return this.each(function(n){if("className"in this){if(e===t)return G(this,"");i=G(this),Y(this,e,n,i).split(/\s+/g).forEach(function(t){i=i.replace(H(t)," ")}),G(this,i.trim())}})},toggleClass:function(e,i){return e?this.each(function(r){var o=n(this),s=Y(this,e,r,G(this));s.split(/\s+/g).forEach(function(e){(i===t?!o.hasClass(e):i)?o.addClass(e):o.removeClass(e)})}):this},scrollTop:function(e){if(this.length){var n="scrollTop"in this[0];return e===t?n?this[0].scrollTop:this[0].pageYOffset:this.each(n?function(){this.scrollTop=e}:function(){this.scrollTo(this.scrollX,e)})}},scrollLeft:function(e){if(this.length){var n="scrollLeft"in this[0];return e===t?n?this[0].scrollLeft:this[0].pageXOffset:this.each(n?function(){this.scrollLeft=e}:function(){this.scrollTo(e,this.scrollY)})}},position:function(){if(this.length){var t=this[0],e=this.offsetParent(),i=this.offset(),r=m.test(e[0].nodeName)?{top:0,left:0}:e.offset();return i.top-=parseFloat(n(t).css("margin-top"))||0,i.left-=parseFloat(n(t).css("margin-left"))||0,r.top+=parseFloat(n(e[0]).css("border-top-width"))||0,r.left+=parseFloat(n(e[0]).css("border-left-width"))||0,{top:i.top-r.top,left:i.left-r.left}}},offsetParent:function(){return this.map(function(){for(var t=this.offsetParent||u.body;t&&!m.test(t.nodeName)&&"static"==n(t).css("position");)t=t.offsetParent;return t})}},n.fn.detach=n.fn.remove,["width","height"].forEach(function(e){var i=e.replace(/./,function(t){return t[0].toUpperCase()});n.fn[e]=function(r){var o,s=this[0];return r===t?k(s)?s["inner"+i]:Z(s)?s.documentElement["scroll"+i]:(o=this.offset())&&o[e]:this.each(function(t){s=n(this),s.css(e,Y(this,r,t,s[e]()))})}}),y.forEach(function(t,e){var i=e%2;n.fn[t]=function(){var t,o,r=n.map(arguments,function(e){return t=D(e),"object"==t||"array"==t||null==e?e:C.fragment(e)}),s=this.length>1;return r.length<1?this:this.each(function(t,a){o=i?a:a.parentNode,a=0==e?a.nextSibling:1==e?a.firstChild:2==e?a:null;var f=n.contains(u.documentElement,o);r.forEach(function(t){if(s)t=t.cloneNode(!0);else if(!o)return n(t).remove();o.insertBefore(t,a),f&&Q(t,function(t){null==t.nodeName||"SCRIPT"!==t.nodeName.toUpperCase()||t.type&&"text/javascript"!==t.type||t.src||window.eval.call(window,t.innerHTML)})})})},n.fn[i?t+"To":"insert"+(e?"Before":"After")]=function(e){return n(e)[t](this),this}}),C.Z.prototype=X.prototype=n.fn,C.uniq=P,C.deserializeValue=K,n.zepto=C,n}();window.Zepto=Zepto,void 0===window.$&&(window.$=Zepto),function(t){function l(t){return t._zid||(t._zid=e++)}function h(t,e,n,i){if(e=p(e),e.ns)var r=d(e.ns);return(s[l(t)]||[]).filter(function(t){return!(!t||e.e&&t.e!=e.e||e.ns&&!r.test(t.ns)||n&&l(t.fn)!==l(n)||i&&t.sel!=i)})}function p(t){var e=(""+t).split(".");return{e:e[0],ns:e.slice(1).sort().join(" ")}}function d(t){return new RegExp("(?:^| )"+t.replace(" "," .* ?")+"(?: |$)")}function m(t,e){return t.del&&!u&&t.e in f||!!e}function g(t){return c[t]||u&&f[t]||t}function v(e,i,r,o,a,u,f){var h=l(e),d=s[h]||(s[h]=[]);i.split(/\s/).forEach(function(i){if("ready"==i)return t(document).ready(r);var s=p(i);s.fn=r,s.sel=a,s.e in c&&(r=function(e){var n=e.relatedTarget;return!n||n!==this&&!t.contains(this,n)?s.fn.apply(this,arguments):void 0}),s.del=u;var l=u||r;s.proxy=function(t){if(t=T(t),!t.isImmediatePropagationStopped()){t.data=o;var i=l.apply(e,t._args==n?[t]:[t].concat(t._args));return i===!1&&(t.preventDefault(),t.stopPropagation()),i}},s.i=d.length,d.push(s),"addEventListener"in e&&e.addEventListener(g(s.e),s.proxy,m(s,f))})}function y(t,e,n,i,r){var o=l(t);(e||"").split(/\s/).forEach(function(e){h(t,e,n,i).forEach(function(e){delete s[o][e.i],"removeEventListener"in t&&t.removeEventListener(g(e.e),e.proxy,m(e,r))})})}function T(e,i){return(i||!e.isDefaultPrevented)&&(i||(i=e),t.each(E,function(t,n){var r=i[t];e[t]=function(){return this[n]=w,r&&r.apply(i,arguments)},e[n]=x}),(i.defaultPrevented!==n?i.defaultPrevented:"returnValue"in i?i.returnValue===!1:i.getPreventDefault&&i.getPreventDefault())&&(e.isDefaultPrevented=w)),e}function j(t){var e,i={originalEvent:t};for(e in t)b.test(e)||t[e]===n||(i[e]=t[e]);return T(i,t)}var n,e=1,i=Array.prototype.slice,r=t.isFunction,o=function(t){return"string"==typeof t},s={},a={},u="onfocusin"in window,f={focus:"focusin",blur:"focusout"},c={mouseenter:"mouseover",mouseleave:"mouseout"};a.click=a.mousedown=a.mouseup=a.mousemove="MouseEvents",t.event={add:v,remove:y},t.proxy=function(e,n){var s=2 in arguments&&i.call(arguments,2);if(r(e)){var a=function(){return e.apply(n,s?s.concat(i.call(arguments)):arguments)};return a._zid=l(e),a}if(o(n))return s?(s.unshift(e[n],e),t.proxy.apply(null,s)):t.proxy(e[n],e);throw new TypeError("expected function")},t.fn.bind=function(t,e,n){return this.on(t,e,n)},t.fn.unbind=function(t,e){return this.off(t,e)},t.fn.one=function(t,e,n,i){return this.on(t,e,n,i,1)};var w=function(){return!0},x=function(){return!1},b=/^([A-Z]|returnValue$|layer[XY]$)/,E={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};t.fn.delegate=function(t,e,n){return this.on(e,t,n)},t.fn.undelegate=function(t,e,n){return this.off(e,t,n)},t.fn.live=function(e,n){return t(document.body).delegate(this.selector,e,n),this},t.fn.die=function(e,n){return t(document.body).undelegate(this.selector,e,n),this},t.fn.on=function(e,s,a,u,f){var c,l,h=this;return e&&!o(e)?(t.each(e,function(t,e){h.on(t,s,a,e,f)}),h):(o(s)||r(u)||u===!1||(u=a,a=s,s=n),(u===n||a===!1)&&(u=a,a=n),u===!1&&(u=x),h.each(function(n,r){f&&(c=function(t){return y(r,t.type,u),u.apply(this,arguments)}),s&&(l=function(e){var n,o=t(e.target).closest(s,r).get(0);return o&&o!==r?(n=t.extend(j(e),{currentTarget:o,liveFired:r}),(c||u).apply(o,[n].concat(i.call(arguments,1)))):void 0}),v(r,e,u,a,s,l||c)}))},t.fn.off=function(e,i,s){var a=this;return e&&!o(e)?(t.each(e,function(t,e){a.off(t,i,e)}),a):(o(i)||r(s)||s===!1||(s=i,i=n),s===!1&&(s=x),a.each(function(){y(this,e,s,i)}))},t.fn.trigger=function(e,n){return e=o(e)||t.isPlainObject(e)?t.Event(e):T(e),e._args=n,this.each(function(){e.type in f&&"function"==typeof this[e.type]?this[e.type]():"dispatchEvent"in this?this.dispatchEvent(e):t(this).triggerHandler(e,n)})},t.fn.triggerHandler=function(e,n){var i,r;return this.each(function(s,a){i=j(o(e)?t.Event(e):e),i._args=n,i.target=a,t.each(h(a,e.type||e),function(t,e){return r=e.proxy(i),i.isImmediatePropagationStopped()?!1:void 0})}),r},"focusin focusout focus blur load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach(function(e){t.fn[e]=function(t){return 0 in arguments?this.bind(e,t):this.trigger(e)}}),t.Event=function(t,e){o(t)||(e=t,t=e.type);var n=document.createEvent(a[t]||"Events"),i=!0;if(e)for(var r in e)"bubbles"==r?i=!!e[r]:n[r]=e[r];return n.initEvent(t,i,!0),T(n)}}(Zepto),function(t){function h(e,n,i){var r=t.Event(n);return t(e).trigger(r,i),!r.isDefaultPrevented()}function p(t,e,i,r){return t.global?h(e||n,i,r):void 0}function d(e){e.global&&0===t.active++&&p(e,null,"ajaxStart")}function m(e){e.global&&!--t.active&&p(e,null,"ajaxStop")}function g(t,e){var n=e.context;return e.beforeSend.call(n,t,e)===!1||p(e,n,"ajaxBeforeSend",[t,e])===!1?!1:void p(e,n,"ajaxSend",[t,e])}function v(t,e,n,i){var r=n.context,o="success";n.success.call(r,t,o,e),i&&i.resolveWith(r,[t,o,e]),p(n,r,"ajaxSuccess",[e,n,t]),w(o,e,n)}function y(t,e,n,i,r){var o=i.context;i.error.call(o,n,e,t),r&&r.rejectWith(o,[n,e,t]),p(i,o,"ajaxError",[n,i,t||e]),w(e,n,i)}function w(t,e,n){var i=n.context;n.complete.call(i,e,t),p(n,i,"ajaxComplete",[e,n]),m(n)}function x(){}function b(t){return t&&(t=t.split(";",2)[0]),t&&(t==f?"html":t==u?"json":s.test(t)?"script":a.test(t)&&"xml")||"text"}function E(t,e){return""==e?t:(t+"&"+e).replace(/[&?]{1,2}/,"?")}function T(e){e.processData&&e.data&&"string"!=t.type(e.data)&&(e.data=t.param(e.data,e.traditional)),!e.data||e.type&&"GET"!=e.type.toUpperCase()||(e.url=E(e.url,e.data),e.data=void 0)}function j(e,n,i,r){return t.isFunction(n)&&(r=i,i=n,n=void 0),t.isFunction(i)||(r=i,i=void 0),{url:e,data:n,success:i,dataType:r}}function C(e,n,i,r){var o,s=t.isArray(n),a=t.isPlainObject(n);t.each(n,function(n,u){o=t.type(u),r&&(n=i?r:r+"["+(a||"object"==o||"array"==o?n:"")+"]"),!r&&s?e.add(u.name,u.value):"array"==o||!i&&"object"==o?C(e,u,i,n):e.add(n,u)})}var i,r,e=0,n=window.document,o=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,s=/^(?:text|application)\/javascript/i,a=/^(?:text|application)\/xml/i,u="application/json",f="text/html",c=/^\s*$/,l=n.createElement("a");l.href=window.location.href,t.active=0,t.ajaxJSONP=function(i,r){if(!("type"in i))return t.ajax(i);var f,h,o=i.jsonpCallback,s=(t.isFunction(o)?o():o)||"jsonp"+ ++e,a=n.createElement("script"),u=window[s],c=function(e){t(a).triggerHandler("error",e||"abort")},l={abort:c};return r&&r.promise(l),t(a).on("load error",function(e,n){clearTimeout(h),t(a).off().remove(),"error"!=e.type&&f?v(f[0],l,i,r):y(null,n||"error",l,i,r),window[s]=u,f&&t.isFunction(u)&&u(f[0]),u=f=void 0}),g(l,i)===!1?(c("abort"),l):(window[s]=function(){f=arguments},a.src=i.url.replace(/\?(.+)=\?/,"?$1="+s),n.head.appendChild(a),i.timeout>0&&(h=setTimeout(function(){c("timeout")},i.timeout)),l)},t.ajaxSettings={type:"GET",beforeSend:x,success:x,error:x,complete:x,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript, application/x-javascript",json:u,xml:"application/xml, text/xml",html:f,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0},t.ajax=function(e){var a,u,o=t.extend({},e||{}),s=t.Deferred&&t.Deferred();for(i in t.ajaxSettings)void 0===o[i]&&(o[i]=t.ajaxSettings[i]);d(o),o.crossDomain||(a=n.createElement("a"),a.href=o.url,a.href=a.href,o.crossDomain=l.protocol+"//"+l.host!=a.protocol+"//"+a.host),o.url||(o.url=window.location.toString()),(u=o.url.indexOf("#"))>-1&&(o.url=o.url.slice(0,u)),T(o);var f=o.dataType,h=/\?.+=\?/.test(o.url);if(h&&(f="jsonp"),o.cache!==!1&&(e&&e.cache===!0||"script"!=f&&"jsonp"!=f)||(o.url=E(o.url,"_="+Date.now())),"jsonp"==f)return h||(o.url=E(o.url,o.jsonp?o.jsonp+"=?":o.jsonp===!1?"":"callback=?")),t.ajaxJSONP(o,s);var N,p=o.accepts[f],m={},w=function(t,e){m[t.toLowerCase()]=[t,e]},j=/^([\w-]+:)\/\//.test(o.url)?RegExp.$1:window.location.protocol,S=o.xhr(),C=S.setRequestHeader;if(s&&s.promise(S),o.crossDomain||w("X-Requested-With","XMLHttpRequest"),w("Accept",p||"*/*"),(p=o.mimeType||p)&&(p.indexOf(",")>-1&&(p=p.split(",",2)[0]),S.overrideMimeType&&S.overrideMimeType(p)),(o.contentType||o.contentType!==!1&&o.data&&"GET"!=o.type.toUpperCase())&&w("Content-Type",o.contentType||"application/x-www-form-urlencoded"),o.headers)for(r in o.headers)w(r,o.headers[r]);if(S.setRequestHeader=w,S.onreadystatechange=function(){if(4==S.readyState){S.onreadystatechange=x,clearTimeout(N);var e,n=!1;if(S.status>=200&&S.status<300||304==S.status||0==S.status&&"file:"==j){f=f||b(o.mimeType||S.getResponseHeader("content-type")),e=S.responseText;try{"script"==f?(1,eval)(e):"xml"==f?e=S.responseXML:"json"==f&&(e=c.test(e)?null:t.parseJSON(e))}catch(i){n=i}n?y(n,"parsererror",S,o,s):v(e,S,o,s)}else y(S.statusText||null,S.status?"error":"abort",S,o,s)}},g(S,o)===!1)return S.abort(),y(null,"abort",S,o,s),S;if(o.xhrFields)for(r in o.xhrFields)S[r]=o.xhrFields[r];var P="async"in o?o.async:!0;S.open(o.type,o.url,P,o.username,o.password);for(r in m)C.apply(S,m[r]);return o.timeout>0&&(N=setTimeout(function(){S.onreadystatechange=x,S.abort(),y(null,"timeout",S,o,s)},o.timeout)),S.send(o.data?o.data:null),S},t.get=function(){return t.ajax(j.apply(null,arguments))},t.post=function(){var e=j.apply(null,arguments);return e.type="POST",t.ajax(e)},t.getJSON=function(){var e=j.apply(null,arguments);return e.dataType="json",t.ajax(e)},t.fn.load=function(e,n,i){if(!this.length)return this;var a,r=this,s=e.split(/\s/),u=j(e,n,i),f=u.success;return s.length>1&&(u.url=s[0],a=s[1]),u.success=function(e){r.html(a?t("<div>").html(e.replace(o,"")).find(a):e),f&&f.apply(r,arguments)},t.ajax(u),this};var S=encodeURIComponent;t.param=function(e,n){var i=[];return i.add=function(e,n){t.isFunction(n)&&(n=n()),null==n&&(n=""),this.push(S(e)+"="+S(n))},C(i,e,n),i.join("&").replace(/%20/g,"+")}}(Zepto),function(t){t.Callbacks=function(e){e=t.extend({},e);var n,i,r,o,s,a,u=[],f=!e.once&&[],c=function(t){for(n=e.memory&&t,i=!0,a=o||0,o=0,s=u.length,r=!0;u&&s>a;++a)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}r=!1,u&&(f?f.length&&c(f.shift()):n?u.length=0:l.disable())},l={add:function(){if(u){var i=u.length,a=function(n){t.each(n,function(t,n){"function"==typeof n?e.unique&&l.has(n)||u.push(n):n&&n.length&&"string"!=typeof n&&a(n)})};a(arguments),r?s=u.length:n&&(o=i,c(n))}return this},remove:function(){return u&&t.each(arguments,function(e,n){for(var i;(i=t.inArray(n,u,i))>-1;)u.splice(i,1),r&&(s>=i&&--s,a>=i&&--a)}),this},has:function(e){return!(!u||!(e?t.inArray(e,u)>-1:u.length))},empty:function(){return s=u.length=0,this},disable:function(){return u=f=n=void 0,this},disabled:function(){return!u},lock:function(){return f=void 0,n||l.disable(),this},locked:function(){return!f},fireWith:function(t,e){return!u||i&&!f||(e=e||[],e=[t,e.slice?e.slice():e],r?f.push(e):c(e)),this},fire:function(){return l.fireWith(this,arguments)},fired:function(){return!!i}};return l}}(Zepto),function(t){function n(e){var i=[["resolve","done",t.Callbacks({once:1,memory:1}),"resolved"],["reject","fail",t.Callbacks({once:1,memory:1}),"rejected"],["notify","progress",t.Callbacks({memory:1})]],r="pending",o={state:function(){return r},always:function(){return s.done(arguments).fail(arguments),this},then:function(){var e=arguments;return n(function(n){t.each(i,function(i,r){var a=t.isFunction(e[i])&&e[i];s[r[1]](function(){var e=a&&a.apply(this,arguments);if(e&&t.isFunction(e.promise))e.promise().done(n.resolve).fail(n.reject).progress(n.notify);else{var i=this===o?n.promise():this,s=a?[e]:arguments;n[r[0]+"With"](i,s)}})}),e=null}).promise()},promise:function(e){return null!=e?t.extend(e,o):o}},s={};return t.each(i,function(t,e){var n=e[2],a=e[3];o[e[1]]=n.add,a&&n.add(function(){r=a},i[1^t][2].disable,i[2][2].lock),s[e[0]]=function(){return s[e[0]+"With"](this===s?o:this,arguments),this},s[e[0]+"With"]=n.fireWith}),o.promise(s),e&&e.call(s,s),s}var e=Array.prototype.slice;t.when=function(i){var f,c,l,r=e.call(arguments),o=r.length,s=0,a=1!==o||i&&t.isFunction(i.promise)?o:0,u=1===a?i:n(),h=function(t,n,i){return function(r){n[t]=this,i[t]=arguments.length>1?e.call(arguments):r,i===f?u.notifyWith(n,i):--a||u.resolveWith(n,i)}};if(o>1)for(f=new Array(o),c=new Array(o),l=new Array(o);o>s;++s)r[s]&&t.isFunction(r[s].promise)?r[s].promise().done(h(s,l,r)).fail(u.reject).progress(h(s,c,f)):--a;return a||u.resolveWith(l,r),u.promise()},t.Deferred=n}(Zepto),function(t){function u(t,e,n,i){return Math.abs(t-e)>=Math.abs(n-i)?t-e>0?"Left":"Right":n-i>0?"Up":"Down"}function f(){o=null,e.last&&(e.el.trigger("longTap"),e={})}function c(){o&&clearTimeout(o),o=null}function l(){n&&clearTimeout(n),i&&clearTimeout(i),r&&clearTimeout(r),o&&clearTimeout(o),n=i=r=o=null,e={}}function h(t){return("touch"==t.pointerType||t.pointerType==t.MSPOINTER_TYPE_TOUCH)&&t.isPrimary}function p(t,e){return t.type=="pointer"+e||t.type.toLowerCase()=="mspointer"+e}var n,i,r,o,a,e={},s=750;t(document).ready(function(){var d,m,y,w,g=0,v=0;"MSGesture"in window&&(a=new MSGesture,a.target=document.body),t(document).bind("MSGestureEnd",function(t){var n=t.velocityX>1?"Right":t.velocityX<-1?"Left":t.velocityY>1?"Down":t.velocityY<-1?"Up":null;n&&(e.el.trigger("swipe"),e.el.trigger("swipe"+n))}).on("touchstart MSPointerDown pointerdown",function(i){(!(w=p(i,"down"))||h(i))&&(y=w?i:i.touches[0],i.touches&&1===i.touches.length&&e.x2&&(e.x2=void 0,e.y2=void 0),d=Date.now(),m=d-(e.last||d),e.el=t("tagName"in y.target?y.target:y.target.parentNode),n&&clearTimeout(n),e.x1=y.pageX,e.y1=y.pageY,m>0&&250>=m&&(e.isDoubleTap=!0),e.last=d,o=setTimeout(f,s),a&&w&&a.addPointer(i.pointerId))}).on("touchmove MSPointerMove pointermove",function(t){(!(w=p(t,"move"))||h(t))&&(y=w?t:t.touches[0],c(),e.x2=y.pageX,e.y2=y.pageY,g+=Math.abs(e.x1-e.x2),v+=Math.abs(e.y1-e.y2))}).on("touchend MSPointerUp pointerup",function(o){(!(w=p(o,"up"))||h(o))&&(c(),e.x2&&Math.abs(e.x1-e.x2)>30||e.y2&&Math.abs(e.y1-e.y2)>30?r=setTimeout(function(){e.el.trigger("swipe"),e.el.trigger("swipe"+u(e.x1,e.x2,e.y1,e.y2)),e={}},0):"last"in e&&(30>g&&30>v?i=setTimeout(function(){var i=t.Event("tap");i.cancelTouch=l,e.el.trigger(i),e.isDoubleTap?(e.el&&e.el.trigger("doubleTap"),e={}):n=setTimeout(function(){n=null,e.el&&e.el.trigger("singleTap"),e={}},250)},0):e={}),g=v=0)}).on("touchcancel MSPointerCancel pointercancel",l),t(window).on("scroll",l)}),["swipe","swipeLeft","swipeRight","swipeUp","swipeDown","doubleTap","tap","singleTap","longTap"].forEach(function(e){t.fn[e]=function(t){return this.on(e,t)}})}(Zepto),function(t){function r(e){return e=t(e),!(!e.width()&&!e.height())&&"none"!==e.css("display")}function f(t,e){t=t.replace(/=#\]/g,'="#"]');var n,i,r=s.exec(t);if(r&&r[2]in o&&(n=o[r[2]],i=r[3],t=r[1],i)){var a=Number(i);i=isNaN(a)?i.replace(/^["']|["']$/g,""):a}return e(t,n,i)}var e=t.zepto,n=e.qsa,i=e.matches,o=t.expr[":"]={visible:function(){return r(this)?this:void 0},hidden:function(){return r(this)?void 0:this},selected:function(){return this.selected?this:void 0},checked:function(){return this.checked?this:void 0},parent:function(){return this.parentNode},first:function(t){return 0===t?this:void 0},last:function(t,e){return t===e.length-1?this:void 0},eq:function(t,e,n){return t===n?this:void 0},contains:function(e,n,i){return t(this).text().indexOf(i)>-1?this:void 0},has:function(t,n,i){return e.qsa(this,i).length?this:void 0}},s=new RegExp("(.*):(\\w+)(?:\\(([^)]+)\\))?$\\s*"),a=/^\s*>/,u="Zepto"+ +new Date;e.qsa=function(i,r){return f(r,function(o,s,f){try{var c;!o&&s?o="*":a.test(o)&&(c=t(i).addClass(u),o="."+u+" "+o);var l=n(i,o)}catch(h){throw console.error("error performing selector: %o",r),h}finally{c&&c.removeClass(u)}return s?e.uniq(t.map(l,function(t,e){return s.call(t,e,l,f)})):l})},e.matches=function(t,e){return f(e,function(e,n,r){return!(e&&!i(t,e)||n&&n.call(t,null,r)!==t)})}}(Zepto);
module.exports = Zepto;
},{}]},{},[3,1])
//# sourceMappingURL=clappr.map |
src/svg-icons/image/exposure-plus-2.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageExposurePlus2 = (props) => (
<SvgIcon {...props}>
<path d="M16.05 16.29l2.86-3.07c.38-.39.72-.79 1.04-1.18.32-.39.59-.78.82-1.17.23-.39.41-.78.54-1.17.13-.39.19-.79.19-1.18 0-.53-.09-1.02-.27-1.46-.18-.44-.44-.81-.78-1.11-.34-.31-.77-.54-1.26-.71-.51-.16-1.08-.24-1.72-.24-.69 0-1.31.11-1.85.32-.54.21-1 .51-1.36.88-.37.37-.65.8-.84 1.3-.18.47-.27.97-.28 1.5h2.14c.01-.31.05-.6.13-.87.09-.29.23-.54.4-.75.18-.21.41-.37.68-.49.27-.12.6-.18.96-.18.31 0 .58.05.81.15.23.1.43.25.59.43.16.18.28.4.37.65.08.25.13.52.13.81 0 .22-.03.43-.08.65-.06.22-.15.45-.29.7-.14.25-.32.53-.56.83-.23.3-.52.65-.88 1.03l-4.17 4.55V18H22v-1.71h-5.95zM8 7H6v4H2v2h4v4h2v-4h4v-2H8V7z"/>
</SvgIcon>
);
ImageExposurePlus2 = pure(ImageExposurePlus2);
ImageExposurePlus2.displayName = 'ImageExposurePlus2';
export default ImageExposurePlus2;
|
src/main/app/src/components/Layout/Layout.js | mbrossard/cryptonit-cloud | import React from 'react';
import PropTypes from 'prop-types'
import _ from 'underscore';
class Layout extends React.Component {
static propTypes = {
children: PropTypes.node.isRequired
};
render() {
const { children, className, ...otherProps } = this.props;
return (
<div
id="application"
className={ className }
>
<div className="main-wrap">
{ children }
</div>
</div>
)
}
}
export default Layout;
|
ajax/libs/react-virtualized/7.18.0/react-virtualized.min.js | dlueth/cdnjs | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("React"),require("React.addons.shallowCompare"),require("ReactDOM")):"function"==typeof define&&define.amd?define(["React","React.addons.shallowCompare","ReactDOM"],t):"object"==typeof exports?exports.ReactVirtualized=t(require("React"),require("React.addons.shallowCompare"),require("ReactDOM")):e.ReactVirtualized=t(e.React,e["React.addons.shallowCompare"],e.ReactDOM)}(this,function(e,t,n){return function(e){function t(o){if(n[o])return n[o].exports;var r=n[o]={exports:{},id:o,loaded:!1};return e[o].call(r.exports,r,r.exports,t),r.loaded=!0,r.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=n(1);Object.defineProperty(t,"ArrowKeyStepper",{enumerable:!0,get:function(){return o.ArrowKeyStepper}});var r=n(5);Object.defineProperty(t,"AutoSizer",{enumerable:!0,get:function(){return r.AutoSizer}});var i=n(8);Object.defineProperty(t,"CellMeasurer",{enumerable:!0,get:function(){return i.CellMeasurer}});var l=n(11);Object.defineProperty(t,"Collection",{enumerable:!0,get:function(){return l.Collection}});var s=n(25);Object.defineProperty(t,"ColumnSizer",{enumerable:!0,get:function(){return s.ColumnSizer}});var a=n(35);Object.defineProperty(t,"defaultFlexTableCellDataGetter",{enumerable:!0,get:function(){return a.defaultCellDataGetter}}),Object.defineProperty(t,"defaultFlexTableCellRenderer",{enumerable:!0,get:function(){return a.defaultCellRenderer}}),Object.defineProperty(t,"defaultFlexTableHeaderRenderer",{enumerable:!0,get:function(){return a.defaultHeaderRenderer}}),Object.defineProperty(t,"defaultFlexTableRowRenderer",{enumerable:!0,get:function(){return a.defaultRowRenderer}}),Object.defineProperty(t,"FlexTable",{enumerable:!0,get:function(){return a.FlexTable}}),Object.defineProperty(t,"FlexColumn",{enumerable:!0,get:function(){return a.FlexColumn}}),Object.defineProperty(t,"SortDirection",{enumerable:!0,get:function(){return a.SortDirection}}),Object.defineProperty(t,"SortIndicator",{enumerable:!0,get:function(){return a.SortIndicator}});var u=n(27);Object.defineProperty(t,"defaultCellRangeRenderer",{enumerable:!0,get:function(){return u.defaultCellRangeRenderer}}),Object.defineProperty(t,"Grid",{enumerable:!0,get:function(){return u.Grid}});var c=n(44);Object.defineProperty(t,"InfiniteLoader",{enumerable:!0,get:function(){return c.InfiniteLoader}});var d=n(46);Object.defineProperty(t,"ScrollSync",{enumerable:!0,get:function(){return d.ScrollSync}});var f=n(48);Object.defineProperty(t,"VirtualScroll",{enumerable:!0,get:function(){return f.VirtualScroll}});var p=n(50);Object.defineProperty(t,"WindowScroller",{enumerable:!0,get:function(){return p.WindowScroller}})},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.ArrowKeyStepper=t["default"]=void 0;var r=n(2),i=o(r);t["default"]=i["default"],t.ArrowKeyStepper=i["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),a=n(3),u=o(a),c=n(4),d=o(c),f=function(e){function t(e,n){r(this,t);var o=i(this,Object.getPrototypeOf(t).call(this,e,n));return o.state={scrollToColumn:0,scrollToRow:0},o._columnStartIndex=0,o._columnStopIndex=0,o._rowStartIndex=0,o._rowStopIndex=0,o._onKeyDown=o._onKeyDown.bind(o),o._onSectionRendered=o._onSectionRendered.bind(o),o}return l(t,e),s(t,[{key:"render",value:function(){var e=this.props,t=e.className,n=e.children,o=this.state,r=o.scrollToColumn,i=o.scrollToRow;return u["default"].createElement("div",{className:t,onKeyDown:this._onKeyDown},n({onSectionRendered:this._onSectionRendered,scrollToColumn:r,scrollToRow:i}))}},{key:"shouldComponentUpdate",value:function(e,t){return(0,d["default"])(this,e,t)}},{key:"_onKeyDown",value:function(e){var t=this.props,n=t.columnCount,o=t.rowCount;switch(e.key){case"ArrowDown":e.preventDefault(),this.setState({scrollToRow:Math.min(this._rowStopIndex+1,o-1)});break;case"ArrowLeft":e.preventDefault(),this.setState({scrollToColumn:Math.max(this._columnStartIndex-1,0)});break;case"ArrowRight":e.preventDefault(),this.setState({scrollToColumn:Math.min(this._columnStopIndex+1,n-1)});break;case"ArrowUp":e.preventDefault(),this.setState({scrollToRow:Math.max(this._rowStartIndex-1,0)})}}},{key:"_onSectionRendered",value:function(e){var t=e.columnStartIndex,n=e.columnStopIndex,o=e.rowStartIndex,r=e.rowStopIndex;this._columnStartIndex=t,this._columnStopIndex=n,this._rowStartIndex=o,this._rowStopIndex=r}}]),t}(a.Component);f.propTypes={children:a.PropTypes.func.isRequired,className:a.PropTypes.string,columnCount:a.PropTypes.number.isRequired,rowCount:a.PropTypes.number.isRequired},t["default"]=f},function(t,n){t.exports=e},function(e,t){e.exports=React.addons.shallowCompare},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.AutoSizer=t["default"]=void 0;var r=n(6),i=o(r);t["default"]=i["default"],t.AutoSizer=i["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),a=n(3),u=o(a),c=n(4),d=o(c),f=function(e){function t(e){r(this,t);var n=i(this,Object.getPrototypeOf(t).call(this,e));return n.state={height:0,width:0},n._onResize=n._onResize.bind(n),n._onScroll=n._onScroll.bind(n),n._setRef=n._setRef.bind(n),n}return l(t,e),s(t,[{key:"componentDidMount",value:function(){this._detectElementResize=n(7),this._detectElementResize.addResizeListener(this._parentNode,this._onResize),this._onResize()}},{key:"componentWillUnmount",value:function(){this._detectElementResize&&this._detectElementResize.removeResizeListener(this._parentNode,this._onResize)}},{key:"render",value:function(){var e=this.props,t=e.children,n=e.disableHeight,o=e.disableWidth,r=this.state,i=r.height,l=r.width,s={overflow:"visible"};return n||(s.height=0),o||(s.width=0),u["default"].createElement("div",{ref:this._setRef,onScroll:this._onScroll,style:s},t({height:i,width:l}))}},{key:"shouldComponentUpdate",value:function(e,t){return(0,d["default"])(this,e,t)}},{key:"_onResize",value:function(){var e=this.props.onResize,t=this._parentNode.getBoundingClientRect(),n=t.height||0,o=t.width||0,r=getComputedStyle(this._parentNode),i=parseInt(r.paddingLeft,10)||0,l=parseInt(r.paddingRight,10)||0,s=parseInt(r.paddingTop,10)||0,a=parseInt(r.paddingBottom,10)||0;this.setState({height:n-s-a,width:o-i-l}),e({height:n,width:o})}},{key:"_onScroll",value:function(e){e.stopPropagation()}},{key:"_setRef",value:function(e){this._parentNode=e&&e.parentNode}}]),t}(a.Component);f.propTypes={children:a.PropTypes.func.isRequired,disableHeight:a.PropTypes.bool,disableWidth:a.PropTypes.bool,onResize:a.PropTypes.func.isRequired},f.defaultProps={onResize:function(){}},t["default"]=f},function(e,t){"use strict";var n;n="undefined"!=typeof window?window:"undefined"!=typeof self?self:void 0;var o="undefined"!=typeof document&&document.attachEvent,r=!1;if(!o){var i=function(){var e=n.requestAnimationFrame||n.mozRequestAnimationFrame||n.webkitRequestAnimationFrame||function(e){return n.setTimeout(e,20)};return function(t){return e(t)}}(),l=function(){var e=n.cancelAnimationFrame||n.mozCancelAnimationFrame||n.webkitCancelAnimationFrame||n.clearTimeout;return function(t){return e(t)}}(),s=function(e){var t=e.__resizeTriggers__,n=t.firstElementChild,o=t.lastElementChild,r=n.firstElementChild;o.scrollLeft=o.scrollWidth,o.scrollTop=o.scrollHeight,r.style.width=n.offsetWidth+1+"px",r.style.height=n.offsetHeight+1+"px",n.scrollLeft=n.scrollWidth,n.scrollTop=n.scrollHeight},a=function(e){return e.offsetWidth!=e.__resizeLast__.width||e.offsetHeight!=e.__resizeLast__.height},u=function(e){var t=this;s(this),this.__resizeRAF__&&l(this.__resizeRAF__),this.__resizeRAF__=i(function(){a(t)&&(t.__resizeLast__.width=t.offsetWidth,t.__resizeLast__.height=t.offsetHeight,t.__resizeListeners__.forEach(function(n){n.call(t,e)}))})},c=!1,d="animation",f="",p="animationstart",h="Webkit Moz O ms".split(" "),y="webkitAnimationStart animationstart oAnimationStart MSAnimationStart".split(" "),_="",m=document.createElement("fakeelement");if(void 0!==m.style.animationName&&(c=!0),c===!1)for(var v=0;v<h.length;v++)if(void 0!==m.style[h[v]+"AnimationName"]){_=h[v],d=_+"Animation",f="-"+_.toLowerCase()+"-",p=y[v],c=!0;break}var S="resizeanim",g="@"+f+"keyframes "+S+" { from { opacity: 0; } to { opacity: 0; } } ",b=f+"animation: 1ms "+S+"; "}var w=function(){if(!r){var e=(g?g:"")+".resize-triggers { "+(b?b:"")+'visibility: hidden; opacity: 0; } .resize-triggers, .resize-triggers > div, .contract-trigger:before { content: " "; display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }',t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e)),t.appendChild(n),r=!0}},T=function(e,t){o?e.attachEvent("onresize",t):(e.__resizeTriggers__||("static"==getComputedStyle(e).position&&(e.style.position="relative"),w(),e.__resizeLast__={},e.__resizeListeners__=[],(e.__resizeTriggers__=document.createElement("div")).className="resize-triggers",e.__resizeTriggers__.innerHTML='<div class="expand-trigger"><div></div></div><div class="contract-trigger"></div>',e.appendChild(e.__resizeTriggers__),s(e),e.addEventListener("scroll",u,!0),p&&e.__resizeTriggers__.addEventListener(p,function(t){t.animationName==S&&s(e)})),e.__resizeListeners__.push(t))},C=function(e,t){o?e.detachEvent("onresize",t):(e.__resizeListeners__.splice(e.__resizeListeners__.indexOf(t),1),e.__resizeListeners__.length||(e.removeEventListener("scroll",u,!0),e.__resizeTriggers__=!e.removeChild(e.__resizeTriggers__)))};e.exports={addResizeListener:T,removeResizeListener:C}},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.CellMeasurer=t["default"]=void 0;var r=n(9),i=o(r);t["default"]=i["default"],t.CellMeasurer=i["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),a=n(3),u=o(a),c=n(10),d=o(c),f=function(e){function t(e,n){r(this,t);var o=i(this,Object.getPrototypeOf(t).call(this,e,n));return o._cachedColumnWidths={},o._cachedRowHeights={},o.getColumnWidth=o.getColumnWidth.bind(o),o.getRowHeight=o.getRowHeight.bind(o),o.resetMeasurements=o.resetMeasurements.bind(o),o.resetMeasurementForColumn=o.resetMeasurementForColumn.bind(o),o.resetMeasurementForRow=o.resetMeasurementForRow.bind(o),o}return l(t,e),s(t,[{key:"getColumnWidth",value:function(e){var t=e.index;if(this._cachedColumnWidths[t])return this._cachedColumnWidths[t];for(var n=this.props.rowCount,o=0,r=0;n>r;r++){var i=this._measureCell({clientWidth:!0,columnIndex:t,rowIndex:r}),l=i.width;o=Math.max(o,l)}return this._cachedColumnWidths[t]=o,o}},{key:"getRowHeight",value:function(e){var t=e.index;if(this._cachedRowHeights[t])return this._cachedRowHeights[t];for(var n=this.props.columnCount,o=0,r=0;n>r;r++){var i=this._measureCell({clientHeight:!0,columnIndex:r,rowIndex:t}),l=i.height;o=Math.max(o,l)}return this._cachedRowHeights[t]=o,o}},{key:"resetMeasurementForColumn",value:function(e){delete this._cachedColumnWidths[e]}},{key:"resetMeasurementForRow",value:function(e){delete this._cachedRowHeights[e]}},{key:"resetMeasurements",value:function(){this._cachedColumnWidths={},this._cachedRowHeights={}}},{key:"componentDidMount",value:function(){this._renderAndMount()}},{key:"componentWillReceiveProps",value:function(e){this._updateDivDimensions(e)}},{key:"componentWillUnmount",value:function(){this._unmountContainer()}},{key:"render",value:function(){var e=this.props.children;return e({getColumnWidth:this.getColumnWidth,getRowHeight:this.getRowHeight,resetMeasurements:this.resetMeasurements,resetMeasurementForColumn:this.resetMeasurementForColumn,resetMeasurementForRow:this.resetMeasurementForRow})}},{key:"_getContainerNode",value:function(e){var t=e.container;return t?d["default"].findDOMNode("function"==typeof t?t():t):document.body}},{key:"_measureCell",value:function(e){var t=e.clientHeight,n=void 0===t?!1:t,o=e.clientWidth,r=void 0===o?!0:o,i=e.columnIndex,l=e.rowIndex,s=this.props.cellRenderer,a=s({columnIndex:i,rowIndex:l});this._renderAndMount(),d["default"].unstable_renderSubtreeIntoContainer(this,a,this._div);var u={height:n&&this._div.clientHeight,width:r&&this._div.clientWidth};return d["default"].unmountComponentAtNode(this._div),u}},{key:"_renderAndMount",value:function(){this._div||(this._div=document.createElement("div"),this._div.style.display="inline-block",this._div.style.position="absolute",this._div.style.visibility="hidden",this._div.style.zIndex=-1,this._updateDivDimensions(this.props),this._containerNode=this._getContainerNode(this.props),this._containerNode.appendChild(this._div))}},{key:"_unmountContainer",value:function(){this._div&&(this._containerNode.removeChild(this._div),this._div=null),this._containerNode=null}},{key:"_updateDivDimensions",value:function(e){var t=e.height,n=e.width;t&&t!==this._divHeight&&(this._divHeight=t,this._div.style.height=t+"px"),n&&n!==this._divWidth&&(this._divWidth=n,this._div.style.width=n+"px")}}]),t}(a.Component);f.propTypes={cellRenderer:a.PropTypes.func.isRequired,children:a.PropTypes.func.isRequired,columnCount:a.PropTypes.number.isRequired,container:u["default"].PropTypes.oneOfType([u["default"].PropTypes.func,u["default"].PropTypes.node]),height:a.PropTypes.number,rowCount:a.PropTypes.number.isRequired,width:a.PropTypes.number},t["default"]=f},function(e,t){e.exports=n},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Collection=t["default"]=void 0;var r=n(12),i=o(r);t["default"]=i["default"],t.Collection=i["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){var n={};for(var o in e)t.indexOf(o)>=0||Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o]);return n}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function a(e){var t=e.cellRenderer,n=e.cellSizeAndPositionGetter,o=e.indices,r=e.isScrolling;return o.map(function(e){var o=n({index:e}),i=t({index:e,isScrolling:r});return null==i||i===!1?null:f["default"].createElement("div",{className:"Collection__cell",key:e,style:{height:o.height,left:o.x,top:o.y,width:o.width}},i)}).filter(function(e){return!!e})}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},c=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),d=n(3),f=o(d),p=n(13),h=o(p),y=n(21),_=o(y),m=n(24),v=o(m),S=n(4),g=o(S),b=function(e){function t(e,n){i(this,t);var o=l(this,Object.getPrototypeOf(t).call(this,e,n));return o._cellMetadata=[],o._lastRenderedCellIndices=[],o}return s(t,e),c(t,[{key:"recomputeCellSizesAndPositions",value:function(){this._collectionView.recomputeCellSizesAndPositions()}},{key:"render",value:function(){var e=this,t=r(this.props,[]);return f["default"].createElement(h["default"],u({cellLayoutManager:this,ref:function(t){e._collectionView=t}},t))}},{key:"shouldComponentUpdate",value:function(e,t){return(0,g["default"])(this,e,t)}},{key:"calculateSizeAndPositionData",value:function(){var e=this.props,t=e.cellCount,n=e.cellSizeAndPositionGetter,o=e.sectionSize,r=(0,_["default"])({cellCount:t,cellSizeAndPositionGetter:n,sectionSize:o});this._cellMetadata=r.cellMetadata,this._sectionManager=r.sectionManager,this._height=r.height,this._width=r.width}},{key:"getLastRenderedIndices",value:function(){return this._lastRenderedCellIndices}},{key:"getScrollPositionForCell",value:function(e){var t=e.align,n=e.cellIndex,o=e.height,r=e.scrollLeft,i=e.scrollTop,l=e.width,s=this.props.cellCount;if(n>=0&&s>n){var a=this._cellMetadata[n];r=(0,v["default"])({align:t,cellOffset:a.x,cellSize:a.width,containerSize:l,currentOffset:r,targetIndex:n}),i=(0,v["default"])({align:t,cellOffset:a.y,cellSize:a.height,containerSize:o,currentOffset:i,targetIndex:n})}return{scrollLeft:r,scrollTop:i}}},{key:"getTotalSize",value:function(){return{height:this._height,width:this._width}}},{key:"cellRenderers",value:function(e){var t=this,n=e.height,o=e.isScrolling,r=e.width,i=e.x,l=e.y,s=this.props,a=s.cellGroupRenderer,u=s.cellRenderer;return this._lastRenderedCellIndices=this._sectionManager.getCellIndices({height:n,width:r,x:i,y:l}),a({cellRenderer:u,cellSizeAndPositionGetter:function(e){var n=e.index;return t._sectionManager.getCellMetadata({index:n})},indices:this._lastRenderedCellIndices,isScrolling:o})}}]),t}(d.Component);b.propTypes={"aria-label":d.PropTypes.string,cellCount:d.PropTypes.number.isRequired,cellGroupRenderer:d.PropTypes.func.isRequired,cellRenderer:d.PropTypes.func.isRequired,cellSizeAndPositionGetter:d.PropTypes.func.isRequired,sectionSize:d.PropTypes.number},b.defaultProps={"aria-label":"grid",cellGroupRenderer:a},t["default"]=b},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},a=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),u=n(3),c=o(u),d=n(14),f=o(d),p=n(15),h=o(p),y=n(16),_=o(y),m=n(18),v=o(m),S=n(4),g=o(S),b=150,w={OBSERVED:"observed",REQUESTED:"requested"},T=function(e){function t(e,n){r(this,t);var o=i(this,Object.getPrototypeOf(t).call(this,e,n));return o.state={calculateSizeAndPositionDataOnNextUpdate:!1,isScrolling:!1,scrollLeft:0,scrollTop:0},o._onSectionRenderedMemoizer=(0,h["default"])(),o._onScrollMemoizer=(0,h["default"])(!1),o._invokeOnSectionRenderedHelper=o._invokeOnSectionRenderedHelper.bind(o),o._onScroll=o._onScroll.bind(o),o._updateScrollPositionForScrollToCell=o._updateScrollPositionForScrollToCell.bind(o),o}return l(t,e),a(t,[{key:"recomputeCellSizesAndPositions",value:function(){this.setState({calculateSizeAndPositionDataOnNextUpdate:!0})}},{key:"componentDidMount",value:function(){var e=this.props,t=e.cellLayoutManager,n=e.scrollLeft,o=e.scrollToCell,r=e.scrollTop;this._scrollbarSizeMeasured||(this._scrollbarSize=(0,_["default"])(),this._scrollbarSizeMeasured=!0,this.setState({})),o>=0?this._updateScrollPositionForScrollToCell():(n>=0||r>=0)&&this._setScrollPosition({scrollLeft:n,scrollTop:r}),this._invokeOnSectionRenderedHelper();var i=t.getTotalSize(),l=i.height,s=i.width;this._invokeOnScrollMemoizer({scrollLeft:n||0,scrollTop:r||0,totalHeight:l,totalWidth:s})}},{key:"componentDidUpdate",value:function(e,t){var n=this.props,o=n.height,r=n.scrollToCell,i=n.width,l=this.state,s=l.scrollLeft,a=l.scrollPositionChangeReason,u=l.scrollToAlignment,c=l.scrollTop;a===w.REQUESTED&&(s>=0&&s!==t.scrollLeft&&s!==this._scrollingContainer.scrollLeft&&(this._scrollingContainer.scrollLeft=s),c>=0&&c!==t.scrollTop&&c!==this._scrollingContainer.scrollTop&&(this._scrollingContainer.scrollTop=c)),o===e.height&&u===e.scrollToAlignment&&r===e.scrollToCell&&i===e.width||this._updateScrollPositionForScrollToCell(),this._invokeOnSectionRenderedHelper()}},{key:"componentWillMount",value:function(){var e=this.props.cellLayoutManager;e.calculateSizeAndPositionData(),this._scrollbarSize=(0,_["default"])(),void 0===this._scrollbarSize?(this._scrollbarSizeMeasured=!1,this._scrollbarSize=0):this._scrollbarSizeMeasured=!0}},{key:"componentWillUnmount",value:function(){this._disablePointerEventsTimeoutId&&clearTimeout(this._disablePointerEventsTimeoutId),this._setNextStateAnimationFrameId&&v["default"].cancel(this._setNextStateAnimationFrameId)}},{key:"componentWillUpdate",value:function(e,t){0!==e.cellCount||0===t.scrollLeft&&0===t.scrollTop?e.scrollLeft===this.props.scrollLeft&&e.scrollTop===this.props.scrollTop||this._setScrollPosition({scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}):this._setScrollPosition({scrollLeft:0,scrollTop:0}),(e.cellCount!==this.props.cellCount||e.cellLayoutManager!==this.props.cellLayoutManager||t.calculateSizeAndPositionDataOnNextUpdate)&&e.cellLayoutManager.calculateSizeAndPositionData(),t.calculateSizeAndPositionDataOnNextUpdate&&this.setState({calculateSizeAndPositionDataOnNextUpdate:!1})}},{key:"render",value:function(){var e=this,t=this.props,n=t.cellCount,o=t.cellLayoutManager,r=t.className,i=t.height,l=t.noContentRenderer,a=t.style,u=t.width,d=this.state,p=d.isScrolling,h=d.scrollLeft,y=d.scrollTop,_=i>0&&u>0?o.cellRenderers({height:i,isScrolling:p,width:u,x:h,y:y}):[],m=o.getTotalSize(),v=m.height,S=m.width,g={height:i,width:u},b=v>i?this._scrollbarSize:0,w=S>u?this._scrollbarSize:0;return u>=S+b&&(g.overflowX="hidden"),i>=v+w&&(g.overflowY="hidden"),c["default"].createElement("div",{ref:function(t){e._scrollingContainer=t},"aria-label":this.props["aria-label"],className:(0,f["default"])("Collection",r),onScroll:this._onScroll,role:"grid",style:s({},g,a),tabIndex:0},n>0&&c["default"].createElement("div",{className:"Collection__innerScrollContainer",style:{height:v,maxHeight:v,maxWidth:S,pointerEvents:p?"none":"auto",width:S}},_),0===n&&l())}},{key:"shouldComponentUpdate",value:function(e,t){return(0,g["default"])(this,e,t)}},{key:"_enablePointerEventsAfterDelay",value:function(){var e=this;this._disablePointerEventsTimeoutId&&clearTimeout(this._disablePointerEventsTimeoutId),this._disablePointerEventsTimeoutId=setTimeout(function(){e._disablePointerEventsTimeoutId=null,e.setState({isScrolling:!1})},b)}},{key:"_invokeOnSectionRenderedHelper",value:function(){var e=this.props,t=e.cellLayoutManager,n=e.onSectionRendered;this._onSectionRenderedMemoizer({callback:n,indices:{indices:t.getLastRenderedIndices()}})}},{key:"_invokeOnScrollMemoizer",value:function(e){var t=this,n=e.scrollLeft,o=e.scrollTop,r=e.totalHeight,i=e.totalWidth;this._onScrollMemoizer({callback:function(e){var n=e.scrollLeft,o=e.scrollTop,l=t.props,s=l.height,a=l.onScroll,u=l.width;a({clientHeight:s,clientWidth:u,scrollHeight:r,scrollLeft:n,scrollTop:o,scrollWidth:i})},indices:{scrollLeft:n,scrollTop:o}})}},{key:"_setNextState",value:function(e){var t=this;this._setNextStateAnimationFrameId&&v["default"].cancel(this._setNextStateAnimationFrameId),this._setNextStateAnimationFrameId=(0,v["default"])(function(){t._setNextStateAnimationFrameId=null,t.setState(e)})}},{key:"_setScrollPosition",value:function(e){var t=e.scrollLeft,n=e.scrollTop,o={scrollPositionChangeReason:w.REQUESTED};t>=0&&(o.scrollLeft=t),n>=0&&(o.scrollTop=n),(t>=0&&t!==this.state.scrollLeft||n>=0&&n!==this.state.scrollTop)&&this.setState(o)}},{key:"_updateScrollPositionForScrollToCell",value:function(){var e=this.props,t=e.cellLayoutManager,n=e.height,o=e.scrollToAlignment,r=e.scrollToCell,i=e.width,l=this.state,s=l.scrollLeft,a=l.scrollTop;if(r>=0){var u=t.getScrollPositionForCell({align:o,cellIndex:r,height:n,scrollLeft:s,scrollTop:a,width:i});u.scrollLeft===s&&u.scrollTop===a||this._setScrollPosition(u)}}},{key:"_onScroll",value:function(e){if(e.target===this._scrollingContainer){this._enablePointerEventsAfterDelay();var t=this.props,n=t.cellLayoutManager,o=t.height,r=t.width,i=this._scrollbarSize,l=n.getTotalSize(),s=l.height,a=l.width,u=Math.max(0,Math.min(a-r+i,e.target.scrollLeft)),c=Math.max(0,Math.min(s-o+i,e.target.scrollTop));if(this.state.scrollLeft!==u||this.state.scrollTop!==c){var d=e.cancelable?w.OBSERVED:w.REQUESTED;this.state.isScrolling||this.setState({isScrolling:!0}),this._setNextState({isScrolling:!0,scrollLeft:u,scrollPositionChangeReason:d,scrollTop:c})}this._invokeOnScrollMemoizer({scrollLeft:u,scrollTop:c,totalWidth:a,totalHeight:s})}}}]),t}(u.Component);T.propTypes={"aria-label":u.PropTypes.string,cellCount:u.PropTypes.number.isRequired,cellLayoutManager:u.PropTypes.object.isRequired,className:u.PropTypes.string,height:u.PropTypes.number.isRequired,noContentRenderer:u.PropTypes.func.isRequired,onScroll:u.PropTypes.func.isRequired,onSectionRendered:u.PropTypes.func.isRequired,scrollLeft:u.PropTypes.number,scrollToAlignment:u.PropTypes.oneOf(["auto","end","start","center"]).isRequired,scrollToCell:u.PropTypes.number,scrollTop:u.PropTypes.number,style:u.PropTypes.object,width:u.PropTypes.number.isRequired},T.defaultProps={"aria-label":"grid",noContentRenderer:function(){return null},onScroll:function(){return null},onSectionRendered:function(){return null},scrollToAlignment:"auto",style:{}},t["default"]=T},function(e,t,n){var o,r;!function(){"use strict";function n(){for(var e=[],t=0;t<arguments.length;t++){var o=arguments[t];if(o){var r=typeof o;if("string"===r||"number"===r)e.push(o);else if(Array.isArray(o))e.push(n.apply(null,o));else if("object"===r)for(var l in o)i.call(o,l)&&o[l]&&e.push(l)}}return e.join(" ")}var i={}.hasOwnProperty;"undefined"!=typeof e&&e.exports?e.exports=n:(o=[],r=function(){return n}.apply(t,o),!(void 0!==r&&(e.exports=r)))}()},function(e,t){"use strict";function n(){var e=arguments.length<=0||void 0===arguments[0]?!0:arguments[0],t={};return function(n){var o=n.callback,r=n.indices,i=Object.keys(r),l=!e||i.every(function(e){var t=r[e];return Array.isArray(t)?t.length>0:t>=0}),s=i.length!==Object.keys(t).length||i.some(function(e){var n=t[e],o=r[e];return Array.isArray(o)?n.join(",")!==o.join(","):n!==o});t=r,l&&s&&o(r)}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n},function(e,t,n){"use strict";var o,r=n(17);e.exports=function(e){if((!o||e)&&r){var t=document.createElement("div");t.style.position="absolute",t.style.top="-9999px",t.style.width="50px",t.style.height="50px",t.style.overflow="scroll",document.body.appendChild(t),o=t.offsetWidth-t.clientWidth,document.body.removeChild(t)}return o}},function(e,t){"use strict";e.exports=!("undefined"==typeof window||!window.document||!window.document.createElement)},function(e,t,n){(function(t){for(var o=n(19),r="undefined"==typeof window?t:window,i=["moz","webkit"],l="AnimationFrame",s=r["request"+l],a=r["cancel"+l]||r["cancelRequest"+l],u=0;!s&&u<i.length;u++)s=r[i[u]+"Request"+l],a=r[i[u]+"Cancel"+l]||r[i[u]+"CancelRequest"+l];if(!s||!a){var c=0,d=0,f=[],p=1e3/60;s=function(e){if(0===f.length){var t=o(),n=Math.max(0,p-(t-c));c=n+t,setTimeout(function(){var e=f.slice(0);f.length=0;for(var t=0;t<e.length;t++)if(!e[t].cancelled)try{e[t].callback(c)}catch(n){setTimeout(function(){throw n},0)}},Math.round(n))}return f.push({handle:++d,callback:e,cancelled:!1}),d},a=function(e){for(var t=0;t<f.length;t++)f[t].handle===e&&(f[t].cancelled=!0)}}e.exports=function(e){return s.call(r,e)},e.exports.cancel=function(){a.apply(r,arguments)},e.exports.polyfill=function(){r.requestAnimationFrame=s,r.cancelAnimationFrame=a}}).call(t,function(){return this}())},function(e,t,n){(function(t){(function(){var n,o,r;"undefined"!=typeof performance&&null!==performance&&performance.now?e.exports=function(){return performance.now()}:"undefined"!=typeof t&&null!==t&&t.hrtime?(e.exports=function(){return(n()-r)/1e6},o=t.hrtime,n=function(){var e;return e=o(),1e9*e[0]+e[1]},r=n()):Date.now?(e.exports=function(){return Date.now()-r},r=Date.now()):(e.exports=function(){return(new Date).getTime()-r},r=(new Date).getTime())}).call(this)}).call(t,n(20))},function(e,t){function n(){u&&l&&(u=!1,l.length?a=l.concat(a):c=-1,a.length&&o())}function o(){if(!u){var e=setTimeout(n);u=!0;for(var t=a.length;t;){for(l=a,a=[];++c<t;)l&&l[c].run();c=-1,t=a.length}l=null,u=!1,clearTimeout(e)}}function r(e,t){this.fun=e,this.array=t}function i(){}var l,s=e.exports={},a=[],u=!1,c=-1;s.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];
a.push(new r(e,t)),1!==a.length||u||setTimeout(o,0)},r.prototype.run=function(){this.fun.apply(null,this.array)},s.title="browser",s.browser=!0,s.env={},s.argv=[],s.version="",s.versions={},s.on=i,s.addListener=i,s.once=i,s.off=i,s.removeListener=i,s.removeAllListeners=i,s.emit=i,s.binding=function(e){throw new Error("process.binding is not supported")},s.cwd=function(){return"/"},s.chdir=function(e){throw new Error("process.chdir is not supported")},s.umask=function(){return 0}},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){for(var t=e.cellCount,n=e.cellSizeAndPositionGetter,o=e.sectionSize,r=[],i=new l["default"](o),s=0,a=0,u=0;t>u;u++){var c=n({index:u});if(null==c.height||isNaN(c.height)||null==c.width||isNaN(c.width)||null==c.x||isNaN(c.x)||null==c.y||isNaN(c.y))throw Error("Invalid metadata returned for cell "+u+":\n x:"+c.x+", y:"+c.y+", width:"+c.width+", height:"+c.height);s=Math.max(s,c.y+c.height),a=Math.max(a,c.x+c.width),r[u]=c,i.registerCell({cellMetadatum:c,index:u})}return{cellMetadata:r,height:s,sectionManager:i,width:a}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r;var i=n(22),l=o(i)},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),l=n(23),s=o(l),a=100,u=function(){function e(){var t=arguments.length<=0||void 0===arguments[0]?a:arguments[0];r(this,e),this._sectionSize=t,this._cellMetadata=[],this._sections={}}return i(e,[{key:"getCellIndices",value:function(e){var t=e.height,n=e.width,o=e.x,r=e.y,i={};return this.getSections({height:t,width:n,x:o,y:r}).forEach(function(e){return e.getCellIndices().forEach(function(e){i[e]=e})}),Object.keys(i).map(function(e){return i[e]})}},{key:"getCellMetadata",value:function(e){var t=e.index;return this._cellMetadata[t]}},{key:"getSections",value:function(e){for(var t=e.height,n=e.width,o=e.x,r=e.y,i=Math.floor(o/this._sectionSize),l=Math.floor((o+n-1)/this._sectionSize),a=Math.floor(r/this._sectionSize),u=Math.floor((r+t-1)/this._sectionSize),c=[],d=i;l>=d;d++)for(var f=a;u>=f;f++){var p=d+"."+f;this._sections[p]||(this._sections[p]=new s["default"]({height:this._sectionSize,width:this._sectionSize,x:d*this._sectionSize,y:f*this._sectionSize})),c.push(this._sections[p])}return c}},{key:"getTotalSectionCount",value:function(){return Object.keys(this._sections).length}},{key:"toString",value:function(){var e=this;return Object.keys(this._sections).map(function(t){return e._sections[t].toString()})}},{key:"registerCell",value:function(e){var t=e.cellMetadatum,n=e.index;this._cellMetadata[n]=t,this.getSections(t).forEach(function(e){return e.addCellIndex({index:n})})}}]),e}();t["default"]=u},function(e,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var o=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),r=function(){function e(t){var o=t.height,r=t.width,i=t.x,l=t.y;n(this,e),this.height=o,this.width=r,this.x=i,this.y=l,this._indexMap={},this._indices=[]}return o(e,[{key:"addCellIndex",value:function(e){var t=e.index;this._indexMap[t]||(this._indexMap[t]=!0,this._indices.push(t))}},{key:"getCellIndices",value:function(){return this._indices}},{key:"toString",value:function(){return this.x+","+this.y+" "+this.width+"x"+this.height}}]),e}();t["default"]=r},function(e,t){"use strict";function n(e){var t=e.align,n=void 0===t?"auto":t,o=e.cellOffset,r=e.cellSize,i=e.containerSize,l=e.currentOffset,s=o,a=s-i+r;switch(n){case"start":return s;case"end":return a;case"center":return s-(i-r)/2;default:return Math.max(a,Math.min(s,l))}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.ColumnSizer=t["default"]=void 0;var r=n(26),i=o(r);t["default"]=i["default"],t.ColumnSizer=i["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),a=n(3),u=n(4),c=o(u),d=n(27),f=o(d),p=function(e){function t(e,n){r(this,t);var o=i(this,Object.getPrototypeOf(t).call(this,e,n));return o._registerChild=o._registerChild.bind(o),o}return l(t,e),s(t,[{key:"componentDidUpdate",value:function(e,t){var n=this.props,o=n.columnMaxWidth,r=n.columnMinWidth,i=n.columnCount,l=n.width;o===e.columnMaxWidth&&r===e.columnMinWidth&&i===e.columnCount&&l===e.width||this._registeredChild&&this._registeredChild.recomputeGridSize()}},{key:"render",value:function(){var e=this.props,t=e.children,n=e.columnMaxWidth,o=e.columnMinWidth,r=e.columnCount,i=e.width,l=o||1,s=n?Math.min(n,i):i,a=i/r;a=Math.max(l,a),a=Math.min(s,a),a=Math.floor(a);var u=Math.min(i,a*r);return t({adjustedWidth:u,getColumnWidth:function(){return a},registerChild:this._registerChild})}},{key:"shouldComponentUpdate",value:function(e,t){return(0,c["default"])(this,e,t)}},{key:"_registerChild",value:function(e){if(null!==e&&!(e instanceof f["default"]))throw Error("Unexpected child type registered; only Grid children are supported.");this._registeredChild=e,this._registeredChild&&this._registeredChild.recomputeGridSize()}}]),t}(a.Component);p.propTypes={children:a.PropTypes.func.isRequired,columnMaxWidth:a.PropTypes.number,columnMinWidth:a.PropTypes.number,columnCount:a.PropTypes.number.isRequired,width:a.PropTypes.number.isRequired},t["default"]=p},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.defaultCellRangeRenderer=t.Grid=t["default"]=void 0;var r=n(28),i=o(r),l=n(34),s=o(l);t["default"]=i["default"],t.Grid=i["default"],t.defaultCellRangeRenderer=s["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},a=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),u=n(3),c=o(u),d=n(14),f=o(d),p=n(29),h=o(p),y=n(30),_=o(y),m=n(15),v=o(m),S=n(32),g=o(S),b=n(16),w=o(b),T=n(18),C=o(T),P=n(4),x=o(P),R=n(33),z=o(R),O=n(34),M=o(O),I=150,k={OBSERVED:"observed",REQUESTED:"requested"},A=function(e){function t(e,n){r(this,t);var o=i(this,Object.getPrototypeOf(t).call(this,e,n));return o.state={isScrolling:!1,scrollLeft:0,scrollTop:0},o._onGridRenderedMemoizer=(0,v["default"])(),o._onScrollMemoizer=(0,v["default"])(!1),o._enablePointerEventsAfterDelayCallback=o._enablePointerEventsAfterDelayCallback.bind(o),o._invokeOnGridRenderedHelper=o._invokeOnGridRenderedHelper.bind(o),o._onScroll=o._onScroll.bind(o),o._setNextStateCallback=o._setNextStateCallback.bind(o),o._updateScrollLeftForScrollToColumn=o._updateScrollLeftForScrollToColumn.bind(o),o._updateScrollTopForScrollToRow=o._updateScrollTopForScrollToRow.bind(o),o._columnWidthGetter=o._wrapSizeGetter(e.columnWidth),o._rowHeightGetter=o._wrapSizeGetter(e.rowHeight),o._columnSizeAndPositionManager=new _["default"]({cellCount:e.columnCount,cellSizeGetter:function(e){return o._columnWidthGetter(e)},estimatedCellSize:o._getEstimatedColumnSize(e)}),o._rowSizeAndPositionManager=new _["default"]({cellCount:e.rowCount,cellSizeGetter:function(e){return o._rowHeightGetter(e)},estimatedCellSize:o._getEstimatedRowSize(e)}),o._cellCache={},o}return l(t,e),a(t,[{key:"measureAllCells",value:function(){var e=this.props,t=e.columnCount,n=e.rowCount;this._columnSizeAndPositionManager.getSizeAndPositionOfCell(t-1),this._rowSizeAndPositionManager.getSizeAndPositionOfCell(n-1)}},{key:"recomputeGridSize",value:function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.columnIndex,n=void 0===t?0:t,o=e.rowIndex,r=void 0===o?0:o;this._columnSizeAndPositionManager.resetCell(n),this._rowSizeAndPositionManager.resetCell(r),this.forceUpdate()}},{key:"componentDidMount",value:function(){var e=this.props,t=e.scrollLeft,n=e.scrollToColumn,o=e.scrollTop,r=e.scrollToRow;this._scrollbarSizeMeasured||(this._scrollbarSize=(0,w["default"])(),this._scrollbarSizeMeasured=!0,this.setState({})),(t>=0||o>=0)&&this._setScrollPosition({scrollLeft:t,scrollTop:o}),(n>=0||r>=0)&&(this._updateScrollLeftForScrollToColumn(),this._updateScrollTopForScrollToRow()),this._invokeOnGridRenderedHelper(),this._invokeOnScrollMemoizer({scrollLeft:t||0,scrollTop:o||0,totalColumnsWidth:this._columnSizeAndPositionManager.getTotalSize(),totalRowsHeight:this._rowSizeAndPositionManager.getTotalSize()})}},{key:"componentDidUpdate",value:function(e,t){var n=this,o=this.props,r=o.autoHeight,i=o.height,l=o.scrollToAlignment,a=o.scrollToColumn,u=o.scrollToRow,c=o.width,d=this.state,f=d.scrollLeft,p=d.scrollPositionChangeReason,h=d.scrollTop;p===k.REQUESTED&&(f>=0&&f!==t.scrollLeft&&f!==this._scrollingContainer.scrollLeft&&(this._scrollingContainer.scrollLeft=f),!r&&h>=0&&h!==t.scrollTop&&h!==this._scrollingContainer.scrollTop&&(this._scrollingContainer.scrollTop=h)),(0,z["default"])({cellSizeAndPositionManager:this._columnSizeAndPositionManager,previousCellsCount:e.columnCount,previousCellSize:e.columnWidth,previousScrollToAlignment:e.scrollToAlignment,previousScrollToIndex:e.scrollToColumn,previousSize:e.width,scrollOffset:f,scrollToAlignment:l,scrollToIndex:a,size:c,updateScrollIndexCallback:function(e){return n._updateScrollLeftForScrollToColumn(s({},n.props,{scrollToColumn:e}))}}),(0,z["default"])({cellSizeAndPositionManager:this._rowSizeAndPositionManager,previousCellsCount:e.rowCount,previousCellSize:e.rowHeight,previousScrollToAlignment:e.scrollToAlignment,previousScrollToIndex:e.scrollToRow,previousSize:e.height,scrollOffset:h,scrollToAlignment:l,scrollToIndex:u,size:i,updateScrollIndexCallback:function(e){return n._updateScrollTopForScrollToRow(s({},n.props,{scrollToRow:e}))}}),this._invokeOnGridRenderedHelper()}},{key:"componentWillMount",value:function(){this._scrollbarSize=(0,w["default"])(),void 0===this._scrollbarSize?(this._scrollbarSizeMeasured=!1,this._scrollbarSize=0):this._scrollbarSizeMeasured=!0,this._calculateChildrenToRender()}},{key:"componentWillUnmount",value:function(){this._disablePointerEventsTimeoutId&&clearTimeout(this._disablePointerEventsTimeoutId),this._setNextStateAnimationFrameId&&C["default"].cancel(this._setNextStateAnimationFrameId)}},{key:"componentWillUpdate",value:function(e,t){var n=this;0===e.columnCount&&0!==t.scrollLeft||0===e.rowCount&&0!==t.scrollTop?this._setScrollPosition({scrollLeft:0,scrollTop:0}):e.scrollLeft===this.props.scrollLeft&&e.scrollTop===this.props.scrollTop||this._setScrollPosition({scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}),this._columnWidthGetter=this._wrapSizeGetter(e.columnWidth),this._rowHeightGetter=this._wrapSizeGetter(e.rowHeight),this._columnSizeAndPositionManager.configure({cellCount:e.columnCount,estimatedCellSize:this._getEstimatedColumnSize(e)}),this._rowSizeAndPositionManager.configure({cellCount:e.rowCount,estimatedCellSize:this._getEstimatedRowSize(e)}),(0,h["default"])({cellCount:this.props.columnCount,cellSize:this.props.columnWidth,computeMetadataCallback:function(){return n._columnSizeAndPositionManager.resetCell(0)},computeMetadataCallbackProps:e,nextCellsCount:e.columnCount,nextCellSize:e.columnWidth,nextScrollToIndex:e.scrollToColumn,scrollToIndex:this.props.scrollToColumn,updateScrollOffsetForScrollToIndex:function(){return n._updateScrollLeftForScrollToColumn(e,t)}}),(0,h["default"])({cellCount:this.props.rowCount,cellSize:this.props.rowHeight,computeMetadataCallback:function(){return n._rowSizeAndPositionManager.resetCell(0)},computeMetadataCallbackProps:e,nextCellsCount:e.rowCount,nextCellSize:e.rowHeight,nextScrollToIndex:e.scrollToRow,scrollToIndex:this.props.scrollToRow,updateScrollOffsetForScrollToIndex:function(){return n._updateScrollTopForScrollToRow(e,t)}}),this._calculateChildrenToRender(e,t)}},{key:"render",value:function(){var e=this,t=this.props,n=t.autoContainerWidth,o=t.autoHeight,r=t.className,i=t.height,l=t.noContentRenderer,a=t.style,u=t.tabIndex,d=t.width,p=this.state.isScrolling,h={height:o?"auto":i,width:d},y=this._columnSizeAndPositionManager.getTotalSize(),_=this._rowSizeAndPositionManager.getTotalSize(),m=_>i?this._scrollbarSize:0,v=y>d?this._scrollbarSize:0;h.overflowX=d>=y+m?"hidden":"auto",h.overflowY=i>=_+v?"hidden":"auto";var S=this._childrenToDisplay,g=0===S.length&&i>0&&d>0;return c["default"].createElement("div",{ref:function(t){e._scrollingContainer=t},"aria-label":this.props["aria-label"],className:(0,f["default"])("Grid",r),onScroll:this._onScroll,role:"grid",style:s({},h,a),tabIndex:u},S.length>0&&c["default"].createElement("div",{className:"Grid__innerScrollContainer",style:{width:n?"auto":y,height:_,maxWidth:y,maxHeight:_,pointerEvents:p?"none":"auto"}},S),g&&l())}},{key:"shouldComponentUpdate",value:function(e,t){return(0,x["default"])(this,e,t)}},{key:"_calculateChildrenToRender",value:function(){var e=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0],t=arguments.length<=1||void 0===arguments[1]?this.state:arguments[1],n=e.cellClassName,o=e.cellRenderer,r=e.cellRangeRenderer,i=e.cellStyle,l=e.columnCount,s=e.height,a=e.overscanColumnCount,u=e.overscanRowCount,c=e.rowCount,d=e.width,f=t.isScrolling,p=t.scrollLeft,h=t.scrollTop;if(this._childrenToDisplay=[],s>0&&d>0){var y=this._columnSizeAndPositionManager.getVisibleCellRange({containerSize:d,offset:p}),_=this._rowSizeAndPositionManager.getVisibleCellRange({containerSize:s,offset:h}),m=this._columnSizeAndPositionManager.getOffsetAdjustment({containerSize:d,offset:p}),v=this._rowSizeAndPositionManager.getOffsetAdjustment({containerSize:s,offset:h});this._renderedColumnStartIndex=y.start,this._renderedColumnStopIndex=y.stop,this._renderedRowStartIndex=_.start,this._renderedRowStopIndex=_.stop;var S=(0,g["default"])({cellCount:l,overscanCellsCount:a,startIndex:this._renderedColumnStartIndex,stopIndex:this._renderedColumnStopIndex}),b=(0,g["default"])({cellCount:c,overscanCellsCount:u,startIndex:this._renderedRowStartIndex,stopIndex:this._renderedRowStopIndex});this._columnStartIndex=S.overscanStartIndex,this._columnStopIndex=S.overscanStopIndex,this._rowStartIndex=b.overscanStartIndex,this._rowStopIndex=b.overscanStopIndex,this._childrenToDisplay=r({cellCache:this._cellCache,cellClassName:this._wrapCellClassNameGetter(n),cellRenderer:o,cellStyle:this._wrapCellStyleGetter(i),columnSizeAndPositionManager:this._columnSizeAndPositionManager,columnStartIndex:this._columnStartIndex,columnStopIndex:this._columnStopIndex,horizontalOffsetAdjustment:m,isScrolling:f,rowSizeAndPositionManager:this._rowSizeAndPositionManager,rowStartIndex:this._rowStartIndex,rowStopIndex:this._rowStopIndex,scrollLeft:p,scrollTop:h,verticalOffsetAdjustment:v})}}},{key:"_enablePointerEventsAfterDelay",value:function(){this._disablePointerEventsTimeoutId&&clearTimeout(this._disablePointerEventsTimeoutId),this._disablePointerEventsTimeoutId=setTimeout(this._enablePointerEventsAfterDelayCallback,I)}},{key:"_enablePointerEventsAfterDelayCallback",value:function(){this._disablePointerEventsTimeoutId=null,this._cellCache={},this.setState({isScrolling:!1})}},{key:"_getEstimatedColumnSize",value:function(e){return"number"==typeof e.columnWidth?e.columnWidth:e.estimatedColumnSize}},{key:"_getEstimatedRowSize",value:function(e){return"number"==typeof e.rowHeight?e.rowHeight:e.estimatedRowSize}},{key:"_invokeOnGridRenderedHelper",value:function(){var e=this.props.onSectionRendered;this._onGridRenderedMemoizer({callback:e,indices:{columnOverscanStartIndex:this._columnStartIndex,columnOverscanStopIndex:this._columnStopIndex,columnStartIndex:this._renderedColumnStartIndex,columnStopIndex:this._renderedColumnStopIndex,rowOverscanStartIndex:this._rowStartIndex,rowOverscanStopIndex:this._rowStopIndex,rowStartIndex:this._renderedRowStartIndex,rowStopIndex:this._renderedRowStopIndex}})}},{key:"_invokeOnScrollMemoizer",value:function(e){var t=this,n=e.scrollLeft,o=e.scrollTop,r=e.totalColumnsWidth,i=e.totalRowsHeight;this._onScrollMemoizer({callback:function(e){var n=e.scrollLeft,o=e.scrollTop,l=t.props,s=l.height,a=l.onScroll,u=l.width;a({clientHeight:s,clientWidth:u,scrollHeight:i,scrollLeft:n,scrollTop:o,scrollWidth:r})},indices:{scrollLeft:n,scrollTop:o}})}},{key:"_setNextState",value:function(e){this._nextState=e,this._setNextStateAnimationFrameId||(this._setNextStateAnimationFrameId=(0,C["default"])(this._setNextStateCallback))}},{key:"_setNextStateCallback",value:function(){var e=this._nextState;this._setNextStateAnimationFrameId=null,this._nextState=null,this.setState(e)}},{key:"_setScrollPosition",value:function(e){var t=e.scrollLeft,n=e.scrollTop,o={scrollPositionChangeReason:k.REQUESTED};t>=0&&(o.scrollLeft=t),n>=0&&(o.scrollTop=n),(t>=0&&t!==this.state.scrollLeft||n>=0&&n!==this.state.scrollTop)&&this.setState(o)}},{key:"_wrapCellClassNameGetter",value:function(e){return this._wrapPropertyGetter(e)}},{key:"_wrapCellStyleGetter",value:function(e){return this._wrapPropertyGetter(e)}},{key:"_wrapPropertyGetter",value:function(e){return e instanceof Function?e:function(){return e}}},{key:"_wrapSizeGetter",value:function(e){return this._wrapPropertyGetter(e)}},{key:"_updateScrollLeftForScrollToColumn",value:function(){var e=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0],t=arguments.length<=1||void 0===arguments[1]?this.state:arguments[1],n=e.columnCount,o=e.scrollToAlignment,r=e.scrollToColumn,i=e.width,l=t.scrollLeft;if(r>=0&&n>0){var s=Math.max(0,Math.min(n-1,r)),a=this._columnSizeAndPositionManager.getUpdatedOffsetForIndex({align:o,containerSize:i,currentOffset:l,targetIndex:s});l!==a&&this._setScrollPosition({scrollLeft:a})}}},{key:"_updateScrollTopForScrollToRow",value:function(){var e=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0],t=arguments.length<=1||void 0===arguments[1]?this.state:arguments[1],n=e.height,o=e.rowCount,r=e.scrollToAlignment,i=e.scrollToRow,l=t.scrollTop;if(i>=0&&o>0){var s=Math.max(0,Math.min(o-1,i)),a=this._rowSizeAndPositionManager.getUpdatedOffsetForIndex({align:r,containerSize:n,currentOffset:l,targetIndex:s});l!==a&&this._setScrollPosition({scrollTop:a})}}},{key:"_onScroll",value:function(e){if(e.target===this._scrollingContainer){this._enablePointerEventsAfterDelay();var t=this.props,n=t.height,o=t.width,r=this._scrollbarSize,i=this._rowSizeAndPositionManager.getTotalSize(),l=this._columnSizeAndPositionManager.getTotalSize(),s=Math.min(Math.max(0,l-o+r),e.target.scrollLeft),a=Math.min(Math.max(0,i-n+r),e.target.scrollTop);if(this.state.scrollLeft!==s||this.state.scrollTop!==a){var u=e.cancelable?k.OBSERVED:k.REQUESTED;this.state.isScrolling||this.setState({isScrolling:!0}),this._setNextState({isScrolling:!0,scrollLeft:s,scrollPositionChangeReason:u,scrollTop:a})}this._invokeOnScrollMemoizer({scrollLeft:s,scrollTop:a,totalColumnsWidth:l,totalRowsHeight:i})}}}]),t}(u.Component);A.propTypes={"aria-label":u.PropTypes.string,autoContainerWidth:u.PropTypes.bool,autoHeight:u.PropTypes.bool,cellClassName:u.PropTypes.oneOfType([u.PropTypes.string,u.PropTypes.func]),cellStyle:u.PropTypes.oneOfType([u.PropTypes.object,u.PropTypes.func]),cellRenderer:u.PropTypes.func.isRequired,cellRangeRenderer:u.PropTypes.func.isRequired,className:u.PropTypes.string,columnCount:u.PropTypes.number.isRequired,columnWidth:u.PropTypes.oneOfType([u.PropTypes.number,u.PropTypes.func]).isRequired,estimatedColumnSize:u.PropTypes.number.isRequired,estimatedRowSize:u.PropTypes.number.isRequired,height:u.PropTypes.number.isRequired,noContentRenderer:u.PropTypes.func.isRequired,onScroll:u.PropTypes.func.isRequired,onSectionRendered:u.PropTypes.func.isRequired,overscanColumnCount:u.PropTypes.number.isRequired,overscanRowCount:u.PropTypes.number.isRequired,rowHeight:u.PropTypes.oneOfType([u.PropTypes.number,u.PropTypes.func]).isRequired,rowCount:u.PropTypes.number.isRequired,scrollLeft:u.PropTypes.number,scrollToAlignment:u.PropTypes.oneOf(["auto","end","start","center"]).isRequired,scrollToColumn:u.PropTypes.number,scrollTop:u.PropTypes.number,scrollToRow:u.PropTypes.number,style:u.PropTypes.object,tabIndex:u.PropTypes.number,width:u.PropTypes.number.isRequired},A.defaultProps={"aria-label":"grid",cellStyle:{},cellRangeRenderer:M["default"],estimatedColumnSize:100,estimatedRowSize:30,noContentRenderer:function(){return null},onScroll:function(){return null},onSectionRendered:function(){return null},overscanColumnCount:0,overscanRowCount:10,scrollToAlignment:"auto",style:{},tabIndex:0},t["default"]=A},function(e,t){"use strict";function n(e){var t=e.cellCount,n=e.cellSize,o=e.computeMetadataCallback,r=e.computeMetadataCallbackProps,i=e.nextCellsCount,l=e.nextCellSize,s=e.nextScrollToIndex,a=e.scrollToIndex,u=e.updateScrollOffsetForScrollToIndex;t===i&&("number"!=typeof n&&"number"!=typeof l||n===l)||(o(r),a>=0&&a===s&&u())}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){var n={};for(var o in e)t.indexOf(o)>=0||Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o]);return n}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_MAX_SCROLL_SIZE=void 0;var l=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),s=n(31),a=o(s),u=t.DEFAULT_MAX_SCROLL_SIZE=1e7,c=function(){function e(t){var n=t.maxScrollSize,o=void 0===n?u:n,l=r(t,["maxScrollSize"]);i(this,e),this._cellSizeAndPositionManager=new a["default"](l),this._maxScrollSize=o}return l(e,[{key:"configure",value:function(e){this._cellSizeAndPositionManager.configure(e)}},{key:"getCellCount",value:function(){return this._cellSizeAndPositionManager.getCellCount()}},{key:"getEstimatedCellSize",value:function(){return this._cellSizeAndPositionManager.getEstimatedCellSize()}},{key:"getLastMeasuredIndex",value:function(){return this._cellSizeAndPositionManager.getLastMeasuredIndex()}},{key:"getOffsetAdjustment",value:function(e){var t=e.containerSize,n=e.offset,o=this._cellSizeAndPositionManager.getTotalSize(),r=this.getTotalSize(),i=this._getOffsetPercentage({containerSize:t,offset:n,totalSize:r});return Math.round(i*(r-o))}},{key:"getSizeAndPositionOfCell",value:function(e){return this._cellSizeAndPositionManager.getSizeAndPositionOfCell(e)}},{key:"getSizeAndPositionOfLastMeasuredCell",value:function(){return this._cellSizeAndPositionManager.getSizeAndPositionOfLastMeasuredCell()}},{key:"getTotalSize",value:function(){return Math.min(this._maxScrollSize,this._cellSizeAndPositionManager.getTotalSize())}},{key:"getUpdatedOffsetForIndex",value:function(e){var t=e.align,n=void 0===t?"auto":t,o=e.containerSize,r=e.currentOffset,i=e.targetIndex,l=e.totalSize;r=this._safeOffsetToOffset({containerSize:o,offset:r});var s=this._cellSizeAndPositionManager.getUpdatedOffsetForIndex({align:n,containerSize:o,currentOffset:r,targetIndex:i,totalSize:l});return this._offsetToSafeOffset({containerSize:o,offset:s})}},{key:"getVisibleCellRange",value:function(e){var t=e.containerSize,n=e.offset;return n=this._safeOffsetToOffset({containerSize:t,offset:n}),this._cellSizeAndPositionManager.getVisibleCellRange({containerSize:t,offset:n})}},{key:"resetCell",value:function(e){this._cellSizeAndPositionManager.resetCell(e)}},{key:"_getOffsetPercentage",value:function(e){var t=e.containerSize,n=e.offset,o=e.totalSize;return t>=o?0:n/(o-t)}},{key:"_offsetToSafeOffset",value:function(e){var t=e.containerSize,n=e.offset,o=this._cellSizeAndPositionManager.getTotalSize(),r=this.getTotalSize();if(o===r)return n;var i=this._getOffsetPercentage({containerSize:t,offset:n,totalSize:o});return Math.round(i*(r-t))}},{key:"_safeOffsetToOffset",value:function(e){var t=e.containerSize,n=e.offset,o=this._cellSizeAndPositionManager.getTotalSize(),r=this.getTotalSize();if(o===r)return n;var i=this._getOffsetPercentage({containerSize:t,offset:n,totalSize:r});return Math.round(i*(o-t))}}]),e}();t["default"]=c},function(e,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var o=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),r=function(){function e(t){var o=t.cellCount,r=t.cellSizeGetter,i=t.estimatedCellSize;n(this,e),this._cellSizeGetter=r,this._cellCount=o,this._estimatedCellSize=i,this._cellSizeAndPositionData={},this._lastMeasuredIndex=-1}return o(e,[{key:"configure",value:function(e){var t=e.cellCount,n=e.estimatedCellSize;this._cellCount=t,this._estimatedCellSize=n}},{key:"getCellCount",value:function(){return this._cellCount}},{key:"getEstimatedCellSize",value:function(){return this._estimatedCellSize}},{key:"getLastMeasuredIndex",value:function(){return this._lastMeasuredIndex}},{key:"getSizeAndPositionOfCell",value:function(e){if(0>e||e>=this._cellCount)throw Error("Requested index "+e+" is outside of range 0.."+this._cellCount);if(e>this._lastMeasuredIndex){for(var t=this.getSizeAndPositionOfLastMeasuredCell(),n=t.offset+t.size,o=this._lastMeasuredIndex+1;e>=o;o++){var r=this._cellSizeGetter({index:o});if(null==r||isNaN(r))throw Error("Invalid size returned for cell "+o+" of value "+r);this._cellSizeAndPositionData[o]={offset:n,size:r},n+=r}this._lastMeasuredIndex=e}return this._cellSizeAndPositionData[e]}},{key:"getSizeAndPositionOfLastMeasuredCell",value:function(){return this._lastMeasuredIndex>=0?this._cellSizeAndPositionData[this._lastMeasuredIndex]:{offset:0,size:0}}},{key:"getTotalSize",value:function(){var e=this.getSizeAndPositionOfLastMeasuredCell();return e.offset+e.size+(this._cellCount-this._lastMeasuredIndex-1)*this._estimatedCellSize}},{key:"getUpdatedOffsetForIndex",value:function(e){var t=e.align,n=void 0===t?"auto":t,o=e.containerSize,r=e.currentOffset,i=e.targetIndex,l=this.getSizeAndPositionOfCell(i),s=l.offset,a=s-o+l.size,u=void 0;switch(n){case"start":u=s;break;case"end":u=a;break;case"center":u=s-(o-l.size)/2;break;default:u=Math.max(a,Math.min(s,r))}var c=this.getTotalSize();return Math.max(0,Math.min(c-o,u))}},{key:"getVisibleCellRange",value:function(e){var t=e.containerSize,n=e.offset,o=this.getTotalSize();if(0===o)return{};var r=n+t,i=this._findNearestCell(n),l=this.getSizeAndPositionOfCell(i);n=l.offset+l.size;for(var s=i;r>n&&s<this._cellCount-1;)s++,n+=this.getSizeAndPositionOfCell(s).size;return{start:i,stop:s}}},{key:"resetCell",value:function(e){this._lastMeasuredIndex=Math.min(this._lastMeasuredIndex,e-1)}},{key:"_binarySearch",value:function(e){for(var t=e.high,n=e.low,o=e.offset,r=void 0,i=void 0;t>=n;){if(r=n+Math.floor((t-n)/2),i=this.getSizeAndPositionOfCell(r).offset,i===o)return r;o>i?n=r+1:i>o&&(t=r-1)}return n>0?n-1:void 0}},{key:"_exponentialSearch",value:function(e){for(var t=e.index,n=e.offset,o=1;t<this._cellCount&&this.getSizeAndPositionOfCell(t).offset<n;)t+=o,o*=2;return this._binarySearch({high:Math.min(t,this._cellCount-1),low:Math.floor(t/2),offset:n})}},{key:"_findNearestCell",value:function(e){if(isNaN(e))throw Error("Invalid offset "+e+" specified");e=Math.max(0,e);var t=this.getSizeAndPositionOfLastMeasuredCell(),n=Math.max(0,this._lastMeasuredIndex);return t.offset>=e?this._binarySearch({high:n,low:0,offset:e}):this._exponentialSearch({index:n,offset:e})}}]),e}();t["default"]=r},function(e,t){"use strict";function n(e){var t=e.cellCount,n=e.overscanCellsCount,o=e.startIndex,r=e.stopIndex;return{overscanStartIndex:Math.max(0,o-n),overscanStopIndex:Math.min(t-1,r+n)}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n},function(e,t){"use strict";function n(e){var t=e.cellSize,n=e.cellSizeAndPositionManager,o=e.previousCellsCount,r=e.previousCellSize,i=e.previousScrollToAlignment,l=e.previousScrollToIndex,s=e.previousSize,a=e.scrollOffset,u=e.scrollToAlignment,c=e.scrollToIndex,d=e.size,f=e.updateScrollIndexCallback,p=n.getCellCount(),h=c>=0&&p>c,y=d!==s||!r||"number"==typeof t&&t!==r;if(h&&(y||u!==i||c!==l))f(c);else if(!h&&p>0&&(s>d||o>p)){c=p-1;var _=n.getUpdatedOffsetForIndex({containerSize:d,currentOffset:a,targetIndex:c});a>_&&f(p-1)}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){for(var t=e.cellCache,n=e.cellClassName,o=e.cellRenderer,r=e.cellStyle,l=e.columnSizeAndPositionManager,a=e.columnStartIndex,c=e.columnStopIndex,d=e.horizontalOffsetAdjustment,f=e.isScrolling,p=e.rowSizeAndPositionManager,h=e.rowStartIndex,y=e.rowStopIndex,_=(e.scrollLeft,e.scrollTop,e.verticalOffsetAdjustment),m=[],v=h;y>=v;v++)for(var S=p.getSizeAndPositionOfCell(v),g=a;c>=g;g++){var b=l.getSizeAndPositionOfCell(g),w=v+"-"+g,T=r({rowIndex:v,columnIndex:g}),C=void 0;if(f?(t[w]||(t[w]=o({columnIndex:g,isScrolling:f,rowIndex:v})),C=t[w]):C=o({columnIndex:g,isScrolling:f,rowIndex:v}),null!=C&&C!==!1){var P=n({columnIndex:g,rowIndex:v}),x=s["default"].createElement("div",{key:w,className:(0,u["default"])("Grid__cell",P),style:i({height:S.size,left:b.offset+d,top:S.offset+_,width:b.size},T)},C);m.push(x)}}return m}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e};t["default"]=r;var l=n(3),s=o(l),a=n(14),u=o(a)},function(e,t,n){
"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.SortIndicator=t.SortDirection=t.FlexColumn=t.FlexTable=t.defaultRowRenderer=t.defaultHeaderRenderer=t.defaultCellRenderer=t.defaultCellDataGetter=t["default"]=void 0;var r=n(36),i=o(r),l=n(42),s=o(l),a=n(41),u=o(a),c=n(38),d=o(c),f=n(43),p=o(f),h=n(37),y=o(h),_=n(40),m=o(_),v=n(39),S=o(v);t["default"]=i["default"],t.defaultCellDataGetter=s["default"],t.defaultCellRenderer=u["default"],t.defaultHeaderRenderer=d["default"],t.defaultRowRenderer=p["default"],t.FlexTable=i["default"],t.FlexColumn=y["default"],t.SortDirection=m["default"],t.SortIndicator=S["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},a=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),u=n(14),c=o(u),d=n(37),f=o(d),p=n(3),h=o(p),y=n(10),_=n(4),m=o(_),v=n(27),S=o(v),g=n(43),b=o(g),w=n(40),T=o(w),C=function(e){function t(e){r(this,t);var n=i(this,Object.getPrototypeOf(t).call(this,e));return n.state={scrollbarWidth:0},n._cellClassName=n._cellClassName.bind(n),n._cellStyle=n._cellStyle.bind(n),n._createColumn=n._createColumn.bind(n),n._createRow=n._createRow.bind(n),n._onScroll=n._onScroll.bind(n),n._onSectionRendered=n._onSectionRendered.bind(n),n}return l(t,e),a(t,[{key:"forceUpdateGrid",value:function(){this.Grid.forceUpdate()}},{key:"measureAllRows",value:function(){this.Grid.measureAllCells()}},{key:"recomputeRowHeights",value:function(){var e=arguments.length<=0||void 0===arguments[0]?0:arguments[0];this.Grid.recomputeGridSize({rowIndex:e}),this.forceUpdateGrid()}},{key:"componentDidMount",value:function(){this._setScrollbarWidth()}},{key:"componentDidUpdate",value:function(){this._setScrollbarWidth()}},{key:"render",value:function(){var e=this,t=this.props,n=t.children,o=t.className,r=t.disableHeader,i=t.gridClassName,l=t.gridStyle,a=t.headerHeight,u=t.height,d=t.noRowsRenderer,f=t.rowClassName,p=t.rowStyle,y=t.scrollToIndex,_=t.style,m=t.width,v=this.state.scrollbarWidth,g=u-a,b=f instanceof Function?f({index:-1}):f,w=p instanceof Function?p({index:-1}):p;return this._cachedColumnStyles=[],h["default"].Children.toArray(n).forEach(function(t,n){e._cachedColumnStyles[n]=e._getFlexStyleForColumn(t,t.props.style)}),h["default"].createElement("div",{className:(0,c["default"])("FlexTable",o),style:_},!r&&h["default"].createElement("div",{className:(0,c["default"])("FlexTable__headerRow",b),style:s({},w,{height:a,paddingRight:v,width:m})},this._getRenderedHeaderRow()),h["default"].createElement(S["default"],s({},this.props,{autoContainerWidth:!0,className:(0,c["default"])("FlexTable__Grid",i),cellClassName:this._cellClassName,cellRenderer:this._createRow,cellStyle:this._cellStyle,columnWidth:m,columnCount:1,height:g,noContentRenderer:d,onScroll:this._onScroll,onSectionRendered:this._onSectionRendered,ref:function(t){e.Grid=t},scrollbarWidth:v,scrollToRow:y,style:l})))}},{key:"shouldComponentUpdate",value:function(e,t){return(0,m["default"])(this,e,t)}},{key:"_cellClassName",value:function(e){var t=e.rowIndex,n=this.props.rowWrapperClassName;return n instanceof Function?n({index:t-1}):n}},{key:"_cellStyle",value:function(e){var t=e.rowIndex,n=this.props.rowWrapperStyle;return n instanceof Function?n({index:t-1}):n}},{key:"_createColumn",value:function(e){var t=e.column,n=e.columnIndex,o=e.isScrolling,r=e.rowData,i=e.rowIndex,l=t.props,s=l.cellDataGetter,a=l.cellRenderer,u=l.className,d=l.columnData,f=l.dataKey,p=s({columnData:d,dataKey:f,rowData:r}),y=a({cellData:p,columnData:d,dataKey:f,isScrolling:o,rowData:r,rowIndex:i}),_=this._cachedColumnStyles[n],m="string"==typeof y?y:null;return h["default"].createElement("div",{key:"Row"+i+"-Col"+n,className:(0,c["default"])("FlexTable__rowColumn",u),style:_,title:m},y)}},{key:"_createHeader",value:function(e){var t=e.column,n=e.index,o=this.props,r=o.headerClassName,i=o.headerStyle,l=o.onHeaderClick,a=o.sort,u=o.sortBy,d=o.sortDirection,f=t.props,p=f.dataKey,y=f.disableSort,_=f.headerRenderer,m=f.label,v=f.columnData,S=!y&&a,g=(0,c["default"])("FlexTable__headerColumn",r,t.props.headerClassName,{FlexTable__sortableHeaderColumn:S}),b=this._getFlexStyleForColumn(t,i),w=_({columnData:v,dataKey:p,disableSort:y,label:m,sortBy:u,sortDirection:d}),C={};return(S||l)&&!function(){var e=u!==p||d===T["default"].DESC?T["default"].ASC:T["default"].DESC,n=function(){S&&a({sortBy:p,sortDirection:e}),l&&l({columnData:v,dataKey:p})},o=function(e){"Enter"!==e.key&&" "!==e.key||n()};C["aria-label"]=t.props["aria-label"]||m||p,C.role="rowheader",C.tabIndex=0,C.onClick=n,C.onKeyDown=o}(),h["default"].createElement("div",s({},C,{key:"Header-Col"+n,className:g,style:b}),w)}},{key:"_createRow",value:function(e){var t=this,n=e.rowIndex,o=e.isScrolling,r=this.props,i=r.children,l=r.onRowClick,a=r.onRowDoubleClick,u=r.onRowMouseOver,d=r.onRowMouseOut,f=r.rowClassName,p=r.rowGetter,y=r.rowRenderer,_=r.rowStyle,m=this.state.scrollbarWidth,v=f instanceof Function?f({index:n}):f,S=_ instanceof Function?_({index:n}):_,g=p({index:n}),b=h["default"].Children.toArray(i).map(function(e,r){return t._createColumn({column:e,columnIndex:r,isScrolling:o,rowData:g,rowIndex:n,scrollbarWidth:m})}),w=(0,c["default"])("FlexTable__row",v),T=s({},S,{height:this._getRowHeight(n),paddingRight:m});return y({className:w,columns:b,index:n,isScrolling:o,onRowClick:l,onRowDoubleClick:a,onRowMouseOver:u,onRowMouseOut:d,rowData:g,style:T})}},{key:"_getFlexStyleForColumn",value:function(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=e.props.flexGrow+" "+e.props.flexShrink+" "+e.props.width+"px",o=s({},t,{flex:n,msFlex:n,WebkitFlex:n});return e.props.maxWidth&&(o.maxWidth=e.props.maxWidth),e.props.minWidth&&(o.minWidth=e.props.minWidth),o}},{key:"_getRenderedHeaderRow",value:function(){var e=this,t=this.props,n=t.children,o=t.disableHeader,r=o?[]:h["default"].Children.toArray(n);return r.map(function(t,n){return e._createHeader({column:t,index:n})})}},{key:"_getRowHeight",value:function(e){var t=this.props.rowHeight;return t instanceof Function?t({index:e}):t}},{key:"_onScroll",value:function(e){var t=e.clientHeight,n=e.scrollHeight,o=e.scrollTop,r=this.props.onScroll;r({clientHeight:t,scrollHeight:n,scrollTop:o})}},{key:"_onSectionRendered",value:function(e){var t=e.rowOverscanStartIndex,n=e.rowOverscanStopIndex,o=e.rowStartIndex,r=e.rowStopIndex,i=this.props.onRowsRendered;i({overscanStartIndex:t,overscanStopIndex:n,startIndex:o,stopIndex:r})}},{key:"_setScrollbarWidth",value:function(){var e=(0,y.findDOMNode)(this.Grid),t=e.clientWidth||0,n=e.offsetWidth||0,o=n-t;this.setState({scrollbarWidth:o})}}]),t}(p.Component);C.propTypes={"aria-label":p.PropTypes.string,autoHeight:p.PropTypes.bool,children:function P(e,t,n){for(var P=h["default"].Children.toArray(e.children),o=0;o<P.length;o++)if(P[o].type!==f["default"])return new Error("FlexTable only accepts children of type FlexColumn")},className:p.PropTypes.string,disableHeader:p.PropTypes.bool,estimatedRowSize:p.PropTypes.number.isRequired,gridClassName:p.PropTypes.string,gridStyle:p.PropTypes.object,headerClassName:p.PropTypes.string,headerHeight:p.PropTypes.number.isRequired,height:p.PropTypes.number.isRequired,noRowsRenderer:p.PropTypes.func,onHeaderClick:p.PropTypes.func,headerStyle:p.PropTypes.object,onRowClick:p.PropTypes.func,onRowDoubleClick:p.PropTypes.func,onRowMouseOut:p.PropTypes.func,onRowMouseOver:p.PropTypes.func,onRowsRendered:p.PropTypes.func,onScroll:p.PropTypes.func.isRequired,overscanRowCount:p.PropTypes.number.isRequired,rowClassName:p.PropTypes.oneOfType([p.PropTypes.string,p.PropTypes.func]),rowGetter:p.PropTypes.func.isRequired,rowHeight:p.PropTypes.oneOfType([p.PropTypes.number,p.PropTypes.func]).isRequired,rowCount:p.PropTypes.number.isRequired,rowRenderer:p.PropTypes.func,rowStyle:p.PropTypes.oneOfType([p.PropTypes.object,p.PropTypes.func]).isRequired,rowWrapperClassName:p.PropTypes.oneOfType([p.PropTypes.string,p.PropTypes.func]),rowWrapperStyle:p.PropTypes.oneOfType([p.PropTypes.object,p.PropTypes.func]),scrollToAlignment:p.PropTypes.oneOf(["auto","end","start","center"]).isRequired,scrollToIndex:p.PropTypes.number,scrollTop:p.PropTypes.number,sort:p.PropTypes.func,sortBy:p.PropTypes.string,sortDirection:p.PropTypes.oneOf([T["default"].ASC,T["default"].DESC]),style:p.PropTypes.object,tabIndex:p.PropTypes.number,width:p.PropTypes.number.isRequired},C.defaultProps={disableHeader:!1,estimatedRowSize:30,headerHeight:0,headerStyle:{},noRowsRenderer:function(){return null},onRowsRendered:function(){return null},onScroll:function(){return null},overscanRowCount:10,rowRenderer:b["default"],rowStyle:{},scrollToAlignment:"auto",style:{}},t["default"]=C},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=n(3),a=n(38),u=o(a),c=n(41),d=o(c),f=n(42),p=o(f),h=function(e){function t(){return r(this,t),i(this,Object.getPrototypeOf(t).apply(this,arguments))}return l(t,e),t}(s.Component);h.defaultProps={cellDataGetter:p["default"],cellRenderer:d["default"],cellStyle:{},flexGrow:0,flexShrink:1,headerRenderer:u["default"]},h.propTypes={"aria-label":s.PropTypes.string,cellDataGetter:s.PropTypes.func,cellRenderer:s.PropTypes.func,className:s.PropTypes.string,columnData:s.PropTypes.object,dataKey:s.PropTypes.any.isRequired,disableSort:s.PropTypes.bool,flexGrow:s.PropTypes.number,flexShrink:s.PropTypes.number,headerClassName:s.PropTypes.string,headerRenderer:s.PropTypes.func.isRequired,label:s.PropTypes.string,maxWidth:s.PropTypes.number,minWidth:s.PropTypes.number,style:s.PropTypes.object,width:s.PropTypes.number.isRequired},t["default"]=h},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=(e.columnData,e.dataKey),n=(e.disableSort,e.label),o=e.sortBy,r=e.sortDirection,i=o===t,s=[l["default"].createElement("span",{className:"FlexTable__headerTruncatedText",key:"label",title:n},n)];return i&&s.push(l["default"].createElement(a["default"],{key:"SortIndicator",sortDirection:r})),s}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r;var i=n(3),l=o(i),s=n(39),a=o(s)},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=e.sortDirection,n=(0,a["default"])("FlexTable__sortableHeaderIcon",{"FlexTable__sortableHeaderIcon--ASC":t===c["default"].ASC,"FlexTable__sortableHeaderIcon--DESC":t===c["default"].DESC});return l["default"].createElement("svg",{className:n,width:18,height:18,viewBox:"0 0 24 24"},t===c["default"].ASC?l["default"].createElement("path",{d:"M7 14l5-5 5 5z"}):l["default"].createElement("path",{d:"M7 10l5 5 5-5z"}),l["default"].createElement("path",{d:"M0 0h24v24H0z",fill:"none"}))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r;var i=n(3),l=o(i),s=n(14),a=o(s),u=n(40),c=o(u);r.propTypes={sortDirection:i.PropTypes.oneOf([c["default"].ASC,c["default"].DESC])}},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={ASC:"ASC",DESC:"DESC"};t["default"]=n},function(e,t){"use strict";function n(e){var t=e.cellData;return e.cellDataKey,e.columnData,e.rowData,e.rowIndex,null==t?"":String(t)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n},function(e,t){"use strict";function n(e){var t=(e.columnData,e.dataKey),n=e.rowData;return n.get instanceof Function?n.get(t):n[t]}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=e.className,n=e.columns,o=e.index,r=(e.isScrolling,e.onRowClick),l=e.onRowDoubleClick,a=e.onRowMouseOver,u=e.onRowMouseOut,c=(e.rowData,e.style),d={};return(r||l||a||u)&&(d["aria-label"]="row",d.role="row",d.tabIndex=0,r&&(d.onClick=function(){return r({index:o})}),l&&(d.onDoubleClick=function(){return l({index:o})}),u&&(d.onMouseOut=function(){return u({index:o})}),a&&(d.onMouseOver=function(){return a({index:o})})),s["default"].createElement("div",i({},d,{className:t,style:c}),n)}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e};t["default"]=r;var l=n(3),s=o(l)},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.InfiniteLoader=t["default"]=void 0;var r=n(45),i=o(r);t["default"]=i["default"],t.InfiniteLoader=i["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(e){var t=e.lastRenderedStartIndex,n=e.lastRenderedStopIndex,o=e.startIndex,r=e.stopIndex;return!(o>n||t>r)}function a(e){for(var t=e.isRowLoaded,n=e.minimumBatchSize,o=e.rowCount,r=e.startIndex,i=e.stopIndex,l=[],s=null,a=null,u=r;i>=u;u++){var c=t({index:u});c?null!==a&&(l.push({startIndex:s,stopIndex:a}),s=a=null):(a=u,null===s&&(s=u))}if(null!==a){for(var d=Math.min(Math.max(a,s+n-1),o-1),f=a+1;d>=f&&!t({index:f});f++)a=f;l.push({startIndex:s,stopIndex:a})}if(l.length)for(var p=l[0];p.stopIndex-p.startIndex+1<n&&p.startIndex>0;){var h=p.startIndex-1;if(t({index:h}))break;p.startIndex=h}return l}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}();t.isRangeVisible=s,t.scanForUnloadedRanges=a;var c=n(3),d=n(4),f=o(d),p=function(e){function t(e,n){r(this,t);var o=i(this,Object.getPrototypeOf(t).call(this,e,n));return o._onRowsRendered=o._onRowsRendered.bind(o),o._registerChild=o._registerChild.bind(o),o}return l(t,e),u(t,[{key:"render",value:function(){var e=this.props.children;return e({onRowsRendered:this._onRowsRendered,registerChild:this._registerChild})}},{key:"shouldComponentUpdate",value:function(e,t){return(0,f["default"])(this,e,t)}},{key:"_onRowsRendered",value:function(e){var t=this,n=e.startIndex,o=e.stopIndex,r=this.props,i=r.isRowLoaded,l=r.loadMoreRows,u=r.minimumBatchSize,c=r.rowCount,d=r.threshold;this._lastRenderedStartIndex=n,this._lastRenderedStopIndex=o;var f=a({isRowLoaded:i,minimumBatchSize:u,rowCount:c,startIndex:Math.max(0,n-d),stopIndex:Math.min(c-1,o+d)});f.forEach(function(e){var n=l(e);n&&n.then(function(){s({lastRenderedStartIndex:t._lastRenderedStartIndex,lastRenderedStopIndex:t._lastRenderedStopIndex,startIndex:e.startIndex,stopIndex:e.stopIndex})&&t._registeredChild&&t._registeredChild.forceUpdate()})})}},{key:"_registerChild",value:function(e){this._registeredChild=e}}]),t}(c.Component);p.propTypes={children:c.PropTypes.func.isRequired,isRowLoaded:c.PropTypes.func.isRequired,loadMoreRows:c.PropTypes.func.isRequired,minimumBatchSize:c.PropTypes.number.isRequired,rowCount:c.PropTypes.number.isRequired,threshold:c.PropTypes.number.isRequired},p.defaultProps={minimumBatchSize:10,rowCount:0,threshold:15},t["default"]=p},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.ScrollSync=t["default"]=void 0;var r=n(47),i=o(r);t["default"]=i["default"],t.ScrollSync=i["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),a=n(3),u=n(4),c=o(u),d=function(e){function t(e,n){r(this,t);var o=i(this,Object.getPrototypeOf(t).call(this,e,n));return o.state={clientHeight:0,clientWidth:0,scrollHeight:0,scrollLeft:0,scrollTop:0,scrollWidth:0},o._onScroll=o._onScroll.bind(o),o}return l(t,e),s(t,[{key:"render",value:function(){var e=this.props.children,t=this.state,n=t.clientHeight,o=t.clientWidth,r=t.scrollHeight,i=t.scrollLeft,l=t.scrollTop,s=t.scrollWidth;return e({clientHeight:n,clientWidth:o,onScroll:this._onScroll,scrollHeight:r,scrollLeft:i,scrollTop:l,scrollWidth:s})}},{key:"shouldComponentUpdate",value:function(e,t){return(0,c["default"])(this,e,t)}},{key:"_onScroll",value:function(e){var t=e.clientHeight,n=e.clientWidth,o=e.scrollHeight,r=e.scrollLeft,i=e.scrollTop,l=e.scrollWidth;this.setState({clientHeight:t,clientWidth:n,scrollHeight:o,scrollLeft:r,scrollTop:i,scrollWidth:l})}}]),t}(a.Component);d.propTypes={children:a.PropTypes.func.isRequired},t["default"]=d},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.VirtualScroll=t["default"]=void 0;var r=n(49),i=o(r);t["default"]=i["default"],t.VirtualScroll=i["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},a=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),u=n(27),c=o(u),d=n(3),f=o(d),p=n(14),h=o(p),y=n(4),_=o(y),m=function(e){function t(e,n){r(this,t);var o=i(this,Object.getPrototypeOf(t).call(this,e,n));return o._cellRenderer=o._cellRenderer.bind(o),o._createRowClassNameGetter=o._createRowClassNameGetter.bind(o),o._createRowStyleGetter=o._createRowStyleGetter.bind(o),o._onScroll=o._onScroll.bind(o),o._onSectionRendered=o._onSectionRendered.bind(o),o}return l(t,e),a(t,[{key:"forceUpdateGrid",value:function(){this.Grid.forceUpdate()}},{key:"measureAllRows",value:function(){this.Grid.measureAllCells()}},{key:"recomputeRowHeights",value:function(){var e=arguments.length<=0||void 0===arguments[0]?0:arguments[0];this.Grid.recomputeGridSize({rowIndex:e}),this.forceUpdateGrid()}},{key:"render",value:function(){var e=this,t=this.props,n=t.className,o=t.noRowsRenderer,r=t.scrollToIndex,i=t.width,l=(0,h["default"])("VirtualScroll",n);return f["default"].createElement(c["default"],s({},this.props,{autoContainerWidth:!0,cellRenderer:this._cellRenderer,cellClassName:this._createRowClassNameGetter(),cellStyle:this._createRowStyleGetter(),className:l,columnWidth:i,columnCount:1,noContentRenderer:o,onScroll:this._onScroll,onSectionRendered:this._onSectionRendered,ref:function(t){e.Grid=t},scrollToRow:r}))}},{key:"shouldComponentUpdate",value:function(e,t){return(0,_["default"])(this,e,t)}},{key:"_cellRenderer",value:function(e){var t=(e.columnIndex,e.isScrolling),n=e.rowIndex,o=this.props.rowRenderer;return o({index:n,isScrolling:t})}},{key:"_createRowClassNameGetter",value:function(){var e=this.props.rowClassName;return e instanceof Function?function(t){var n=t.rowIndex;return e({index:n})}:function(){return e}}},{key:"_createRowStyleGetter",value:function(){var e=this.props.rowStyle,t=e instanceof Function?e:function(){return e};return function(e){var n=e.rowIndex;return s({width:"100%"},t({index:n}))}}},{key:"_onScroll",value:function(e){var t=e.clientHeight,n=e.scrollHeight,o=e.scrollTop,r=this.props.onScroll;r({clientHeight:t,scrollHeight:n,scrollTop:o})}},{key:"_onSectionRendered",value:function(e){var t=e.rowOverscanStartIndex,n=e.rowOverscanStopIndex,o=e.rowStartIndex,r=e.rowStopIndex,i=this.props.onRowsRendered;i({overscanStartIndex:t,overscanStopIndex:n,startIndex:o,stopIndex:r})}}]),t}(d.Component);m.propTypes={"aria-label":d.PropTypes.string,autoHeight:d.PropTypes.bool,className:d.PropTypes.string,estimatedRowSize:d.PropTypes.number.isRequired,height:d.PropTypes.number.isRequired,noRowsRenderer:d.PropTypes.func.isRequired,onRowsRendered:d.PropTypes.func.isRequired,overscanRowCount:d.PropTypes.number.isRequired,onScroll:d.PropTypes.func.isRequired,rowHeight:d.PropTypes.oneOfType([d.PropTypes.number,d.PropTypes.func]).isRequired,rowRenderer:d.PropTypes.func.isRequired,rowClassName:d.PropTypes.oneOfType([d.PropTypes.string,d.PropTypes.func]),rowCount:d.PropTypes.number.isRequired,rowStyle:d.PropTypes.oneOfType([d.PropTypes.object,d.PropTypes.func]),scrollToAlignment:d.PropTypes.oneOf(["auto","end","start","center"]).isRequired,scrollToIndex:d.PropTypes.number,scrollTop:d.PropTypes.number,style:d.PropTypes.object,tabIndex:d.PropTypes.number,width:d.PropTypes.number.isRequired},m.defaultProps={estimatedRowSize:30,noRowsRenderer:function(){return null},onRowsRendered:function(){return null},onScroll:function(){return null},overscanRowCount:10,scrollToAlignment:"auto",style:{}},t["default"]=m},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.WindowScroller=t["default"]=void 0;var r=n(51),i=o(r);t["default"]=i["default"],t.WindowScroller=i["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),a=n(3),u=o(a),c=n(10),d=o(c),f=n(4),p=o(f),h=n(18),y=o(h),_=150,m=function(e){function t(e){r(this,t);var n=i(this,Object.getPrototypeOf(t).call(this,e));return n.state={isScrolling:!1,height:0,scrollTop:0},n._onScrollWindow=n._onScrollWindow.bind(n),n._onResizeWindow=n._onResizeWindow.bind(n),n._enablePointerEventsAfterDelayCallback=n._enablePointerEventsAfterDelayCallback.bind(n),n}return l(t,e),s(t,[{key:"componentDidMount",value:function(){this._positionFromTop=d["default"].findDOMNode(this).getBoundingClientRect().top,this.setState({height:window.innerHeight}),window.addEventListener("scroll",this._onScrollWindow,!1),window.addEventListener("resize",this._onResizeWindow,!1)}},{key:"componentWillUnmount",value:function(){window.removeEventListener("scroll",this._onScrollWindow,!1),window.removeEventListener("resize",this._onResizeWindow,!1)}},{key:"_setNextState",value:function(e){var t=this;this._setNextStateAnimationFrameId&&y["default"].cancel(this._setNextStateAnimationFrameId),this._setNextStateAnimationFrameId=(0,y["default"])(function(){t._setNextStateAnimationFrameId=null,t.setState(e)})}},{key:"render",value:function(){var e=this.props.children,t=this.state,n=t.isScrolling,o=t.scrollTop,r=t.height;return u["default"].createElement("div",null,e({height:r,isScrolling:n,scrollTop:o}))}},{key:"shouldComponentUpdate",value:function(e,t){return(0,p["default"])(this,e,t)}},{key:"_enablePointerEventsAfterDelay",value:function(){this._disablePointerEventsTimeoutId&&clearTimeout(this._disablePointerEventsTimeoutId),this._disablePointerEventsTimeoutId=setTimeout(this._enablePointerEventsAfterDelayCallback,_)}},{key:"_enablePointerEventsAfterDelayCallback",value:function(){this._disablePointerEventsTimeoutId=null,document.body.style.pointerEvents=this._originalBodyPointerEvents,this._originalBodyPointerEvents=null,this.setState({isScrolling:!1})}},{key:"_onResizeWindow",value:function(e){var t=this.props.onResize,n=window.innerHeight||0;this.setState({height:n}),t({height:n})}},{key:"_onScrollWindow",value:function(e){var t=this.props.onScroll,n="scrollY"in window?window.scrollY:document.documentElement.scrollTop,o=Math.max(0,n-this._positionFromTop);null==this._originalBodyPointerEvents&&(this._originalBodyPointerEvents=document.body.style.pointerEvents,document.body.style.pointerEvents="none",this._enablePointerEventsAfterDelay());var r={isScrolling:!0,scrollTop:o};this.state.isScrolling?this._setNextState(r):this.setState(r),t({scrollTop:o})}}]),t}(a.Component);m.propTypes={children:a.PropTypes.func.isRequired,onResize:a.PropTypes.func.isRequired,onScroll:a.PropTypes.func.isRequired},m.defaultProps={onResize:function(){},onScroll:function(){}},t["default"]=m}])});
//# sourceMappingURL=react-virtualized.min.js.map |
client/src/components/courses/CourseSave.js | yegor-sytnyk/contoso-express | import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {Modal, Button} from 'react-bootstrap';
import _ from 'lodash';
import helper from '../../helpers/uiHelper';
import * as courseActions from '../../actions/courseActions';
import {departmentSelectListItem} from '../../formatters/entityFromatter';
import CourseForm from './CourseForm';
class CourseSave extends React.Component {
constructor(props) {
super(props);
this.state = {
course: _.assign({}, props.course),
errors: {},
saving: false,
visible: props.visible,
close: props.close
};
this.updateCourseState = this.updateCourseState.bind(this);
this.saveCourse = this.saveCourse.bind(this);
}
componentWillReceiveProps(nextProps) {
this.setState({course: _.assign({}, nextProps.course)});
}
updateCourseState(event) {
let course = this.state.course;
const field = event.target.name;
course[field] = event.target.value;
return this.setState({course: course});
}
courseFormIsValid() {
let formIsValid = true;
let errors = {};
if (!this.state.course.number) {
errors.number = 'The Number field is required.';
formIsValid = false;
}
if (!this.state.course.title) {
errors.title = 'The Title field is required.';
formIsValid = false;
}
if (!this.state.course.credits) {
errors.credits = 'The Credits field is required.';
formIsValid = false;
}
if (!_.inRange(this.state.course.credits, 0, 6)) {
errors.credits = 'The field Credits must be between 0 and 5.';
formIsValid = false;
}
if (!this.state.course.departmentId) {
errors.departmentId = 'Department is required.';
formIsValid = false;
}
this.setState({errors: errors});
return formIsValid;
}
saveCourse(event) {
event.preventDefault();
if (!this.courseFormIsValid()) {
return;
}
this.setState({saving: true});
this.props.actions.saveCourse(this.state.course)
.then(() => {
this.props.close();
let message = this.state.course.id ? 'Course updated' : 'Course added';
helper.showMessage(message);
})
.catch(err => {
this.setState({saving: false});
});
}
render() {
let header = this.props.course.id ? 'Edit Course' : 'Create Course';
return (
<div>
<Modal show={this.props.visible} onHide={this.props.close}>
<Modal.Header closeButton onClick={this.props.close}>
<Modal.Title>{header}</Modal.Title>
</Modal.Header>
<Modal.Body>
<CourseForm
course={this.state.course}
allDepartments={this.props.departments}
onChange={this.updateCourseState}
errors={this.state.errors}
/>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.saveCourse}>
{this.props.saving ? 'Saving...' : 'Save'}
</Button>
<Button onClick={this.props.close}>Close</Button>
</Modal.Footer>
</Modal>
</div>
);
}
}
CourseSave.propTypes = {
course: React.PropTypes.object.isRequired,
actions: React.PropTypes.object.isRequired,
visible: React.PropTypes.bool.isRequired,
close: React.PropTypes.func.isRequired
};
function mapStateToProps(state) {
return {
course: _.cloneDeep(state.course.current),
departments: departmentSelectListItem(state.department.list)
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(courseActions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(CourseSave); |
ajax/libs/analytics.js/2.8.2/analytics.min.js | emmy41124/cdnjs | (function umd(require){if("object"==typeof exports){module.exports=require("1")}else if("function"==typeof define&&define.amd){define(function(){return require("1")})}else{this["analytics"]=require("1")}})(function outer(modules,cache,entries){var global=function(){return this}();function require(name,jumped){if(cache[name])return cache[name].exports;if(modules[name])return call(name,require);throw new Error('cannot find module "'+name+'"')}function call(id,require){var m=cache[id]={exports:{}};var mod=modules[id];var name=mod[2];var fn=mod[0];fn.call(m.exports,function(req){var dep=modules[id][1][req];return require(dep?dep:req)},m,m.exports,outer,modules,cache,entries);if(name)cache[name]=cache[id];return cache[id].exports}for(var id in entries){if(entries[id]){global[entries[id]]=require(id)}else{require(id)}}require.duo=true;require.cache=cache;require.modules=modules;return require}({1:[function(require,module,exports){var _analytics=window.analytics;var Integrations=require("analytics.js-integrations");var Analytics=require("./analytics");var each=require("each");var analytics=module.exports=exports=new Analytics;analytics.require=require;exports.VERSION=require("../bower.json").version;each(Integrations,function(name,Integration){analytics.use(Integration)})},{"analytics.js-integrations":2,"./analytics":3,each:4,"../bower.json":5}],2:[function(require,module,exports){var each=require("each");var plugins=require("./integrations.js");each(plugins,function(plugin){var name=(plugin.Integration||plugin).prototype.name;exports[name]=plugin})},{each:4,"./integrations.js":6}],4:[function(require,module,exports){var type=require("type");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn){switch(type(obj)){case"array":return array(obj,fn);case"object":if("number"==typeof obj.length)return array(obj,fn);return object(obj,fn);case"string":return string(obj,fn)}};function string(obj,fn){for(var i=0;i<obj.length;++i){fn(obj.charAt(i),i)}}function object(obj,fn){for(var key in obj){if(has.call(obj,key)){fn(key,obj[key])}}}function array(obj,fn){for(var i=0;i<obj.length;++i){fn(obj[i],i)}}},{type:7}],7:[function(require,module,exports){var toString=Object.prototype.toString;module.exports=function(val){switch(toString.call(val)){case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object Error]":return"error"}if(val===null)return"null";if(val===undefined)return"undefined";if(val!==val)return"nan";if(val&&val.nodeType===1)return"element";val=val.valueOf?val.valueOf():Object.prototype.valueOf.apply(val);return typeof val}},{}],6:[function(require,module,exports){module.exports=[require("./lib/adroll"),require("./lib/adwords"),require("./lib/alexa"),require("./lib/amplitude"),require("./lib/appcues"),require("./lib/atatus"),require("./lib/autosend"),require("./lib/awesm"),require("./lib/bing-ads"),require("./lib/blueshift"),require("./lib/bronto"),require("./lib/bugherd"),require("./lib/bugsnag"),require("./lib/chartbeat"),require("./lib/churnbee"),require("./lib/clicktale"),require("./lib/clicky"),require("./lib/comscore"),require("./lib/crazy-egg"),require("./lib/curebit"),require("./lib/customerio"),require("./lib/drip"),require("./lib/errorception"),require("./lib/evergage"),require("./lib/extole"),require("./lib/facebook-conversion-tracking"),require("./lib/foxmetrics"),require("./lib/frontleaf"),require("./lib/fullstory"),require("./lib/gauges"),require("./lib/get-satisfaction"),require("./lib/google-analytics"),require("./lib/google-tag-manager"),require("./lib/gosquared"),require("./lib/heap"),require("./lib/hellobar"),require("./lib/hittail"),require("./lib/hubspot"),require("./lib/improvely"),require("./lib/insidevault"),require("./lib/inspectlet"),require("./lib/intercom"),require("./lib/keen-io"),require("./lib/kenshoo"),require("./lib/kissmetrics"),require("./lib/klaviyo"),require("./lib/livechat"),require("./lib/lucky-orange"),require("./lib/lytics"),require("./lib/mixpanel"),require("./lib/mojn"),require("./lib/mouseflow"),require("./lib/mousestats"),require("./lib/navilytics"),require("./lib/nudgespot"),require("./lib/olark"),require("./lib/optimizely"),require("./lib/perfect-audience"),require("./lib/pingdom"),require("./lib/piwik"),require("./lib/preact"),require("./lib/qualaroo"),require("./lib/quantcast"),require("./lib/rollbar"),require("./lib/saasquatch"),require("./lib/satismeter"),require("./lib/segmentio"),require("./lib/sentry"),require("./lib/snapengage"),require("./lib/spinnakr"),require("./lib/tapstream"),require("./lib/trakio"),require("./lib/twitter-ads"),require("./lib/userlike"),require("./lib/uservoice"),require("./lib/vero"),require("./lib/visual-website-optimizer"),require("./lib/webengage"),require("./lib/woopra"),require("./lib/yandex-metrica")]},{"./lib/adroll":8,"./lib/adwords":9,"./lib/alexa":10,"./lib/amplitude":11,"./lib/appcues":12,"./lib/atatus":13,"./lib/autosend":14,"./lib/awesm":15,"./lib/bing-ads":16,"./lib/blueshift":17,"./lib/bronto":18,"./lib/bugherd":19,"./lib/bugsnag":20,"./lib/chartbeat":21,"./lib/churnbee":22,"./lib/clicktale":23,"./lib/clicky":24,"./lib/comscore":25,"./lib/crazy-egg":26,"./lib/curebit":27,"./lib/customerio":28,"./lib/drip":29,"./lib/errorception":30,"./lib/evergage":31,"./lib/extole":32,"./lib/facebook-conversion-tracking":33,"./lib/foxmetrics":34,"./lib/frontleaf":35,"./lib/fullstory":36,"./lib/gauges":37,"./lib/get-satisfaction":38,"./lib/google-analytics":39,"./lib/google-tag-manager":40,"./lib/gosquared":41,"./lib/heap":42,"./lib/hellobar":43,"./lib/hittail":44,"./lib/hubspot":45,"./lib/improvely":46,"./lib/insidevault":47,"./lib/inspectlet":48,"./lib/intercom":49,"./lib/keen-io":50,"./lib/kenshoo":51,"./lib/kissmetrics":52,"./lib/klaviyo":53,"./lib/livechat":54,"./lib/lucky-orange":55,"./lib/lytics":56,"./lib/mixpanel":57,"./lib/mojn":58,"./lib/mouseflow":59,"./lib/mousestats":60,"./lib/navilytics":61,"./lib/nudgespot":62,"./lib/olark":63,"./lib/optimizely":64,"./lib/perfect-audience":65,"./lib/pingdom":66,"./lib/piwik":67,"./lib/preact":68,"./lib/qualaroo":69,"./lib/quantcast":70,"./lib/rollbar":71,"./lib/saasquatch":72,"./lib/satismeter":73,"./lib/segmentio":74,"./lib/sentry":75,"./lib/snapengage":76,"./lib/spinnakr":77,"./lib/tapstream":78,"./lib/trakio":79,"./lib/twitter-ads":80,"./lib/userlike":81,"./lib/uservoice":82,"./lib/vero":83,"./lib/visual-website-optimizer":84,"./lib/webengage":85,"./lib/woopra":86,"./lib/yandex-metrica":87}],8:[function(require,module,exports){var integration=require("analytics.js-integration");var snake=require("to-snake-case");var useHttps=require("use-https");var each=require("each");var is=require("is");var del=require("obj-case").del;var has=Object.prototype.hasOwnProperty;var AdRoll=module.exports=integration("AdRoll").assumesPageview().global("__adroll_loaded").global("adroll_adv_id").global("adroll_pix_id").global("adroll_custom_data").option("advId","").option("pixId","").tag("http",'<script src="http://a.adroll.com/j/roundtrip.js">').tag("https",'<script src="https://s.adroll.com/j/roundtrip.js">').mapping("events");AdRoll.prototype.initialize=function(page){window.adroll_adv_id=this.options.advId;window.adroll_pix_id=this.options.pixId;window.__adroll_loaded=true;var name=useHttps()?"https":"http";this.load(name,this.ready)};AdRoll.prototype.loaded=function(){return window.__adroll};AdRoll.prototype.page=function(page){var name=page.fullName();this.track(page.track(name))};AdRoll.prototype.track=function(track){var event=track.event();var user=this.analytics.user();var events=this.events(event);var total=track.revenue()||track.total()||0;var orderId=track.orderId()||0;var productId=track.id();var sku=track.sku();var customProps=track.properties();var data={};if(user.id())data.user_id=user.id();if(orderId)data.order_id=orderId;if(productId)data.product_id=productId;if(sku)data.sku=sku;del(customProps,"revenue");del(customProps,"total");del(customProps,"orderId");del(customProps,"id");del(customProps,"sku");if(!is.empty(customProps))data.adroll_custom_data=customProps;each(events,function(event){data.adroll_conversion_value_in_dollars=total;data.adroll_segments=snake(event);window.__adroll.record_user(data)});if(!events.length){data.adroll_segments=snake(event);window.__adroll.record_user(data)}}},{"analytics.js-integration":88,"to-snake-case":89,"use-https":90,each:4,is:91,"obj-case":92}],88:[function(require,module,exports){var bind=require("bind");var callback=require("callback");var clone=require("clone");var debug=require("debug");var defaults=require("defaults");var protos=require("./protos");var slug=require("slug");var statics=require("./statics");module.exports=createIntegration;function createIntegration(name){function Integration(options){if(options&&options.addIntegration){return options.addIntegration(Integration)}this.debug=debug("analytics:integration:"+slug(name));this.options=defaults(clone(options)||{},this.defaults);this._queue=[];this.once("ready",bind(this,this.flush));Integration.emit("construct",this);this.ready=bind(this,this.ready);this._wrapInitialize();this._wrapPage();this._wrapTrack()}Integration.prototype.defaults={};Integration.prototype.globals=[];Integration.prototype.templates={};Integration.prototype.name=name;for(var key in statics)Integration[key]=statics[key];for(var key in protos)Integration.prototype[key]=protos[key];return Integration}},{bind:93,callback:94,clone:95,debug:96,defaults:97,"./protos":98,slug:99,"./statics":100}],93:[function(require,module,exports){var bind=require("bind"),bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;function bindMethods(obj,methods){methods=[].slice.call(arguments,1);for(var i=0,method;method=methods[i];i++){obj[method]=bind(obj,obj[method])}return obj}},{bind:101,"bind-all":102}],101:[function(require,module,exports){var slice=[].slice;module.exports=function(obj,fn){if("string"==typeof fn)fn=obj[fn];if("function"!=typeof fn)throw new Error("bind() requires a function");var args=slice.call(arguments,2);return function(){return fn.apply(obj,args.concat(slice.call(arguments)))}}},{}],102:[function(require,module,exports){try{var bind=require("bind");var type=require("type")}catch(e){var bind=require("bind-component");var type=require("type-component")}module.exports=function(obj){for(var key in obj){var val=obj[key];if(type(val)==="function")obj[key]=bind(obj,obj[key])}return obj}},{bind:101,type:7}],94:[function(require,module,exports){var next=require("next-tick");module.exports=callback;function callback(fn){if("function"===typeof fn)fn()}callback.async=function(fn,wait){if("function"!==typeof fn)return;if(!wait)return next(fn);setTimeout(fn,wait)};callback.sync=callback},{"next-tick":103}],103:[function(require,module,exports){"use strict";if(typeof setImmediate=="function"){module.exports=function(f){setImmediate(f)}}else if(typeof process!="undefined"&&typeof process.nextTick=="function"){module.exports=process.nextTick}else if(typeof window=="undefined"||window.ActiveXObject||!window.postMessage){module.exports=function(f){setTimeout(f)}}else{var q=[];window.addEventListener("message",function(){var i=0;while(i<q.length){try{q[i++]()}catch(e){q=q.slice(i);window.postMessage("tic!","*");throw e}}q.length=0},true);module.exports=function(fn){if(!q.length)window.postMessage("tic!","*");q.push(fn)}}},{}],95:[function(require,module,exports){var type;try{type=require("type")}catch(e){type=require("type-component")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{type:7}],96:[function(require,module,exports){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}},{"./lib/debug":104,"./debug":105}],104:[function(require,module,exports){var tty=require("tty");module.exports=debug;var names=[],skips=[];(process.env.DEBUG||"").split(/[\s,]+/).forEach(function(name){name=name.replace("*",".*?");if(name[0]==="-"){skips.push(new RegExp("^"+name.substr(1)+"$"))}else{names.push(new RegExp("^"+name+"$"))}});var colors=[6,2,3,4,5,1];var prev={};var prevColor=0;var isatty=tty.isatty(2);function color(){return colors[prevColor++%colors.length]}function humanize(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"}function debug(name){function disabled(){}disabled.enabled=false;var match=skips.some(function(re){return re.test(name)});if(match)return disabled;match=names.some(function(re){return re.test(name)});if(!match)return disabled;var c=color();function colored(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(prev[name]||curr);prev[name]=curr;fmt=" [9"+c+"m"+name+" "+"[3"+c+"m[90m"+fmt+"[3"+c+"m"+" +"+humanize(ms)+"[0m";console.error.apply(this,arguments)}function plain(fmt){fmt=coerce(fmt);fmt=(new Date).toUTCString()+" "+name+" "+fmt;console.error.apply(this,arguments)}colored.enabled=plain.enabled=true;return isatty||process.env.DEBUG_COLORS?colored:plain}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{}],105:[function(require,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],97:[function(require,module,exports){"use strict";var defaults=function(dest,src,recursive){for(var prop in src){if(recursive&&dest[prop]instanceof Object&&src[prop]instanceof Object){dest[prop]=defaults(dest[prop],src[prop],true)}else if(!(prop in dest)){dest[prop]=src[prop]}}return dest};module.exports=defaults},{}],98:[function(require,module,exports){var loadScript=require("load-script");var loadIframe=require("load-iframe");var events=require("analytics-events");var normalize=require("to-no-case");var callback=require("callback");var Emitter=require("emitter");var tick=require("next-tick");var after=require("after");var each=require("each");var type=require("type");var fmt=require("fmt");function noop(){}var setTimeout=window.setTimeout;var setInterval=window.setInterval;var onerror=window.onerror;var onload=null;Emitter(exports);exports.initialize=function(){var ready=this.ready;tick(ready)};exports.loaded=function(){return false};exports.page=function(page){};exports.track=function(track){};exports.map=function(obj,str){var a=normalize(str);var ret=[];if(!obj)return ret;if("object"==type(obj)){for(var k in obj){var item=obj[k];var b=normalize(k);if(b==a)ret.push(item)}}if("array"==type(obj)){if(!obj.length)return ret;if(!obj[0].key)return ret;for(var i=0;i<obj.length;++i){var item=obj[i];var b=normalize(item.key);if(b==a)ret.push(item.value)}}return ret};exports.invoke=function(method){if(!this[method])return;var args=[].slice.call(arguments,1);if(!this._ready)return this.queue(method,args);var ret;try{this.debug("%s with %o",method,args);ret=this[method].apply(this,args)}catch(e){this.debug("error %o calling %s with %o",e,method,args)}return ret};exports.queue=function(method,args){if("page"==method&&this._assumesPageview&&!this._initialized){return this.page.apply(this,args)}this._queue.push({method:method,args:args})};exports.flush=function(){this._ready=true;var call;while(call=this._queue.shift())this[call.method].apply(this,call.args)};exports.reset=function(){for(var i=0,key;key=this.globals[i];i++)window[key]=undefined;window.setTimeout=setTimeout;window.setInterval=setInterval;window.onerror=onerror;window.onload=onload};exports.load=function(name,locals,fn){if("function"==typeof name)fn=name,locals=null,name=null;if(name&&"object"==typeof name)fn=locals,locals=name,name=null;if("function"==typeof locals)fn=locals,locals=null;name=name||"library";locals=locals||{};locals=this.locals(locals);var template=this.templates[name];if(!template)throw new Error(fmt('template "%s" not defined.',name));var attrs=render(template,locals);var fn=fn||noop;var self=this;var el;switch(template.type){case"img":attrs.width=1;attrs.height=1;el=loadImage(attrs,fn);break;case"script":el=loadScript(attrs,function(err){if(!err)return fn();self.debug('error loading "%s" error="%s"',self.name,err)});delete attrs.src;each(attrs,function(key,val){el.setAttribute(key,val)});break;case"iframe":el=loadIframe(attrs,fn);break}return el};exports.locals=function(locals){locals=locals||{};var cache=Math.floor((new Date).getTime()/36e5);if(!locals.hasOwnProperty("cache"))locals.cache=cache;each(this.options,function(key,val){if(!locals.hasOwnProperty(key))locals[key]=val});return locals};exports.ready=function(){this.emit("ready")};exports._wrapInitialize=function(){var initialize=this.initialize;this.initialize=function(){this.debug("initialize");this._initialized=true;var ret=initialize.apply(this,arguments);this.emit("initialize");return ret};if(this._assumesPageview)this.initialize=after(2,this.initialize)};exports._wrapPage=function(){var page=this.page;this.page=function(){if(this._assumesPageview&&!this._initialized){return this.initialize.apply(this,arguments)}return page.apply(this,arguments)}};exports._wrapTrack=function(){var t=this.track;this.track=function(track){var event=track.event();var called;var ret;for(var method in events){var regexp=events[method];if(!this[method])continue;if(!regexp.test(event))continue;ret=this[method].apply(this,arguments);called=true;break}if(!called)ret=t.apply(this,arguments);return ret}};function loadImage(attrs,fn){fn=fn||function(){};var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};img.src=attrs.src;img.width=1;img.height=1;return img}function error(fn,message,img){return function(e){e=e||window.event;var err=new Error(message);err.event=e;err.source=img;fn(err)}}function render(template,locals){var attrs={};each(template.attrs,function(key,val){attrs[key]=val.replace(/\{\{\ *(\w+)\ *\}\}/g,function(_,$1){return locals[$1]})});return attrs}},{"load-script":106,"load-iframe":107,"analytics-events":108,"to-no-case":109,callback:94,emitter:110,"next-tick":103,after:111,each:112,type:113,fmt:114}],106:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadScript(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;if("function"==type(fn)){onload(script,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript)});return script}},{"script-onload":115,"next-tick":103,type:7}],115:[function(require,module,exports){module.exports=function(el,fn){return el.addEventListener?add(el,fn):attach(el,fn)};function add(el,fn){el.addEventListener("load",function(_,e){fn(null,e)},false);el.addEventListener("error",function(e){var err=new Error('script error "'+el.src+'"');err.event=e;fn(err)},false)}function attach(el,fn){el.attachEvent("onreadystatechange",function(e){if(!/complete|loaded/.test(el.readyState))return;fn(null,e)});el.attachEvent("onerror",function(e){var err=new Error('failed to load the script "'+el.src+'"');err.event=e||window.event;fn(err)})}},{}],107:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadIframe(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var iframe=document.createElement("iframe");iframe.src=options.src;iframe.width=options.width||1;iframe.height=options.height||1;iframe.style.display="none";if("function"==type(fn)){onload(iframe,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(iframe,firstScript)});return iframe}},{"script-onload":115,"next-tick":103,type:7}],108:[function(require,module,exports){module.exports={removedProduct:/^[ _]?removed[ _]?product[ _]?$/i,viewedProduct:/^[ _]?viewed[ _]?product[ _]?$/i,viewedProductCategory:/^[ _]?viewed[ _]?product[ _]?category[ _]?$/i,addedProduct:/^[ _]?added[ _]?product[ _]?$/i,completedOrder:/^[ _]?completed[ _]?order[ _]?$/i,startedOrder:/^[ _]?started[ _]?order[ _]?$/i,updatedOrder:/^[ _]?updated[ _]?order[ _]?$/i,refundedOrder:/^[ _]?refunded?[ _]?order[ _]?$/i,viewedProductDetails:/^[ _]?viewed[ _]?product[ _]?details?[ _]?$/i,clickedProduct:/^[ _]?clicked[ _]?product[ _]?$/i,viewedPromotion:/^[ _]?viewed[ _]?promotion?[ _]?$/i,clickedPromotion:/^[ _]?clicked[ _]?promotion?[ _]?$/i,viewedCheckoutStep:/^[ _]?viewed[ _]?checkout[ _]?step[ _]?$/i,completedCheckoutStep:/^[ _]?completed[ _]?checkout[ _]?step[ _]?$/i}},{}],109:[function(require,module,exports){module.exports=toNoCase;var hasSpace=/\s/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))return unseparate(string).toLowerCase();return uncamelize(string).toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}},{}],110:[function(require,module,exports){var index=require("indexof");module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}fn._off=on;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var i=index(callbacks,fn._off||fn);if(~i)callbacks.splice(i,1);return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{indexof:116}],116:[function(require,module,exports){module.exports=function(arr,obj){if(arr.indexOf)return arr.indexOf(obj);for(var i=0;i<arr.length;++i){if(arr[i]===obj)return i}return-1}},{}],111:[function(require,module,exports){module.exports=function after(times,func){if(times<=0)return func();return function(){if(--times<1){return func.apply(this,arguments)}}}},{}],112:[function(require,module,exports){try{var type=require("type")}catch(err){var type=require("component-type")}var toFunction=require("to-function");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn,ctx){fn=toFunction(fn);ctx=ctx||this;switch(type(obj)){case"array":return array(obj,fn,ctx);case"object":if("number"==typeof obj.length)return array(obj,fn,ctx);return object(obj,fn,ctx);case"string":return string(obj,fn,ctx)}};function string(obj,fn,ctx){for(var i=0;i<obj.length;++i){fn.call(ctx,obj.charAt(i),i)}}function object(obj,fn,ctx){for(var key in obj){if(has.call(obj,key)){fn.call(ctx,key,obj[key])}}}function array(obj,fn,ctx){for(var i=0;i<obj.length;++i){fn.call(ctx,obj[i],i)}}},{type:113,"component-type":113,"to-function":117}],113:[function(require,module,exports){var toString=Object.prototype.toString;module.exports=function(val){switch(toString.call(val)){case"[object Function]":return"function";case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object String]":return"string"}if(val===null)return"null";if(val===undefined)return"undefined";if(val&&val.nodeType===1)return"element";if(val===Object(val))return"object";return typeof val}},{}],117:[function(require,module,exports){var expr;try{expr=require("props")}catch(e){expr=require("component-props")}module.exports=toFunction;function toFunction(obj){switch({}.toString.call(obj)){case"[object Object]":return objectToFunction(obj);case"[object Function]":return obj;case"[object String]":return stringToFunction(obj);case"[object RegExp]":return regexpToFunction(obj);default:return defaultToFunction(obj)}}function defaultToFunction(val){return function(obj){return val===obj}}function regexpToFunction(re){return function(obj){return re.test(obj)}}function stringToFunction(str){if(/^ *\W+/.test(str))return new Function("_","return _ "+str);return new Function("_","return "+get(str))}function objectToFunction(obj){var match={};for(var key in obj){match[key]=typeof obj[key]==="string"?defaultToFunction(obj[key]):toFunction(obj[key])}return function(val){if(typeof val!=="object")return false;for(var key in match){if(!(key in val))return false;if(!match[key](val[key]))return false}return true}}function get(str){var props=expr(str);if(!props.length)return"_."+str;var val,i,prop;for(i=0;i<props.length;i++){prop=props[i];val="_."+prop;val="('function' == typeof "+val+" ? "+val+"() : "+val+")";str=stripNested(prop,str,val)}return str}function stripNested(prop,str,val){return str.replace(new RegExp("(\\.)?"+prop,"g"),function($0,$1){return $1?$0:val})}},{props:118,"component-props":118}],118:[function(require,module,exports){var globals=/\b(this|Array|Date|Object|Math|JSON)\b/g;module.exports=function(str,fn){var p=unique(props(str));if(fn&&"string"==typeof fn)fn=prefixed(fn);if(fn)return map(str,p,fn);return p};function props(str){return str.replace(/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\//g,"").replace(globals,"").match(/[$a-zA-Z_]\w*/g)||[]}function map(str,props,fn){var re=/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g;return str.replace(re,function(_){if("("==_[_.length-1])return fn(_);if(!~props.indexOf(_))return _;return fn(_)})}function unique(arr){var ret=[];for(var i=0;i<arr.length;i++){if(~ret.indexOf(arr[i]))continue;ret.push(arr[i])}return ret}function prefixed(str){return function(_){return str+_}}},{}],114:[function(require,module,exports){var toString=window.JSON?JSON.stringify:function(_){return String(_)};module.exports=fmt;fmt.o=toString;fmt.s=String;fmt.d=parseInt;function fmt(str){var args=[].slice.call(arguments,1);var j=0;return str.replace(/%([a-z])/gi,function(_,f){return fmt[f]?fmt[f](args[j++]):_+f})}},{}],99:[function(require,module,exports){module.exports=function(str,options){options||(options={});return str.toLowerCase().replace(options.replace||/[^a-z0-9]/g," ").replace(/^ +| +$/g,"").replace(/ +/g,options.separator||"-")}},{}],100:[function(require,module,exports){var after=require("after");var domify=require("domify");var each=require("each");var Emitter=require("emitter");Emitter(exports);exports.option=function(key,value){this.prototype.defaults[key]=value;return this};exports.mapping=function(name){this.option(name,[]);this.prototype[name]=function(str){return this.map(this.options[name],str)};return this};exports.global=function(key){this.prototype.globals.push(key);return this};exports.assumesPageview=function(){this.prototype._assumesPageview=true;return this};exports.readyOnLoad=function(){this.prototype._readyOnLoad=true;return this};exports.readyOnInitialize=function(){this.prototype._readyOnInitialize=true;return this};exports.tag=function(name,str){if(null==str){str=name;name="library"}this.prototype.templates[name]=objectify(str);return this};function objectify(str){str=str.replace(' src="',' data-src="');var el=domify(str);var attrs={};each(el.attributes,function(attr){var name="data-src"==attr.name?"src":attr.name;if(!~str.indexOf(attr.name+"="))return;attrs[name]=attr.value});return{type:el.tagName.toLowerCase(),attrs:attrs}}},{after:111,domify:119,each:112,emitter:110}],119:[function(require,module,exports){module.exports=parse;var div=document.createElement("div");div.innerHTML=' <link/><table></table><a href="/a">a</a><input type="checkbox"/>';var innerHTMLBug=!div.getElementsByTagName("link").length;div=undefined;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:innerHTMLBug?[1,"X<div>","</div>"]:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"];map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"];map.polyline=map.ellipse=map.polygon=map.circle=map.text=map.line=map.path=map.rect=map.g=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"];function parse(html,doc){if("string"!=typeof html)throw new TypeError("String expected");if(!doc)doc=document;var m=/<([\w:]+)/.exec(html);if(!m)return doc.createTextNode(html);html=html.replace(/^\s+|\s+$/g,"");var tag=m[1];if(tag=="body"){var el=doc.createElement("html");el.innerHTML=html;return el.removeChild(el.lastChild)}var wrap=map[tag]||map._default;var depth=wrap[0];
var prefix=wrap[1];var suffix=wrap[2];var el=doc.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=doc.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}},{}],89:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}},{"to-space-case":120}],120:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}},{"to-no-case":121}],121:[function(require,module,exports){module.exports=toNoCase;var hasSpace=/\s/;var hasCamel=/[a-z][A-Z]/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))string=unseparate(string);if(hasCamel.test(string))string=uncamelize(string);return string.toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}},{}],90:[function(require,module,exports){module.exports=function(url){switch(arguments.length){case 0:return check();case 1:return transform(url)}};function transform(url){return check()?"https:"+url:"http:"+url}function check(){return location.protocol=="https:"||location.protocol=="chrome-extension:"}},{}],91:[function(require,module,exports){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":122,type:7,"component-type":7}],122:[function(require,module,exports){module.exports=isEmpty;var has=Object.prototype.hasOwnProperty;function isEmpty(val){if(null==val)return true;if("number"==typeof val)return 0===val;if(undefined!==val.length)return 0===val.length;for(var key in val)if(has.call(val,key))return false;return true}},{}],92:[function(require,module,exports){var Case=require("case");var identity=function(_){return _};var cases=[identity,Case.upper,Case.lower,Case.snake,Case.pascal,Case.camel,Case.constant,Case.title,Case.capital,Case.sentence];module.exports=module.exports.find=multiple(find);module.exports.replace=function(obj,key,val){multiple(replace).apply(this,arguments);return obj};module.exports.del=function(obj,key){multiple(del).apply(this,arguments);return obj};function multiple(fn){return function(obj,key,val){var keys=key.split(".");if(keys.length===0)return;while(keys.length>1){key=keys.shift();obj=find(obj,key);if(obj===null||obj===undefined)return}key=keys.shift();return fn(obj,key,val)}}function find(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))return obj[cased]}}function del(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))delete obj[cased]}return obj}function replace(obj,key,val){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))obj[cased]=val}return obj}},{"case":123}],123:[function(require,module,exports){var cases=require("./cases");module.exports=exports=determineCase;function determineCase(string){for(var key in cases){if(key=="none")continue;var convert=cases[key];if(convert(string)==string)return key}return null}exports.add=function(name,convert){exports[name]=cases[name]=convert};for(var key in cases){exports.add(key,cases[key])}},{"./cases":124}],124:[function(require,module,exports){var camel=require("to-camel-case"),capital=require("to-capital-case"),constant=require("to-constant-case"),dot=require("to-dot-case"),none=require("to-no-case"),pascal=require("to-pascal-case"),sentence=require("to-sentence-case"),slug=require("to-slug-case"),snake=require("to-snake-case"),space=require("to-space-case"),title=require("to-title-case");exports.camel=camel;exports.pascal=pascal;exports.dot=dot;exports.slug=slug;exports.snake=snake;exports.space=space;exports.constant=constant;exports.capital=capital;exports.title=title;exports.sentence=sentence;exports.lower=function(string){return none(string).toLowerCase()};exports.upper=function(string){return none(string).toUpperCase()};exports.inverse=function(string){for(var i=0,char;char=string[i];i++){if(!/[a-z]/i.test(char))continue;var upper=char.toUpperCase();var lower=char.toLowerCase();string[i]=char==upper?lower:upper}return string};exports.none=none},{"to-camel-case":125,"to-capital-case":126,"to-constant-case":127,"to-dot-case":128,"to-no-case":121,"to-pascal-case":129,"to-sentence-case":130,"to-slug-case":131,"to-snake-case":132,"to-space-case":133,"to-title-case":134}],125:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toCamelCase;function toCamelCase(string){return toSpace(string).replace(/\s(\w)/g,function(matches,letter){return letter.toUpperCase()})}},{"to-space-case":133}],133:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}},{"to-no-case":121}],126:[function(require,module,exports){var clean=require("to-no-case");module.exports=toCapitalCase;function toCapitalCase(string){return clean(string).replace(/(^|\s)(\w)/g,function(matches,previous,letter){return previous+letter.toUpperCase()})}},{"to-no-case":121}],127:[function(require,module,exports){var snake=require("to-snake-case");module.exports=toConstantCase;function toConstantCase(string){return snake(string).toUpperCase()}},{"to-snake-case":132}],132:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}},{"to-space-case":133}],128:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toDotCase;function toDotCase(string){return toSpace(string).replace(/\s/g,".")}},{"to-space-case":133}],129:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toPascalCase;function toPascalCase(string){return toSpace(string).replace(/(?:^|\s)(\w)/g,function(matches,letter){return letter.toUpperCase()})}},{"to-space-case":133}],130:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSentenceCase;function toSentenceCase(string){return clean(string).replace(/[a-z]/i,function(letter){return letter.toUpperCase()})}},{"to-no-case":121}],131:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSlugCase;function toSlugCase(string){return toSpace(string).replace(/\s/g,"-")}},{"to-space-case":133}],134:[function(require,module,exports){var capital=require("to-capital-case"),escape=require("escape-regexp"),map=require("map"),minors=require("title-case-minors");module.exports=toTitleCase;var escaped=map(minors,escape);var minorMatcher=new RegExp("[^^]\\b("+escaped.join("|")+")\\b","ig");var colonMatcher=/:\s*(\w)/g;function toTitleCase(string){return capital(string).replace(minorMatcher,function(minor){return minor.toLowerCase()}).replace(colonMatcher,function(letter){return letter.toUpperCase()})}},{"to-capital-case":126,"escape-regexp":135,map:136,"title-case-minors":137}],135:[function(require,module,exports){module.exports=function(str){return String(str).replace(/([.*+?=^!:${}()|[\]\/\\])/g,"\\$1")}},{}],136:[function(require,module,exports){var each=require("each");module.exports=function map(obj,iterator){var arr=[];each(obj,function(o){arr.push(iterator.apply(null,arguments))});return arr}},{each:112}],137:[function(require,module,exports){module.exports=["a","an","and","as","at","but","by","en","for","from","how","if","in","neither","nor","of","on","only","onto","out","or","per","so","than","that","the","to","until","up","upon","v","v.","versus","vs","vs.","via","when","with","without","yet"]},{}],9:[function(require,module,exports){var integration=require("analytics.js-integration");var domify=require("domify");var each=require("each");var has=Object.prototype.hasOwnProperty;var AdWords=module.exports=integration("AdWords").option("conversionId","").option("remarketing",false).tag('<script src="//www.googleadservices.com/pagead/conversion_async.js">').mapping("events");AdWords.prototype.initialize=function(){this.load(this.ready)};AdWords.prototype.loaded=function(){return!!document.body};AdWords.prototype.page=function(page){var remarketing=!!this.options.remarketing;var id=this.options.conversionId;var props={};window.google_trackConversion({google_conversion_id:id,google_custom_params:props,google_remarketing_only:remarketing})};AdWords.prototype.track=function(track){var id=this.options.conversionId;var events=this.events(track.event());var revenue=track.revenue()||0;each(events,function(label){var props=track.properties();delete props.revenue;window.google_trackConversion({google_conversion_id:id,google_custom_params:props,google_conversion_language:"en",google_conversion_format:"3",google_conversion_color:"ffffff",google_conversion_label:label,google_conversion_value:revenue,google_remarketing_only:false})})}},{"analytics.js-integration":88,domify:119,each:4}],10:[function(require,module,exports){var integration=require("analytics.js-integration");var Alexa=module.exports=integration("Alexa").assumesPageview().global("_atrk_opts").option("account",null).option("domain","").option("dynamic",true).tag('<script src="//d31qbv1cthcecs.cloudfront.net/atrk.js">');Alexa.prototype.initialize=function(page){var self=this;window._atrk_opts={atrk_acct:this.options.account,domain:this.options.domain,dynamic:this.options.dynamic};this.load(function(){window.atrk();self.ready()})};Alexa.prototype.loaded=function(){return!!window.atrk}},{"analytics.js-integration":88}],11:[function(require,module,exports){var integration=require("analytics.js-integration");var utm=require("utm-params");var top=require("top-domain");var umd="function"==typeof define&&define.amd;var src="//d24n15hnbwhuhn.cloudfront.net/libs/amplitude-2.0.3-min.js";var Amplitude=module.exports=integration("Amplitude").global("amplitude").option("apiKey","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="'+src+'">');Amplitude.prototype.initialize=function(page){(function(h,a){var f=h.amplitude||{};f._q=[];function e(i){f[i]=function(){f._q.push([i].concat(Array.prototype.slice.call(arguments,0)))}}var c=["init","logEvent","setUserId","setUserProperties","setVersionName","setDomain","setDeviceId","setGlobalUserProperties"];for(var d=0;d<c.length;d++){e(c[d])}h.amplitude=f})(window,document);this.setDomain(window.location.href);window.amplitude.init(this.options.apiKey);this.setUserProperties(window.location.search);var self=this;if(umd){window.require([src],function(amplitude){window.amplitude=amplitude;self.ready()});return}this.load(function(){self.ready()})};Amplitude.prototype.loaded=function(){return!!(window.amplitude&&window.amplitude.options)};Amplitude.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Amplitude.prototype.identify=function(identify){var id=identify.userId();var traits=identify.traits();if(id)window.amplitude.setUserId(id);if(traits)window.amplitude.setUserProperties(traits)};Amplitude.prototype.track=function(track){var props=track.properties();var event=track.event();window.amplitude.logEvent(event,props)};Amplitude.prototype.setDomain=function(href){var domain=top(href);window.amplitude.setDomain(domain)};Amplitude.prototype.setDeviceId=function(deviceId){if(deviceId)window.amplitude.setDeviceId(deviceId)};Amplitude.prototype.setUserProperties=function(query){var campaign=utm(query);var campaignName=campaign.name;campaign.campaign=campaignName;delete campaign.name;if(campaign)window.amplitude.setUserProperties(campaign)}},{"analytics.js-integration":88,"utm-params":138,"top-domain":139}],138:[function(require,module,exports){var parse=require("querystring").parse;module.exports=utm;function utm(query){if("?"==query.charAt(0))query=query.substring(1);var query=query.replace(/\?/g,"&");var params=parse(query);var param;var ret={};for(var key in params){if(~key.indexOf("utm_")){param=key.substr(4);if("campaign"==param)param="name";ret[param]=params[key]}}return ret}},{querystring:140}],140:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=/(\w+)\[(\d+)\]/.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:141,type:7}],141:[function(require,module,exports){exports=module.exports=trim;function trim(str){if(str.trim)return str.trim();return str.replace(/^\s*|\s*$/g,"")}exports.left=function(str){if(str.trimLeft)return str.trimLeft();return str.replace(/^\s*/,"")};exports.right=function(str){if(str.trimRight)return str.trimRight();return str.replace(/\s*$/,"")}},{}],139:[function(require,module,exports){var parse=require("url").parse;module.exports=domain;var regexp=/[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i;function domain(url){var host=parse(url).hostname;var match=host.match(regexp);return match?match[0]:""}},{url:142}],142:[function(require,module,exports){exports.parse=function(url){var a=document.createElement("a");a.href=url;return{href:a.href,host:a.host||location.host,port:"0"===a.port||""===a.port?port(a.protocol):a.port,hash:a.hash,hostname:a.hostname||location.hostname,pathname:a.pathname.charAt(0)!="/"?"/"+a.pathname:a.pathname,protocol:!a.protocol||":"==a.protocol?location.protocol:a.protocol,search:a.search,query:a.search.slice(1)}};exports.isAbsolute=function(url){return 0==url.indexOf("//")||!!~url.indexOf("://")};exports.isRelative=function(url){return!exports.isAbsolute(url)};exports.isCrossDomain=function(url){url=exports.parse(url);var location=exports.parse(window.location.href);return url.hostname!==location.hostname||url.port!==location.port||url.protocol!==location.protocol};function port(protocol){switch(protocol){case"http:":return 80;case"https:":return 443;default:return location.port}}},{}],12:[function(require,module,exports){var integration=require("analytics.js-integration");var load=require("load-script");var is=require("is");module.exports=exports=function(analytics){analytics.addIntegration(Appcues)};var Appcues=exports.Integration=integration("Appcues").assumesPageview().global("Appcues").global("AppcuesIdentity").option("appcuesId","").option("userId","").option("userEmail","");Appcues.prototype.initialize=function(){this.load(function(){window.Appcues.init()})};Appcues.prototype.loaded=function(){return is.object(window.Appcues)};Appcues.prototype.load=function(callback){var script=load("//d2dubfq97s02eu.cloudfront.net/appcues-bundle.min.js",callback);script.setAttribute("data-appcues-id",this.options.appcuesId);script.setAttribute("data-user-id",this.options.userId);script.setAttribute("data-user-email",this.options.userEmail)};Appcues.prototype.identify=function(identify){window.Appcues.identify(identify.traits())}},{"analytics.js-integration":88,"load-script":143,is:91}],143:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadScript(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;if("function"==type(fn)){onload(script,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript)});return script}},{"script-onload":115,"next-tick":103,type:7}],13:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var Atatus=module.exports=integration("Atatus").global("atatus").option("apiKey","").tag('<script src="//www.atatus.com/atatus.js">');Atatus.prototype.initialize=function(page){var self=this;this.load(function(){window.atatus.config(self.options.apiKey).install();self.ready()})};Atatus.prototype.loaded=function(){return is.object(window.atatus)};Atatus.prototype.identify=function(identify){window.atatus.setCustomData({person:identify.traits()})}},{"analytics.js-integration":88,is:91}],14:[function(require,module,exports){var integration=require("analytics.js-integration");var Autosend=module.exports=integration("Autosend").global("_autosend").option("appKey","").tag('<script id="asnd-tracker" src="https://d2zjxodm1cz8d6.cloudfront.net/js/v1/autosend.js" data-auth-key="{{ appKey }}">');Autosend.prototype.initialize=function(page){window._autosend=window._autosend||[];(function(){var a,b,c;a=function(f){return function(){window._autosend.push([f].concat(Array.prototype.slice.call(arguments,0)))}};b=["identify","track","cb"];for(c=0;c<b.length;c++){window._autosend[b[c]]=a(b[c])}})();this.load(this.ready)};Autosend.prototype.loaded=function(){return!!window._autosend};Autosend.prototype.identify=function(identify){var id=identify.userId();if(!id)return;var traits=identify.traits();traits.id=id;window._autosend.identify(traits)};Autosend.prototype.track=function(track){window._autosend.track(track.event())}},{"analytics.js-integration":88}],15:[function(require,module,exports){var integration=require("analytics.js-integration");var each=require("each");var Awesm=module.exports=integration("awe.sm").assumesPageview().global("AWESM").option("apiKey","").tag('<script src="//widgets.awe.sm/v3/widgets.js?key={{ apiKey }}&async=true">').mapping("events");Awesm.prototype.initialize=function(page){window.AWESM={api_key:this.options.apiKey};this.load(this.ready)};Awesm.prototype.loaded=function(){return!!(window.AWESM&&window.AWESM._exists)};Awesm.prototype.track=function(track){var user=this.analytics.user();var goals=this.events(track.event());each(goals,function(goal){window.AWESM.convert(goal,track.cents(),null,user.id())})}},{"analytics.js-integration":88,each:4}],16:[function(require,module,exports){var integration=require("analytics.js-integration");var onbody=require("on-body");var domify=require("domify");var extend=require("extend");var bind=require("bind");var when=require("when");var each=require("each");var has=Object.prototype.hasOwnProperty;var noop=function(){};var Bing=module.exports=integration("Bing Ads").global("uetq").option("tagId","").tag('<script src="//bat.bing.com/bat.js">');Bing.prototype.initialize=function(){window.uetq=window.uetq||[];var self=this;self.load(function(){var setup={ti:self.options.tagId,q:window.uetq};window.uetq=new UET(setup);self.ready()})};Bing.prototype.loaded=function(){return!!(window.uetq&&window.uetq.push!==Array.prototype.push)};Bing.prototype.page=function(){window.uetq.push("pageLoad")};Bing.prototype.track=function(track){var event={ea:"track",el:track.event()};if(track.category())event.ec=track.category();if(track.revenue())event.ev=track.revenue();window.uetq.push(event)}},{"analytics.js-integration":88,"on-body":144,domify:119,extend:145,bind:101,when:146,each:4}],144:[function(require,module,exports){var each=require("each");var body=false;var callbacks=[];module.exports=function onBody(callback){if(body){call(callback)}else{callbacks.push(callback)}};var interval=setInterval(function(){if(!document.body)return;body=true;each(callbacks,call);clearInterval(interval)},5);function call(callback){callback(document.body)}},{each:112}],145:[function(require,module,exports){module.exports=function extend(object){var args=Array.prototype.slice.call(arguments,1);for(var i=0,source;source=args[i];i++){if(!source)continue;for(var property in source){object[property]=source[property]}}return object}},{}],146:[function(require,module,exports){var callback=require("callback");module.exports=when;function when(condition,fn,interval){if(condition())return callback.async(fn);var ref=setInterval(function(){if(!condition())return;callback(fn);clearInterval(ref)},interval||10)}},{callback:94}],17:[function(require,module,exports){var integration=require("analytics.js-integration");var Blueshift=module.exports=integration("Blueshift").global("blueshift").global("_blueshiftid").option("apiKey","").option("retarget",false).tag('<script src="https://cdn.getblueshift.com/blueshift.js">');Blueshift.prototype.initialize=function(page){window.blueshift=window.blueshift||[];window.blueshift.load=function(a){window._blueshiftid=a;var d=function(a){return function(){blueshift.push([a].concat(Array.prototype.slice.call(arguments,0)))}},e=["identify","track","click","pageload","capture","retarget"];for(var f=0;f<e.length;f++)blueshift[e[f]]=d(e[f])};window.blueshift.load(this.options.apiKey);this.load(this.ready)};Blueshift.prototype.loaded=function(){return!!(window.blueshift&&window._blueshiftid)};Blueshift.prototype.page=function(page){if(this.options.retarget)window.blueshift.retarget();var properties=page.properties();properties._bsft_source="segment.com";window.blueshift.pageload(properties)};Blueshift.prototype.identify=function(identify){if(!identify.userId())return this.debug("user id required");var traits=identify.traits({created:"created_at"});traits._bsft_source="segment.com";window.blueshift.identify(traits)};Blueshift.prototype.group=function(group){var traits=group.traits({created:"created_at"});traits._bsft_source="segment.com";window.blueshift.track("group",traits)};Blueshift.prototype.track=function(track){var properties=track.properties();properties._bsft_source="segment.com";window.blueshift.track(track.event(),properties)}},{"analytics.js-integration":88}],18:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var Track=require("facade").Track;var pixel=require("load-pixel")("http://app.bronto.com/public/");var qs=require("querystring");var each=require("each");var Bronto=module.exports=integration("Bronto").global("__bta").option("siteId","").option("host","").tag('<script src="//p.bm23.com/bta.js">');Bronto.prototype.initialize=function(page){var self=this;var params=qs.parse(window.location.search);if(!params._bta_tid&&!params._bta_c){this.debug("missing tracking URL parameters `_bta_tid` and `_bta_c`.")}this.load(function(){var opts=self.options;self.bta=new window.__bta(opts.siteId);if(opts.host)self.bta.setHost(opts.host);self.ready()})};Bronto.prototype.loaded=function(){return this.bta};Bronto.prototype.completedOrder=function(track){var user=this.analytics.user();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({userId:user.id(),traits:user.traits()});var email=identify.email();each(products,function(product){var track=new Track({properties:product});items.push({item_id:track.id()||track.sku(),desc:product.description||track.name(),quantity:track.quantity(),amount:track.price()})});this.bta.addOrder({order_id:track.orderId(),email:email,items:items})}},{"analytics.js-integration":88,facade:147,"load-pixel":148,querystring:149,each:4}],147:[function(require,module,exports){var Facade=require("./facade");module.exports=Facade;Facade.Alias=require("./alias");Facade.Group=require("./group");Facade.Identify=require("./identify");Facade.Track=require("./track");Facade.Page=require("./page");Facade.Screen=require("./screen")},{"./facade":150,"./alias":151,"./group":152,"./identify":153,"./track":154,"./page":155,"./screen":156}],150:[function(require,module,exports){var traverse=require("isodate-traverse");var isEnabled=require("./is-enabled");var clone=require("./utils").clone;var type=require("./utils").type;var address=require("./address");var objCase=require("obj-case");var newDate=require("new-date");module.exports=Facade;function Facade(obj){if(!obj.hasOwnProperty("timestamp"))obj.timestamp=new Date;else obj.timestamp=newDate(obj.timestamp);traverse(obj);this.obj=obj}address(Facade.prototype);Facade.prototype.proxy=function(field){var fields=field.split(".");field=fields.shift();var obj=this[field]||this.field(field);if(!obj)return obj;if(typeof obj==="function")obj=obj.call(this)||{};if(fields.length===0)return transform(obj);obj=objCase(obj,fields.join("."));return transform(obj)};Facade.prototype.field=function(field){var obj=this.obj[field];return transform(obj)};Facade.proxy=function(field){return function(){return this.proxy(field)}};Facade.field=function(field){return function(){return this.field(field)}};Facade.multi=function(path){return function(){var multi=this.proxy(path+"s");if("array"==type(multi))return multi;var one=this.proxy(path);if(one)one=[clone(one)];return one||[]}};Facade.one=function(path){return function(){var one=this.proxy(path);if(one)return one;var multi=this.proxy(path+"s");if("array"==type(multi))return multi[0]}};Facade.prototype.json=function(){var ret=clone(this.obj);if(this.type)ret.type=this.type();return ret};Facade.prototype.context=Facade.prototype.options=function(integration){var options=clone(this.obj.options||this.obj.context)||{};if(!integration)return clone(options);if(!this.enabled(integration))return;var integrations=this.integrations();var value=integrations[integration]||objCase(integrations,integration);if("boolean"==typeof value)value={};return value||{}};Facade.prototype.enabled=function(integration){var allEnabled=this.proxy("options.providers.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("options.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("integrations.all");if(typeof allEnabled!=="boolean")allEnabled=true;var enabled=allEnabled&&isEnabled(integration);var options=this.integrations();if(options.providers&&options.providers.hasOwnProperty(integration)){enabled=options.providers[integration]}if(options.hasOwnProperty(integration)){var settings=options[integration];if(typeof settings==="boolean"){enabled=settings}else{enabled=true}}return enabled?true:false};Facade.prototype.integrations=function(){return this.obj.integrations||this.proxy("options.providers")||this.options()};Facade.prototype.active=function(){var active=this.proxy("options.active");if(active===null||active===undefined)active=true;return active};Facade.prototype.sessionId=Facade.prototype.anonymousId=function(){return this.field("anonymousId")||this.field("sessionId")};Facade.prototype.groupId=Facade.proxy("options.groupId");Facade.prototype.traits=function(aliases){var ret=this.proxy("options.traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("options.traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Facade.prototype.library=function(){var library=this.proxy("options.library");if(!library)return{name:"unknown",version:null};if(typeof library==="string")return{name:library,version:null};return library};Facade.prototype.userId=Facade.field("userId");Facade.prototype.channel=Facade.field("channel");Facade.prototype.timestamp=Facade.field("timestamp");Facade.prototype.userAgent=Facade.proxy("options.userAgent");Facade.prototype.ip=Facade.proxy("options.ip");function transform(obj){var cloned=clone(obj);return cloned}},{"isodate-traverse":157,"./is-enabled":158,"./utils":159,"./address":160,"obj-case":161,"new-date":162}],157:[function(require,module,exports){var is=require("is");var isodate=require("isodate");var each;try{each=require("each")}catch(err){each=require("each-component")}module.exports=traverse;function traverse(input,strict){if(strict===undefined)strict=true;if(is.object(input))return object(input,strict);if(is.array(input))return array(input,strict);return input}function object(obj,strict){each(obj,function(key,val){if(isodate.is(val,strict)){obj[key]=isodate.parse(val)}else if(is.object(val)||is.array(val)){traverse(val,strict)}});return obj}function array(arr,strict){each(arr,function(val,x){if(is.object(val)){traverse(val,strict)}else if(isodate.is(val,strict)){arr[x]=isodate.parse(val)}});return arr}},{is:163,isodate:164,each:4}],163:[function(require,module,exports){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":122,type:7,"component-type":7}],164:[function(require,module,exports){var matcher=/^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;exports.parse=function(iso){var numericKeys=[1,5,6,7,11,12];var arr=matcher.exec(iso);var offset=0;if(!arr)return new Date(iso);for(var i=0,val;val=numericKeys[i];i++){arr[val]=parseInt(arr[val],10)||0}arr[2]=parseInt(arr[2],10)||1;arr[3]=parseInt(arr[3],10)||1;arr[2]--;arr[8]=arr[8]?(arr[8]+"00").substring(0,3):0;if(arr[4]==" "){offset=(new Date).getTimezoneOffset()}else if(arr[9]!=="Z"&&arr[10]){offset=arr[11]*60+arr[12];if("+"==arr[10])offset=0-offset}var millis=Date.UTC(arr[1],arr[2],arr[3],arr[5],arr[6]+offset,arr[7],arr[8]);return new Date(millis)};exports.is=function(string,strict){if(strict&&false===/^\d{4}-\d{2}-\d{2}/.test(string))return false;return matcher.test(string)}},{}],158:[function(require,module,exports){var disabled={Salesforce:true};module.exports=function(integration){return!disabled[integration]}},{}],159:[function(require,module,exports){try{exports.inherit=require("inherit");exports.clone=require("clone");exports.type=require("type")}catch(e){exports.inherit=require("inherit-component");exports.clone=require("clone-component");exports.type=require("type-component")}},{inherit:165,clone:166,type:7}],165:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};
fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],166:[function(require,module,exports){var type;try{type=require("component-type")}catch(_){type=require("type")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{"component-type":7,type:7}],160:[function(require,module,exports){var get=require("obj-case");module.exports=function(proto){proto.zip=trait("postalCode","zip");proto.country=trait("country");proto.street=trait("street");proto.state=trait("state");proto.city=trait("city");function trait(a,b){return function(){var traits=this.traits();var props=this.properties?this.properties():{};return get(traits,"address."+a)||get(traits,a)||(b?get(traits,"address."+b):null)||(b?get(traits,b):null)||get(props,"address."+a)||get(props,a)||(b?get(props,"address."+b):null)||(b?get(props,b):null)}}}},{"obj-case":161}],161:[function(require,module,exports){var identity=function(_){return _};module.exports=multiple(find);module.exports.find=module.exports;module.exports.replace=function(obj,key,val,options){multiple(replace).call(this,obj,key,val,options);return obj};module.exports.del=function(obj,key,options){multiple(del).call(this,obj,key,null,options);return obj};function multiple(fn){return function(obj,path,val,options){var normalize=options&&isFunction(options.normalizer)?options.normalizer:defaultNormalize;path=normalize(path);var key;var finished=false;while(!finished)loop();function loop(){for(key in obj){var normalizedKey=normalize(key);if(0===path.indexOf(normalizedKey)){var temp=path.substr(normalizedKey.length);if(temp.charAt(0)==="."||temp.length===0){path=temp.substr(1);var child=obj[key];if(null==child){finished=true;return}if(!path.length){finished=true;return}obj=child;return}}}key=undefined;finished=true}if(!key)return;if(null==obj)return obj;return fn(obj,key,val)}}function find(obj,key){if(obj.hasOwnProperty(key))return obj[key]}function del(obj,key){if(obj.hasOwnProperty(key))delete obj[key];return obj}function replace(obj,key,val){if(obj.hasOwnProperty(key))obj[key]=val;return obj}function defaultNormalize(path){return path.replace(/[^a-zA-Z0-9\.]+/g,"").toLowerCase()}function isFunction(val){return typeof val==="function"}},{}],162:[function(require,module,exports){var is=require("is");var isodate=require("isodate");var milliseconds=require("./milliseconds");var seconds=require("./seconds");module.exports=function newDate(val){if(is.date(val))return val;if(is.number(val))return new Date(toMs(val));if(isodate.is(val))return isodate.parse(val);if(milliseconds.is(val))return milliseconds.parse(val);if(seconds.is(val))return seconds.parse(val);return new Date(val)};function toMs(num){if(num<315576e5)return num*1e3;return num}},{is:167,isodate:164,"./milliseconds":168,"./seconds":169}],167:[function(require,module,exports){var isEmpty=require("is-empty"),typeOf=require("type");var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":122,type:7}],168:[function(require,module,exports){var matcher=/\d{13}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(millis){millis=parseInt(millis,10);return new Date(millis)}},{}],169:[function(require,module,exports){var matcher=/\d{10}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(seconds){var millis=parseInt(seconds,10)*1e3;return new Date(millis)}},{}],151:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");module.exports=Alias;function Alias(dictionary){Facade.call(this,dictionary)}inherit(Alias,Facade);Alias.prototype.type=Alias.prototype.action=function(){return"alias"};Alias.prototype.from=Alias.prototype.previousId=function(){return this.field("previousId")||this.field("from")};Alias.prototype.to=Alias.prototype.userId=function(){return this.field("userId")||this.field("to")}},{"./utils":159,"./facade":150}],152:[function(require,module,exports){var inherit=require("./utils").inherit;var address=require("./address");var isEmail=require("is-email");var newDate=require("new-date");var Facade=require("./facade");module.exports=Group;function Group(dictionary){Facade.call(this,dictionary)}inherit(Group,Facade);Group.prototype.type=Group.prototype.action=function(){return"group"};Group.prototype.groupId=Facade.field("groupId");Group.prototype.created=function(){var created=this.proxy("traits.createdAt")||this.proxy("traits.created")||this.proxy("properties.createdAt")||this.proxy("properties.created");if(created)return newDate(created)};Group.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var groupId=this.groupId();if(isEmail(groupId))return groupId};Group.prototype.traits=function(aliases){var ret=this.properties();var id=this.groupId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Group.prototype.name=Facade.proxy("traits.name");Group.prototype.industry=Facade.proxy("traits.industry");Group.prototype.employees=Facade.proxy("traits.employees");Group.prototype.properties=function(){return this.field("traits")||this.field("properties")||{}}},{"./utils":159,"./address":160,"is-email":170,"new-date":162,"./facade":150}],170:[function(require,module,exports){module.exports=isEmail;var matcher=/.+\@.+\..+/;function isEmail(string){return matcher.test(string)}},{}],153:[function(require,module,exports){var address=require("./address");var Facade=require("./facade");var isEmail=require("is-email");var newDate=require("new-date");var utils=require("./utils");var get=require("obj-case");var trim=require("trim");var inherit=utils.inherit;var clone=utils.clone;var type=utils.type;module.exports=Identify;function Identify(dictionary){Facade.call(this,dictionary)}inherit(Identify,Facade);Identify.prototype.type=Identify.prototype.action=function(){return"identify"};Identify.prototype.traits=function(aliases){var ret=this.field("traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;if(alias!==aliases[alias])delete ret[alias]}return ret};Identify.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Identify.prototype.created=function(){var created=this.proxy("traits.created")||this.proxy("traits.createdAt");if(created)return newDate(created)};Identify.prototype.companyCreated=function(){var created=this.proxy("traits.company.created")||this.proxy("traits.company.createdAt");if(created)return newDate(created)};Identify.prototype.name=function(){var name=this.proxy("traits.name");if(typeof name==="string")return trim(name);var firstName=this.firstName();var lastName=this.lastName();if(firstName&&lastName)return trim(firstName+" "+lastName)};Identify.prototype.firstName=function(){var firstName=this.proxy("traits.firstName");if(typeof firstName==="string")return trim(firstName);var name=this.proxy("traits.name");if(typeof name==="string")return trim(name).split(" ")[0]};Identify.prototype.lastName=function(){var lastName=this.proxy("traits.lastName");if(typeof lastName==="string")return trim(lastName);var name=this.proxy("traits.name");if(typeof name!=="string")return;var space=trim(name).indexOf(" ");if(space===-1)return;return trim(name.substr(space+1))};Identify.prototype.uid=function(){return this.userId()||this.username()||this.email()};Identify.prototype.description=function(){return this.proxy("traits.description")||this.proxy("traits.background")};Identify.prototype.age=function(){var date=this.birthday();var age=get(this.traits(),"age");if(null!=age)return age;if("date"!=type(date))return;var now=new Date;return now.getFullYear()-date.getFullYear()};Identify.prototype.avatar=function(){var traits=this.traits();return get(traits,"avatar")||get(traits,"photoUrl")||get(traits,"avatarUrl")};Identify.prototype.position=function(){var traits=this.traits();return get(traits,"position")||get(traits,"jobTitle")};Identify.prototype.username=Facade.proxy("traits.username");Identify.prototype.website=Facade.one("traits.website");Identify.prototype.websites=Facade.multi("traits.website");Identify.prototype.phone=Facade.one("traits.phone");Identify.prototype.phones=Facade.multi("traits.phone");Identify.prototype.address=Facade.proxy("traits.address");Identify.prototype.gender=Facade.proxy("traits.gender");Identify.prototype.birthday=Facade.proxy("traits.birthday")},{"./address":160,"./facade":150,"is-email":170,"new-date":162,"./utils":159,"obj-case":161,trim:141}],154:[function(require,module,exports){var inherit=require("./utils").inherit;var clone=require("./utils").clone;var type=require("./utils").type;var Facade=require("./facade");var Identify=require("./identify");var isEmail=require("is-email");var get=require("obj-case");module.exports=Track;function Track(dictionary){Facade.call(this,dictionary)}inherit(Track,Facade);Track.prototype.type=Track.prototype.action=function(){return"track"};Track.prototype.event=Facade.field("event");Track.prototype.value=Facade.proxy("properties.value");Track.prototype.category=Facade.proxy("properties.category");Track.prototype.id=Facade.proxy("properties.id");Track.prototype.sku=Facade.proxy("properties.sku");Track.prototype.tax=Facade.proxy("properties.tax");Track.prototype.name=Facade.proxy("properties.name");Track.prototype.price=Facade.proxy("properties.price");Track.prototype.total=Facade.proxy("properties.total");Track.prototype.coupon=Facade.proxy("properties.coupon");Track.prototype.shipping=Facade.proxy("properties.shipping");Track.prototype.discount=Facade.proxy("properties.discount");Track.prototype.description=Facade.proxy("properties.description");Track.prototype.plan=Facade.proxy("properties.plan");Track.prototype.orderId=function(){return this.proxy("properties.id")||this.proxy("properties.orderId")};Track.prototype.subtotal=function(){var subtotal=get(this.properties(),"subtotal");var total=this.total();var n;if(subtotal)return subtotal;if(!total)return 0;if(n=this.tax())total-=n;if(n=this.shipping())total-=n;if(n=this.discount())total+=n;return total};Track.prototype.products=function(){var props=this.properties();var products=get(props,"products");return"array"==type(products)?products:[]};Track.prototype.quantity=function(){var props=this.obj.properties||{};return props.quantity||1};Track.prototype.currency=function(){var props=this.obj.properties||{};return props.currency||"USD"};Track.prototype.referrer=Facade.proxy("properties.referrer");Track.prototype.query=Facade.proxy("options.query");Track.prototype.properties=function(aliases){var ret=this.field("properties")||{};aliases=aliases||{};for(var alias in aliases){var value=null==this[alias]?this.proxy("properties."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Track.prototype.username=function(){return this.proxy("traits.username")||this.proxy("properties.username")||this.userId()||this.sessionId()};Track.prototype.email=function(){var email=this.proxy("traits.email");email=email||this.proxy("properties.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Track.prototype.revenue=function(){var revenue=this.proxy("properties.revenue");var event=this.event();if(!revenue&&event&&event.match(/completed ?order/i)){revenue=this.proxy("properties.total")}return currency(revenue)};Track.prototype.cents=function(){var revenue=this.revenue();return"number"!=typeof revenue?this.value()||0:revenue*100};Track.prototype.identify=function(){var json=this.json();json.traits=this.traits();return new Identify(json)};function currency(val){if(!val)return;if(typeof val==="number")return val;if(typeof val!=="string")return;val=val.replace(/\$/g,"");val=parseFloat(val);if(!isNaN(val))return val}},{"./utils":159,"./facade":150,"./identify":153,"is-email":170,"obj-case":161}],155:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");var Track=require("./track");module.exports=Page;function Page(dictionary){Facade.call(this,dictionary)}inherit(Page,Facade);Page.prototype.type=Page.prototype.action=function(){return"page"};Page.prototype.category=Facade.field("category");Page.prototype.name=Facade.field("name");Page.prototype.title=Facade.proxy("properties.title");Page.prototype.path=Facade.proxy("properties.path");Page.prototype.url=Facade.proxy("properties.url");Page.prototype.referrer=function(){return this.proxy("properties.referrer")||this.proxy("context.referrer.url")};Page.prototype.properties=function(){var props=this.field("properties")||{};var category=this.category();var name=this.name();if(category)props.category=category;if(name)props.name=name;return props};Page.prototype.fullName=function(){var category=this.category();var name=this.name();return name&&category?category+" "+name:name};Page.prototype.event=function(name){return name?"Viewed "+name+" Page":"Loaded a Page"};Page.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),timestamp:this.timestamp(),context:this.context(),properties:props})}},{"./utils":159,"./facade":150,"./track":154}],156:[function(require,module,exports){var inherit=require("./utils").inherit;var Page=require("./page");var Track=require("./track");module.exports=Screen;function Screen(dictionary){Page.call(this,dictionary)}inherit(Screen,Page);Screen.prototype.type=Screen.prototype.action=function(){return"screen"};Screen.prototype.event=function(name){return name?"Viewed "+name+" Screen":"Loaded a Screen"};Screen.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),timestamp:this.timestamp(),context:this.context(),properties:props})}},{"./utils":159,"./page":155,"./track":154}],148:[function(require,module,exports){var stringify=require("querystring").stringify;var sub=require("substitute");module.exports=function(path){return function(query,obj,fn){if("function"==typeof obj)fn=obj,obj={};obj=obj||{};fn=fn||function(){};var url=sub(path,obj);var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};query=stringify(query);if(query)query="?"+query;img.src=url+query;img.width=1;img.height=1;return img}};function error(fn,message,img){return function(e){e=e||window.event;var err=new Error(message);err.event=e;err.source=img;fn(err)}}},{querystring:140,substitute:171}],171:[function(require,module,exports){module.exports=substitute;var type=Object.prototype.toString;function substitute(str,obj,expr){if(!obj)throw new TypeError("expected an object");expr=expr||/:(\w+)/g;return str.replace(expr,function(_,prop){switch(type.call(obj)){case"[object Object]":return null!=obj[prop]?obj[prop]:_;case"[object Array]":var val=obj.shift();return null!=val?val:_}})}},{}],149:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=/(\w+)\[(\d+)\]/.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:141,type:7}],19:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var BugHerd=module.exports=integration("BugHerd").assumesPageview().global("BugHerdConfig").global("_bugHerd").option("apiKey","").option("showFeedbackTab",true).tag('<script src="//www.bugherd.com/sidebarv2.js?apikey={{ apiKey }}">');BugHerd.prototype.initialize=function(page){window.BugHerdConfig={feedback:{hide:!this.options.showFeedbackTab}};var ready=this.ready;this.load(function(){tick(ready)})};BugHerd.prototype.loaded=function(){return!!window._bugHerd}},{"analytics.js-integration":88,"next-tick":103}],20:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var extend=require("extend");var onError=require("on-error");var umd="function"==typeof define&&define.amd;var src="//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js";var Bugsnag=module.exports=integration("Bugsnag").global("Bugsnag").option("apiKey","").tag('<script src="'+src+'">');Bugsnag.prototype.initialize=function(page){var self=this;if(umd){window.require([src],function(bugsnag){bugsnag.apiKey=self.options.apiKey;window.Bugsnag=bugsnag;self.ready()});return}this.load(function(){window.Bugsnag.apiKey=self.options.apiKey;self.ready()})};Bugsnag.prototype.loaded=function(){return is.object(window.Bugsnag)};Bugsnag.prototype.identify=function(identify){window.Bugsnag.metaData=window.Bugsnag.metaData||{};extend(window.Bugsnag.metaData,identify.traits())}},{"analytics.js-integration":88,is:91,extend:145,"on-error":172}],172:[function(require,module,exports){module.exports=onError;var callbacks=[];if("function"==typeof window.onerror)callbacks.push(window.onerror);window.onerror=handler;function handler(){for(var i=0,fn;fn=callbacks[i];i++)fn.apply(this,arguments)}function onError(fn){callbacks.push(fn);if(window.onerror!=handler){callbacks.push(window.onerror);window.onerror=handler}}},{}],21:[function(require,module,exports){var integration=require("analytics.js-integration");var defaults=require("defaults");var onBody=require("on-body");var Chartbeat=module.exports=integration("Chartbeat").assumesPageview().global("_sf_async_config").global("_sf_endpt").global("pSUPERFLY").option("domain","").option("uid",null).tag('<script src="//static.chartbeat.com/js/chartbeat.js">');Chartbeat.prototype.initialize=function(page){var self=this;window._sf_async_config=window._sf_async_config||{};window._sf_async_config.useCanonical=true;defaults(window._sf_async_config,this.options);onBody(function(){window._sf_endpt=(new Date).getTime();self.load(self.ready)})};Chartbeat.prototype.loaded=function(){return!!window.pSUPERFLY};Chartbeat.prototype.page=function(page){var category=page.category();if(category)window._sf_async_config.sections=category;var author=page.proxy("properties.author");if(author)window._sf_async_config.authors=author;var props=page.properties();var name=page.fullName();window.pSUPERFLY.virtualPage(props.path,name||props.title)}},{"analytics.js-integration":88,defaults:173,"on-body":144}],173:[function(require,module,exports){module.exports=defaults;function defaults(dest,defaults){for(var prop in defaults){if(!(prop in dest)){dest[prop]=defaults[prop]}}return dest}},{}],22:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_cbq");var each=require("each");var has=Object.prototype.hasOwnProperty;var supported={activation:true,changePlan:true,register:true,refund:true,charge:true,cancel:true,login:true};var ChurnBee=module.exports=integration("ChurnBee").global("_cbq").global("ChurnBee").option("apiKey","").tag('<script src="//api.churnbee.com/cb.js">').mapping("events");ChurnBee.prototype.initialize=function(page){push("_setApiKey",this.options.apiKey);this.load(this.ready)};ChurnBee.prototype.loaded=function(){return!!window.ChurnBee};ChurnBee.prototype.track=function(track){var event=track.event();var events=this.events(event);events.push(event);each(events,function(event){if(true!=supported[event])return;push(event,track.properties({revenue:"amount"}))})}},{"analytics.js-integration":88,"global-queue":174,each:4}],174:[function(require,module,exports){module.exports=generate;function generate(name,options){options=options||{};return function(args){args=[].slice.call(arguments);window[name]||(window[name]=[]);options.wrap===false?window[name].push.apply(window[name],args):window[name].push(args)}}},{}],23:[function(require,module,exports){var date=require("load-date");var domify=require("domify");var each=require("each");var integration=require("analytics.js-integration");var is=require("is");var useHttps=require("use-https");var onBody=require("on-body");var ClickTale=module.exports=integration("ClickTale").assumesPageview().global("WRInitTime").global("ClickTale").global("ClickTaleSetUID").global("ClickTaleField").global("ClickTaleEvent").option("httpCdnUrl","http://s.clicktale.net/WRe0.js").option("httpsCdnUrl","").option("projectId","").option("recordingRatio",.01).option("partitionId","").tag('<script src="{{src}}">');ClickTale.prototype.initialize=function(page){var self=this;window.WRInitTime=date.getTime();onBody(function(body){body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">'))});var http=this.options.httpCdnUrl;var https=this.options.httpsCdnUrl;if(useHttps()&&!https)return this.debug("https option required");var src=useHttps()?https:http;this.load({src:src},function(){window.ClickTale(self.options.projectId,self.options.recordingRatio,self.options.partitionId);self.ready()})};ClickTale.prototype.loaded=function(){return is.fn(window.ClickTale)};ClickTale.prototype.identify=function(identify){var id=identify.userId();window.ClickTaleSetUID(id);each(identify.traits(),function(key,value){window.ClickTaleField(key,value)})};ClickTale.prototype.track=function(track){window.ClickTaleEvent(track.event())}},{"load-date":175,domify:119,each:4,"analytics.js-integration":88,is:91,"use-https":90,"on-body":144}],175:[function(require,module,exports){var time=new Date,perf=window.performance;if(perf&&perf.timing&&perf.timing.responseEnd){time=new Date(perf.timing.responseEnd)}module.exports=time},{}],24:[function(require,module,exports){var Identify=require("facade").Identify;var extend=require("extend");var integration=require("analytics.js-integration");var is=require("is");var Clicky=module.exports=integration("Clicky").assumesPageview().global("clicky").global("clicky_site_ids").global("clicky_custom").option("siteId",null).tag('<script src="//static.getclicky.com/js"></script>');Clicky.prototype.initialize=function(page){var user=this.analytics.user();window.clicky_site_ids=window.clicky_site_ids||[this.options.siteId];this.identify(new Identify({userId:user.id(),traits:user.traits()}));this.load(this.ready)};Clicky.prototype.loaded=function(){return is.object(window.clicky)};Clicky.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();window.clicky.log(properties.path,name||properties.title)};Clicky.prototype.identify=function(identify){window.clicky_custom=window.clicky_custom||{};window.clicky_custom.session=window.clicky_custom.session||{};var traits=identify.traits();var username=identify.username();var email=identify.email();var name=identify.name();if(username||email||name)traits.username=username||email||name;extend(window.clicky_custom.session,traits)};Clicky.prototype.track=function(track){window.clicky.goal(track.event(),track.revenue())}},{facade:147,extend:145,"analytics.js-integration":88,is:91}],25:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var Comscore=module.exports=integration("comScore").assumesPageview().global("_comscore").global("COMSCORE").option("c1","2").option("c2","").tag("http",'<script src="http://b.scorecardresearch.com/beacon.js">').tag("https",'<script src="https://sb.scorecardresearch.com/beacon.js">');Comscore.prototype.initialize=function(page){window._comscore=window._comscore||[this.options];var name=useHttps()?"https":"http";this.load(name,this.ready)};Comscore.prototype.loaded=function(){return!!window.COMSCORE};Comscore.prototype.page=function(page){window.COMSCORE.beacon(this.options)}},{"analytics.js-integration":88,"use-https":90}],26:[function(require,module,exports){var integration=require("analytics.js-integration");var CrazyEgg=module.exports=integration("Crazy Egg").assumesPageview().global("CE2").option("accountNumber","").tag('<script src="//dnn506yrbagrg.cloudfront.net/pages/scripts/{{ path }}.js?{{ cache }}">');CrazyEgg.prototype.initialize=function(page){var number=this.options.accountNumber;var path=number.slice(0,4)+"/"+number.slice(4);var cache=Math.floor((new Date).getTime()/36e5);this.load({path:path,cache:cache},this.ready)};CrazyEgg.prototype.loaded=function(){return!!window.CE2}},{"analytics.js-integration":88}],27:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_curebitq");var Identify=require("facade").Identify;var throttle=require("throttle");var Track=require("facade").Track;var iso=require("to-iso-string");var clone=require("clone");var each=require("each");var bind=require("bind");var Curebit=module.exports=integration("Curebit").global("_curebitq").global("curebit").option("siteId","").option("iframeWidth","100%").option("iframeHeight","480").option("iframeBorder",0).option("iframeId","curebit_integration").option("responsive",true).option("device","").option("insertIntoId","").option("campaigns",{}).option("server","https://www.curebit.com").tag('<script src="//d2jjzw81hqbuqv.cloudfront.net/integration/curebit-1.0.min.js">');Curebit.prototype.initialize=function(page){push("init",{site_id:this.options.siteId,server:this.options.server});this.load(this.ready);this.page=throttle(bind(this,this.page),250)};Curebit.prototype.loaded=function(){return!!window.curebit};Curebit.prototype.injectIntoId=function(url,id,fn){var server=this.options.server;when(function(){return document.getElementById(id)},function(){var script=document.createElement("script");script.src=url;var parent=document.getElementById(id);parent.appendChild(script);onload(script,fn)})};Curebit.prototype.page=function(page){var user=this.analytics.user();var campaigns=this.options.campaigns;var path=window.location.pathname;if(!campaigns[path])return;var tags=(campaigns[path]||"").split(",");if(!tags.length)return;var settings={responsive:this.options.responsive,device:this.options.device,campaign_tags:tags,iframe:{width:this.options.iframeWidth,height:this.options.iframeHeight,id:this.options.iframeId,frameborder:this.options.iframeBorder,container:this.options.insertIntoId}};var identify=new Identify({userId:user.id(),traits:user.traits()});if(identify.email()){settings.affiliate_member={email:identify.email(),first_name:identify.firstName(),last_name:identify.lastName(),customer_id:identify.userId()}}push("register_affiliate",settings)};Curebit.prototype.completedOrder=function(track){var user=this.analytics.user();var orderId=track.orderId();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({traits:user.traits(),userId:user.id()});each(products,function(product){var track=new Track({properties:product});items.push({product_id:track.id()||track.sku(),quantity:track.quantity(),image_url:product.image,price:track.price(),title:track.name(),url:product.url})});push("register_purchase",{order_date:iso(props.date||new Date),order_number:orderId,coupon_code:track.coupon(),subtotal:track.total(),customer_id:identify.userId(),first_name:identify.firstName(),last_name:identify.lastName(),email:identify.email(),items:items})}},{"analytics.js-integration":88,"global-queue":174,facade:147,throttle:176,"to-iso-string":177,clone:95,each:4,bind:101}],176:[function(require,module,exports){module.exports=throttle;function throttle(func,wait){var rtn;var last=0;return function throttled(){var now=(new Date).getTime();var delta=now-last;if(delta>=wait){rtn=func.apply(this,arguments);last=now}return rtn}}},{}],177:[function(require,module,exports){module.exports=toIsoString;function toIsoString(date){return date.getUTCFullYear()+"-"+pad(date.getUTCMonth()+1)+"-"+pad(date.getUTCDate())+"T"+pad(date.getUTCHours())+":"+pad(date.getUTCMinutes())+":"+pad(date.getUTCSeconds())+"."+String((date.getUTCMilliseconds()/1e3).toFixed(3)).slice(2,5)+"Z"}function pad(number){var n=number.toString();return n.length===1?"0"+n:n}},{}],28:[function(require,module,exports){var alias=require("alias");var convertDates=require("convert-dates");var Identify=require("facade").Identify;var integration=require("analytics.js-integration");var Customerio=module.exports=integration("Customer.io").global("_cio").option("siteId","").tag('<script id="cio-tracker" src="https://assets.customer.io/assets/track.js" data-site-id="{{ siteId }}">');Customerio.prototype.initialize=function(page){window._cio=window._cio||[];(function(){var a,b,c;a=function(f){return function(){window._cio.push([f].concat(Array.prototype.slice.call(arguments,0)))}};b=["identify","track"];for(c=0;c<b.length;c++){window._cio[b[c]]=a(b[c])}})();this.load(this.ready)};Customerio.prototype.loaded=function(){return!!window._cio&&window._cio.push!==Array.prototype.push};Customerio.prototype.identify=function(identify){if(!identify.userId())return this.debug("user id required");var traits=identify.traits({createdAt:"created"});traits=alias(traits,{created:"created_at"});traits=convertDates(traits,convertDate);window._cio.identify(traits)};Customerio.prototype.group=function(group){var traits=group.traits();var user=this.analytics.user();traits=alias(traits,function(trait){return"Group "+trait});this.identify(new Identify({userId:user.id(),traits:traits}))};Customerio.prototype.track=function(track){var properties=track.properties();properties=convertDates(properties,convertDate);window._cio.track(track.event(),properties)};function convertDate(date){return Math.floor(date.getTime()/1e3)}},{alias:178,"convert-dates":179,facade:147,"analytics.js-integration":88}],178:[function(require,module,exports){var type=require("type");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=alias;function alias(obj,method){switch(type(method)){case"object":return aliasByDictionary(clone(obj),method);case"function":return aliasByFunction(clone(obj),method)}}function aliasByDictionary(obj,aliases){for(var key in aliases){if(undefined===obj[key])continue;obj[aliases[key]]=obj[key];delete obj[key]}return obj}function aliasByFunction(obj,convert){var output={};for(var key in obj)output[convert(key)]=obj[key];return output}},{type:7,clone:166}],179:[function(require,module,exports){var is=require("is");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=convertDates;function convertDates(obj,convert){obj=clone(obj);for(var key in obj){var val=obj[key];if(is.date(val))obj[key]=convert(val);if(is.object(val))obj[key]=convertDates(val,convert)}return obj}},{is:91,clone:95}],29:[function(require,module,exports){
var alias=require("alias");var integration=require("analytics.js-integration");var is=require("is");var load=require("load-script");var push=require("global-queue")("_dcq");var Drip=module.exports=integration("Drip").assumesPageview().global("_dc").global("_dcqi").global("_dcq").global("_dcs").option("account","").tag('<script src="//tag.getdrip.com/{{ account }}.js">');Drip.prototype.initialize=function(page){window._dcq=window._dcq||[];window._dcs=window._dcs||{};window._dcs.account=this.options.account;this.load(this.ready)};Drip.prototype.loaded=function(){return is.object(window._dc)};Drip.prototype.track=function(track){var props=track.properties();var cents=track.cents();if(cents)props.value=cents;delete props.revenue;push("track",track.event(),props)};Drip.prototype.identify=function(identify){push("identify",identify.traits())}},{alias:178,"analytics.js-integration":88,is:91,"load-script":143,"global-queue":174}],30:[function(require,module,exports){var extend=require("extend");var integration=require("analytics.js-integration");var onError=require("on-error");var push=require("global-queue")("_errs");var Errorception=module.exports=integration("Errorception").assumesPageview().global("_errs").option("projectId","").option("meta",true).tag('<script src="//beacon.errorception.com/{{ projectId }}.js">');Errorception.prototype.initialize=function(page){window._errs=window._errs||[this.options.projectId];onError(push);this.load(this.ready)};Errorception.prototype.loaded=function(){return!!(window._errs&&window._errs.push!==Array.prototype.push)};Errorception.prototype.identify=function(identify){if(!this.options.meta)return;var traits=identify.traits();window._errs=window._errs||[];window._errs.meta=window._errs.meta||{};extend(window._errs.meta,traits)}},{extend:145,"analytics.js-integration":88,"on-error":172,"global-queue":174}],31:[function(require,module,exports){var each=require("each");var integration=require("analytics.js-integration");var push=require("global-queue")("_aaq");var Evergage=module.exports=integration("Evergage").assumesPageview().global("_aaq").option("account","").option("dataset","").tag('<script src="//cdn.evergage.com/beacon/{{ account }}/{{ dataset }}/scripts/evergage.min.js">');Evergage.prototype.initialize=function(page){var account=this.options.account;var dataset=this.options.dataset;window._aaq=window._aaq||[];push("setEvergageAccount",account);push("setDataset",dataset);push("setUseSiteConfig",true);this.load(this.ready)};Evergage.prototype.loaded=function(){return!!(window._aaq&&window._aaq.push!==Array.prototype.push)};Evergage.prototype.page=function(page){var props=page.properties();var name=page.name();if(name)push("namePage",name);each(props,function(key,value){push("setCustomField",key,value,"page")});window.Evergage.init(true)};Evergage.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("setUser",id);var traits=identify.traits({email:"userEmail",name:"userName"});each(traits,function(key,value){push("setUserField",key,value,"page")})};Evergage.prototype.group=function(group){var props=group.traits();var id=group.groupId();if(!id)return;push("setCompany",id);each(props,function(key,value){push("setAccountField",key,value,"page")})};Evergage.prototype.track=function(track){push("trackAction",track.event(),track.properties())}},{each:4,"analytics.js-integration":88,"global-queue":174}],32:[function(require,module,exports){"use strict";var bind=require("bind");var domify=require("domify");var each=require("each");var extend=require("extend");var integration=require("analytics.js-integration");var json=require("json");var Extole=module.exports=integration("Extole").global("extole").option("clientId","").mapping("events").tag("main",'<script src="//tags.extole.com/{{ clientId }}/core.js">');Extole.prototype.initialize=function(){if(this.loaded())return this.ready();this.load("main",bind(this,this.ready))};Extole.prototype.loaded=function(){return!!window.extole};Extole.prototype.track=function(track){var user=this.analytics.user();var traits=user.traits();var userId=user.id();var email=traits.email;if(!userId&&!email){return this.debug("User must be identified before `#track` calls")}var event=track.event();var extoleEvents=this.events(event);if(!extoleEvents.length){return this.debug("No events found for %s",event)}each(extoleEvents,bind(this,function(extoleEvent){this._registerConversion(this._createConversionTag({type:extoleEvent,params:this._formatConversionParams(event,email,userId,track.properties())}))}))};Extole.prototype._registerConversion=function(conversionTag){if(window.extole.main&&window.extole.main.fireConversion){return window.extole.main.fireConversion(conversionTag)}if(window.extole.initializeGo){window.extole.initializeGo().andWhenItsReady(function(){window.extole.main.fireConversion(conversionTag)})}};Extole.prototype._formatConversionParams=function(event,email,userId,properties){var total;if(properties.total){total=properties.total;delete properties.total;properties["tag:cart_value"]=total}return extend({"tag:segment_event":event,e:email,partner_conversion_id:userId},properties)};Extole.prototype._createConversionTag=function(conversion){return domify('<script type="extole/conversion">'+json.stringify(conversion)+"</script>")}},{bind:101,domify:119,each:4,extend:145,"analytics.js-integration":88,json:180}],180:[function(require,module,exports){var json=window.JSON||{};var stringify=json.stringify;var parse=json.parse;module.exports=parse&&stringify?JSON:require("json-fallback")},{"json-fallback":181}],181:[function(require,module,exports){(function(){"use strict";var JSON=module.exports={};function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()}}var cx,escapable,gap,indent,meta,rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==="string"){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function"){escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else if(typeof space==="string"){indent=space}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}})()},{}],33:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_fbq");var each=require("each");var has=Object.prototype.hasOwnProperty;var Facebook=module.exports=integration("Facebook Conversion Tracking").global("_fbq").option("currency","USD").tag('<script src="//connect.facebook.net/en_US/fbds.js">').mapping("events");Facebook.prototype.initialize=function(page){window._fbq=window._fbq||[];this.load(this.ready);window._fbq.loaded=true};Facebook.prototype.loaded=function(){return!!(window._fbq&&window._fbq.loaded)};Facebook.prototype.page=function(page){var name=page.fullName();this.track(page.track(name))};Facebook.prototype.track=function(track){var event=track.event();var events=this.events(event);var revenue=track.revenue()||0;var self=this;each(events,function(event){push("track",event,{value:String(revenue.toFixed(2)),currency:self.options.currency})})}},{"analytics.js-integration":88,"global-queue":174,each:4}],34:[function(require,module,exports){var push=require("global-queue")("_fxm");var integration=require("analytics.js-integration");var Track=require("facade").Track;var each=require("each");var FoxMetrics=module.exports=integration("FoxMetrics").assumesPageview().global("_fxm").option("appId","").tag('<script src="//d35tca7vmefkrc.cloudfront.net/scripts/{{ appId }}.js">');FoxMetrics.prototype.initialize=function(page){window._fxm=window._fxm||[];this.load(this.ready)};FoxMetrics.prototype.loaded=function(){return!!(window._fxm&&window._fxm.appId)};FoxMetrics.prototype.page=function(page){var properties=page.proxy("properties");var category=page.category();var name=page.name();this._category=category;push("_fxm.pages.view",properties.title,name,category,properties.url,properties.referrer)};FoxMetrics.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("_fxm.visitor.profile",id,identify.firstName(),identify.lastName(),identify.email(),identify.address(),undefined,undefined,identify.traits())};FoxMetrics.prototype.track=function(track){var props=track.properties();var category=this._category||props.category;push(track.event(),category,props)};FoxMetrics.prototype.viewedProduct=function(track){ecommerce("productview",track)};FoxMetrics.prototype.removedProduct=function(track){ecommerce("removecartitem",track)};FoxMetrics.prototype.addedProduct=function(track){ecommerce("cartitem",track)};FoxMetrics.prototype.completedOrder=function(track){var orderId=track.orderId();push("_fxm.ecommerce.order",orderId,track.subtotal(),track.shipping(),track.tax(),track.city(),track.state(),track.zip(),track.quantity());each(track.products(),function(product){var track=new Track({properties:product});ecommerce("purchaseitem",track,[track.quantity(),track.price(),orderId])})};function ecommerce(event,track,arr){push.apply(null,["_fxm.ecommerce."+event,track.id()||track.sku(),track.name(),track.category()].concat(arr||[]))}},{"global-queue":174,"analytics.js-integration":88,facade:147,each:4}],35:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var is=require("is");var Frontleaf=module.exports=integration("Frontleaf").global("_fl").global("_flBaseUrl").option("baseUrl","https://api.frontleaf.com").option("token","").option("stream","").option("trackNamedPages",false).option("trackCategorizedPages",false).tag('<script id="_fl" src="{{ baseUrl }}/lib/tracker.js">');Frontleaf.prototype.initialize=function(page){window._fl=window._fl||[];window._flBaseUrl=window._flBaseUrl||this.options.baseUrl;this._push("setApiToken",this.options.token);this._push("setStream",this.options.stream);var loaded=bind(this,this.loaded);var ready=this.ready;this.load({baseUrl:window._flBaseUrl},this.ready)};Frontleaf.prototype.loaded=function(){return is.array(window._fl)&&window._fl.ready===true};Frontleaf.prototype.identify=function(identify){var userId=identify.userId();if(userId){this._push("setUser",{id:userId,name:identify.name()||identify.username(),data:clean(identify.traits())})}};Frontleaf.prototype.group=function(group){var groupId=group.groupId();if(groupId){this._push("setAccount",{id:groupId,name:group.proxy("traits.name"),data:clean(group.traits())})}};Frontleaf.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Frontleaf.prototype.track=function(track){var event=track.event();this._push("event",event,clean(track.properties()))};Frontleaf.prototype._push=function(command){var args=[].slice.call(arguments,1);window._fl.push(function(t){t[command].apply(command,args)})};function clean(obj){var ret={};var excludeKeys=["id","name","firstName","lastName"];var len=excludeKeys.length;for(var i=0;i<len;i++){clear(obj,excludeKeys[i])}obj=flatten(obj);for(var key in obj){var val=obj[key];if(null==val){continue}if(is.array(val)){ret[key]=val.toString();continue}ret[key]=val}return ret}function clear(obj,key){if(obj.hasOwnProperty(key)){delete obj[key]}}function flatten(source){var output={};function step(object,prev){for(var key in object){var value=object[key];var newKey=prev?prev+" "+key:key;if(!is.array(value)&&is.object(value)){return step(value,newKey)}output[newKey]=value}}step(source);return output}},{"analytics.js-integration":88,bind:101,when:146,is:91}],36:[function(require,module,exports){var each=require("each");var is=require("is");var del=require("obj-case").del;var camel=require("to-camel-case");var integration=require("analytics.js-integration");var FullStory=module.exports=integration("FullStory").option("org","").option("debug",false).tag('<script src="https://www.fullstory.com/s/fs.js"></script>');FullStory.prototype.initialize=function(){var self=this;window._fs_debug=this.options.debug;window._fs_host="www.fullstory.com";window._fs_org=this.options.org;(function(m,n,e,t,l,o,g,y){g=m[e]=function(a,b){g.q?g.q.push([a,b]):g._api(a,b)};g.q=[];g.identify=function(i,v){g(l,{uid:i});if(v)g(l,v)};g.setUserVars=function(v){FS(l,v)};g.setSessionVars=function(v){FS("session",v)};g.setPageVars=function(v){FS("page",v)};self.ready();self.load()})(window,document,"FS","script","user")};FullStory.prototype.loaded=function(){return!!window.FS};FullStory.prototype.identify=function(identify){var id=identify.userId()||identify.anonymousId();var traits=identify.traits();del(traits,"id");if(identify.name()){traits.displayName=identify.name();del(traits,"name")}each(traits,function(trait,value){if(trait!=="displayName"&&trait!=="email"){var newTrait=convert(trait,value);traits[newTrait]=value;del(traits,trait)}});if(typeof id!=="string")id=""+id;window.FS.identify(id,traits)};function convert(trait,value){trait=camel(trait);if(is.string(value))return trait+="_str";if(isInt(value))return trait+="_int";if(isFloat(value))return trait+="_real";if(is.date(value))return trait+="_date";if(is.boolean(value))return trait+="_bool"}function isFloat(n){return n===+n&&n!==(n|0)}function isInt(n){return n===+n&&n===(n|0)}},{each:4,is:91,"obj-case":92,"to-camel-case":182,"analytics.js-integration":88}],182:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toCamelCase;function toCamelCase(string){return toSpace(string).replace(/\s(\w)/g,function(matches,letter){return letter.toUpperCase()})}},{"to-space-case":120}],37:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_gauges");var Gauges=module.exports=integration("Gauges").assumesPageview().global("_gauges").option("siteId","").tag('<script id="gauges-tracker" src="//secure.gaug.es/track.js" data-site-id="{{ siteId }}">');Gauges.prototype.initialize=function(page){window._gauges=window._gauges||[];this.load(this.ready)};Gauges.prototype.loaded=function(){return!!(window._gauges&&window._gauges.push!==Array.prototype.push)};Gauges.prototype.page=function(page){push("track")}},{"analytics.js-integration":88,"global-queue":174}],38:[function(require,module,exports){var integration=require("analytics.js-integration");var onBody=require("on-body");var GetSatisfaction=module.exports=integration("Get Satisfaction").assumesPageview().global("GSFN").option("widgetId","").tag('<script src="https://loader.engage.gsfn.us/loader.js">');GetSatisfaction.prototype.initialize=function(page){var self=this;var widget=this.options.widgetId;var div=document.createElement("div");var id=div.id="getsat-widget-"+widget;onBody(function(body){body.appendChild(div)});this.load(function(){window.GSFN.loadWidget(widget,{containerId:id});self.ready()})};GetSatisfaction.prototype.loaded=function(){return!!window.GSFN}},{"analytics.js-integration":88,"on-body":144}],39:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_gaq");var length=require("object").length;var canonical=require("canonical");var useHttps=require("use-https");var Track=require("facade").Track;var callback=require("callback");var defaults=require("defaults");var load=require("load-script");var keys=require("object").keys;var select=require("select");var dot=require("obj-case");var each=require("each");var type=require("type");var url=require("url");var is=require("is");var group;var user;module.exports=exports=function(analytics){analytics.addIntegration(GA);group=analytics.group();user=analytics.user()};var GA=exports.Integration=integration("Google Analytics").readyOnLoad().global("ga").global("gaplugins").global("_gaq").global("GoogleAnalyticsObject").option("anonymizeIp",false).option("classic",false).option("domain","auto").option("doubleClick",false).option("enhancedEcommerce",false).option("enhancedLinkAttribution",false).option("nonInteraction",false).option("ignoredReferrers",null).option("includeSearch",false).option("siteSpeedSampleRate",1).option("trackingId","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("sendUserId",false).option("metrics",{}).option("dimensions",{}).tag("library",'<script src="//www.google-analytics.com/analytics.js">').tag("double click",'<script src="//stats.g.doubleclick.net/dc.js">').tag("http",'<script src="http://www.google-analytics.com/ga.js">').tag("https",'<script src="https://ssl.google-analytics.com/ga.js">');GA.on("construct",function(integration){if(integration.options.classic){integration.initialize=integration.initializeClassic;integration.loaded=integration.loadedClassic;integration.page=integration.pageClassic;integration.track=integration.trackClassic;integration.completedOrder=integration.completedOrderClassic}else if(integration.options.enhancedEcommerce){integration.viewedProduct=integration.viewedProductEnhanced;integration.clickedProduct=integration.clickedProductEnhanced;integration.addedProduct=integration.addedProductEnhanced;integration.removedProduct=integration.removedProductEnhanced;integration.startedOrder=integration.startedOrderEnhanced;integration.viewedCheckoutStep=integration.viewedCheckoutStepEnhanced;integration.completedCheckoutStep=integration.completedCheckoutStepEnhanced;integration.updatedOrder=integration.updatedOrderEnhanced;integration.completedOrder=integration.completedOrderEnhanced;integration.refundedOrder=integration.refundedOrderEnhanced;integration.viewedPromotion=integration.viewedPromotionEnhanced;integration.clickedPromotion=integration.clickedPromotionEnhanced}});GA.prototype.initialize=function(){var opts=this.options;window.GoogleAnalyticsObject="ga";window.ga=window.ga||function(){window.ga.q=window.ga.q||[];window.ga.q.push(arguments)};window.ga.l=(new Date).getTime();if(window.location.hostname==="localhost")opts.domain="none";window.ga("create",opts.trackingId,{cookieDomain:opts.domain||GA.prototype.defaults.domain,siteSpeedSampleRate:opts.siteSpeedSampleRate,allowLinker:true});if(opts.doubleClick){window.ga("require","displayfeatures")}if(opts.sendUserId&&user.id()){window.ga("set","userId",user.id())}if(opts.anonymizeIp)window.ga("set","anonymizeIp",true);var custom=metrics(user.traits(),opts);if(length(custom))window.ga("set",custom);this.load("library",this.ready)};GA.prototype.loaded=function(){return!!window.gaplugins};GA.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;var campaign=page.proxy("context.campaign")||{};var pageview={};var track;this._category=category;pageview.page=path(props,this.options);pageview.title=name||props.title;pageview.location=props.url;if(campaign.name)pageview.campaignName=campaign.name;if(campaign.source)pageview.campaignSource=campaign.source;if(campaign.medium)pageview.campaignMedium=campaign.medium;if(campaign.content)pageview.campaignContent=campaign.content;if(campaign.term)pageview.campaignKeyword=campaign.term;var custom=metrics(props,opts);if(length(custom))window.ga("set",custom);window.ga("send","pageview",pageview);if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{nonInteraction:1})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{nonInteraction:1})}};GA.prototype.identify=function(identify){var opts=this.options;if(opts.sendUserId&&identify.userId()){window.ga("set","userId",identify.userId())}var custom=metrics(user.traits(),opts);if(length(custom))window.ga("set",custom)};GA.prototype.track=function(track,options){var contextOpts=track.options(this.name);var interfaceOpts=this.options;var opts=defaults(options||{},contextOpts);opts=defaults(opts,interfaceOpts);var props=track.properties();var campaign=track.proxy("context.campaign")||{};var custom=metrics(props,interfaceOpts);if(length(custom))window.ga("set",custom);var payload={eventAction:track.event(),eventCategory:props.category||this._category||"All",eventLabel:props.label,eventValue:formatValue(props.value||track.revenue()),nonInteraction:!!(props.nonInteraction||opts.nonInteraction)};if(campaign.name)payload.campaignName=campaign.name;if(campaign.source)payload.campaignSource=campaign.source;if(campaign.medium)payload.campaignMedium=campaign.medium;if(campaign.content)payload.campaignContent=campaign.content;if(campaign.term)payload.campaignKeyword=campaign.term;window.ga("send","event",payload)};GA.prototype.completedOrder=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products();var props=track.properties();if(!orderId)return;if(!this.ecommerce){window.ga("require","ecommerce");this.ecommerce=true}window.ga("ecommerce:addTransaction",{affiliation:props.affiliation,shipping:track.shipping(),revenue:total,tax:track.tax(),id:orderId,currency:track.currency()});each(products,function(product){var track=new Track({properties:product});window.ga("ecommerce:addItem",{category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name(),sku:track.sku(),id:orderId,currency:track.currency()})});window.ga("ecommerce:send")};GA.prototype.initializeClassic=function(){var opts=this.options;var anonymize=opts.anonymizeIp;var db=opts.doubleClick;var domain=opts.domain;var enhanced=opts.enhancedLinkAttribution;var ignore=opts.ignoredReferrers;var sample=opts.siteSpeedSampleRate;window._gaq=window._gaq||[];push("_setAccount",opts.trackingId);push("_setAllowLinker",true);if(anonymize)push("_gat._anonymizeIp");if(domain)push("_setDomainName",domain);if(sample)push("_setSiteSpeedSampleRate",sample);if(enhanced){var protocol="https:"===document.location.protocol?"https:":"http:";var pluginUrl=protocol+"//www.google-analytics.com/plugins/ga/inpage_linkid.js";push("_require","inpage_linkid",pluginUrl)}if(ignore){if(!is.array(ignore))ignore=[ignore];each(ignore,function(domain){push("_addIgnoredRef",domain)})}if(this.options.doubleClick){this.load("double click",this.ready)}else{var name=useHttps()?"https":"http";this.load(name,this.ready)}};GA.prototype.loadedClassic=function(){return!!(window._gaq&&window._gaq.push!==Array.prototype.push)};GA.prototype.pageClassic=function(page){var opts=page.options(this.name);var category=page.category();var props=page.properties();var name=page.fullName();var track;push("_trackPageview",path(props,this.options));if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{nonInteraction:1})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{nonInteraction:1})}};GA.prototype.trackClassic=function(track,options){var opts=options||track.options(this.name);var props=track.properties();var revenue=track.revenue();var event=track.event();var category=this._category||props.category||"All";var label=props.label;var value=formatValue(revenue||props.value);var nonInteraction=!!(props.nonInteraction||opts.nonInteraction);push("_trackEvent",category,event,label,value,nonInteraction)};GA.prototype.completedOrderClassic=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products()||[];var props=track.properties();var currency=track.currency();if(!orderId)return;push("_addTrans",orderId,props.affiliation,total,track.tax(),track.shipping(),track.city(),track.state(),track.country());each(products,function(product){var track=new Track({properties:product});push("_addItem",orderId,track.sku(),track.name(),track.category(),track.price(),track.quantity())});push("_set","currencyCode",currency);push("_trackTrans")};function path(properties,options){if(!properties)return;var str=properties.path;if(options.includeSearch&&properties.search)str+=properties.search;return str}function formatValue(value){if(!value||value<0)return 0;return Math.round(value)}function metrics(obj,data){var dimensions=data.dimensions;var metrics=data.metrics;var names=keys(metrics).concat(keys(dimensions));var ret={};for(var i=0;i<names.length;++i){var name=names[i];var key=metrics[name]||dimensions[name];var value=dot(obj,name)||obj[name];if(null==value)continue;ret[key]=value}return ret}GA.prototype.loadEnhancedEcommerce=function(track){if(!this.enhancedEcommerceLoaded){window.ga("require","ec");this.enhancedEcommerceLoaded=true}window.ga("set","&cu",track.currency())};GA.prototype.pushEnhancedEcommerce=function(track){ga("send","event",track.category()||"EnhancedEcommerce",track.event(),{nonInteraction:1})};GA.prototype.startedOrderEnhanced=function(track){this.viewedCheckoutStep(track)};GA.prototype.updatedOrderEnhanced=function(track){this.startedOrderEnhanced(track)};GA.prototype.viewedCheckoutStepEnhanced=function(track){var products=track.products();var props=track.properties();var options=extractCheckoutOptions(props);this.loadEnhancedEcommerce(track);each(products,function(product){var trackTemp=new Track({properties:product});enhancedEcommerceTrackProduct(trackTemp)});window.ga("ec:setAction","checkout",{step:props.step||1,option:options||undefined});this.pushEnhancedEcommerce(track)};GA.prototype.completedCheckoutStepEnhanced=function(track){var props=track.properties();var options=extractCheckoutOptions(props);if(!props.step||!options)return;this.loadEnhancedEcommerce(track);window.ga("ec:setAction","checkout_option",{step:props.step||1,option:options});window.ga("send","event","Checkout","Option")};GA.prototype.completedOrderEnhanced=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products();var props=track.properties();if(!orderId)return;this.loadEnhancedEcommerce(track);each(products,function(product){var track=new Track({properties:product});enhancedEcommerceTrackProduct(track)});window.ga("ec:setAction","purchase",{id:orderId,affiliation:props.affiliation,revenue:total,tax:track.tax(),shipping:track.shipping(),coupon:track.coupon()});this.pushEnhancedEcommerce(track)};GA.prototype.refundedOrderEnhanced=function(track){var orderId=track.orderId();var products=track.products();if(!orderId)return;this.loadEnhancedEcommerce(track);each(products,function(product){var track=new Track({properties:product});window.ga("ec:addProduct",{id:track.id()||track.sku(),quantity:track.quantity()})});window.ga("ec:setAction","refund",{id:orderId});this.pushEnhancedEcommerce(track)};GA.prototype.addedProductEnhanced=function(track){this.loadEnhancedEcommerce(track);enhancedEcommerceProductAction(track,"add");this.pushEnhancedEcommerce(track)};GA.prototype.removedProductEnhanced=function(track){this.loadEnhancedEcommerce(track);enhancedEcommerceProductAction(track,"remove");this.pushEnhancedEcommerce(track)};GA.prototype.viewedProductEnhanced=function(track){this.loadEnhancedEcommerce(track);enhancedEcommerceProductAction(track,"detail");this.pushEnhancedEcommerce(track)};GA.prototype.clickedProductEnhanced=function(track){var props=track.properties();this.loadEnhancedEcommerce(track);enhancedEcommerceProductAction(track,"click",{list:props.list});this.pushEnhancedEcommerce(track)};GA.prototype.viewedPromotionEnhanced=function(track){var props=track.properties();this.loadEnhancedEcommerce(track);window.ga("ec:addPromo",{id:track.id(),name:track.name(),creative:props.creative,position:props.position});this.pushEnhancedEcommerce(track)};GA.prototype.clickedPromotionEnhanced=function(track){var props=track.properties();this.loadEnhancedEcommerce(track);window.ga("ec:addPromo",{id:track.id(),name:track.name(),creative:props.creative,position:props.position});ga("ec:setAction","promo_click",{});this.pushEnhancedEcommerce(track)};function enhancedEcommerceTrackProduct(track){var props=track.properties();window.ga("ec:addProduct",{id:track.id()||track.sku(),name:track.name(),category:track.category(),quantity:track.quantity(),price:track.price(),brand:props.brand,variant:props.variant})}function enhancedEcommerceProductAction(track,action,data){enhancedEcommerceTrackProduct(track);window.ga("ec:setAction",action,data||{})}function extractCheckoutOptions(props){var options=[props.paymentMethod,props.shippingMethod];var valid=select(options,function(e){return e});return valid.length>0?valid.join(", "):null}},{"analytics.js-integration":88,"global-queue":174,object:183,canonical:184,"use-https":90,facade:147,callback:94,defaults:173,"load-script":143,select:185,"obj-case":92,each:4,type:113,url:186,is:91}],183:[function(require,module,exports){var has=Object.prototype.hasOwnProperty;exports.keys=Object.keys||function(obj){var keys=[];for(var key in obj){if(has.call(obj,key)){keys.push(key)}}return keys};exports.values=function(obj){var vals=[];for(var key in obj){if(has.call(obj,key)){vals.push(obj[key])}}return vals};exports.merge=function(a,b){for(var key in b){if(has.call(b,key)){a[key]=b[key]}}return a};exports.length=function(obj){return exports.keys(obj).length};exports.isEmpty=function(obj){return 0==exports.length(obj)}},{}],184:[function(require,module,exports){
module.exports=function canonical(){var tags=document.getElementsByTagName("link");for(var i=0,tag;tag=tags[i];i++){if("canonical"==tag.getAttribute("rel"))return tag.getAttribute("href")}}},{}],185:[function(require,module,exports){var toFunction=require("to-function");module.exports=function(arr,fn){var ret=[];fn=toFunction(fn);for(var i=0;i<arr.length;++i){if(fn(arr[i],i)){ret.push(arr[i])}}return ret}},{"to-function":187}],187:[function(require,module,exports){var expr;try{expr=require("props")}catch(e){expr=require("component-props")}module.exports=toFunction;function toFunction(obj){switch({}.toString.call(obj)){case"[object Object]":return objectToFunction(obj);case"[object Function]":return obj;case"[object String]":return stringToFunction(obj);case"[object RegExp]":return regexpToFunction(obj);default:return defaultToFunction(obj)}}function defaultToFunction(val){return function(obj){return val===obj}}function regexpToFunction(re){return function(obj){return re.test(obj)}}function stringToFunction(str){if(/^ *\W+/.test(str))return new Function("_","return _ "+str);return new Function("_","return "+get(str))}function objectToFunction(obj){var match={};for(var key in obj){match[key]=typeof obj[key]==="string"?defaultToFunction(obj[key]):toFunction(obj[key])}return function(val){if(typeof val!=="object")return false;for(var key in match){if(!(key in val))return false;if(!match[key](val[key]))return false}return true}}function get(str){var props=expr(str);if(!props.length)return"_."+str;var val,i,prop;for(i=0;i<props.length;i++){prop=props[i];val="_."+prop;val="('function' == typeof "+val+" ? "+val+"() : "+val+")";str=stripNested(prop,str,val)}return str}function stripNested(prop,str,val){return str.replace(new RegExp("(\\.)?"+prop,"g"),function($0,$1){return $1?$0:val})}},{props:118,"component-props":118}],186:[function(require,module,exports){exports.parse=function(url){var a=document.createElement("a");a.href=url;return{href:a.href,host:a.host,port:a.port,hash:a.hash,hostname:a.hostname,pathname:a.pathname,protocol:a.protocol,search:a.search,query:a.search.slice(1)}};exports.isAbsolute=function(url){if(0==url.indexOf("//"))return true;if(~url.indexOf("://"))return true;return false};exports.isRelative=function(url){return!exports.isAbsolute(url)};exports.isCrossDomain=function(url){url=exports.parse(url);return url.hostname!=location.hostname||url.port!=location.port||url.protocol!=location.protocol}},{}],40:[function(require,module,exports){var push=require("global-queue")("dataLayer",{wrap:false});var integration=require("analytics.js-integration");var GTM=module.exports=integration("Google Tag Manager").assumesPageview().global("dataLayer").global("google_tag_manager").option("containerId","").option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//www.googletagmanager.com/gtm.js?id={{ containerId }}&l=dataLayer">');GTM.prototype.initialize=function(){push({"gtm.start":+new Date,event:"gtm.js"});this.load(this.ready)};GTM.prototype.loaded=function(){return!!(window.dataLayer&&[].push!=window.dataLayer.push)};GTM.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;var track;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};GTM.prototype.track=function(track){var props=track.properties();props.event=track.event();push(props)}},{"global-queue":174,"analytics.js-integration":88}],41:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var Track=require("facade").Track;var callback=require("callback");var load=require("load-script");var onBody=require("on-body");var each=require("each");var is=require("is");var pick=require("pick");var omit=require("omit");var GoSquared=module.exports=integration("GoSquared").assumesPageview().global("_gs").option("siteToken","").option("anonymizeIP",false).option("cookieDomain",null).option("useCookies",true).option("trackHash",false).option("trackLocal",false).option("trackParams",true).tag('<script src="//d1l6p2sc9645hc.cloudfront.net/tracker.js">');GoSquared.prototype.initialize=function(page){var self=this;var options=this.options;var user=this.analytics.user();push(options.siteToken);each(options,function(name,value){if("siteToken"==name)return;if(null==value)return;push("set",name,value)});self.identify(new Identify({traits:user.traits(),userId:user.id()}));self.load(this.ready)};GoSquared.prototype.loaded=function(){return!!(window._gs&&window._gs.v)};GoSquared.prototype.page=function(page){var props=page.properties();var name=page.fullName();push("track",props.path,name||props.title)};GoSquared.prototype.identify=function(identify){var traits=identify.traits({createdAt:"created_at",firstName:"first_name",lastName:"last_name",title:"company_position",industry:"company_industry"});var specialKeys=["id","email","name","first_name","last_name","username","description","avatar","phone","created_at","company_name","company_size","company_position","company_industry"];var props=pick.apply(null,[traits].concat(specialKeys));props.custom=omit(specialKeys,traits);var id=identify.userId();if(id){push("identify",id,props)}else{push("properties",props)}var email=identify.email();var username=identify.username();var name=email||username||id;if(name)push("set","visitorName",name)};GoSquared.prototype.track=function(track){push("event",track.event(),track.properties())};GoSquared.prototype.completedOrder=function(track){var products=track.products();var items=[];each(products,function(product){var track=new Track({properties:product});items.push({category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name()})});push("transaction",track.orderId(),{revenue:track.total(),track:true},items)};function push(){var _gs=window._gs=window._gs||function(){(_gs.q=_gs.q||[]).push(arguments)};_gs.apply(null,arguments)}},{"analytics.js-integration":88,facade:147,callback:94,"load-script":143,"on-body":144,each:4,is:91,pick:188,omit:189}],188:[function(require,module,exports){module.exports=pick;function pick(obj){var keys=[].slice.call(arguments,1);var ret={};for(var i=0,key;key=keys[i];i++){if(key in obj)ret[key]=obj[key]}return ret}},{}],189:[function(require,module,exports){module.exports=omit;function omit(keys,object){var ret={};for(var item in object){ret[item]=object[item]}for(var i=0;i<keys.length;i++){delete ret[keys[i]]}return ret}},{}],42:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Heap=module.exports=integration("Heap").global("heap").option("appId","").tag('<script src="//cdn.heapanalytics.com/js/heap-{{ appId }}.js">');Heap.prototype.initialize=function(page){window.heap=window.heap||[];window.heap.load=function(appid,config){window.heap.appid=appid;window.heap.config=config;var methodFactory=function(type){return function(){heap.push([type].concat(Array.prototype.slice.call(arguments,0)))}};var methods=["clearEventProperties","identify","setEventProperties","track","unsetEventProperty"];for(var i=0;i<methods.length;i++){heap[methods[i]]=methodFactory(methods[i])}};window.heap.load(this.options.appId);this.load(this.ready)};Heap.prototype.loaded=function(){return window.heap&&window.heap.appid};Heap.prototype.identify=function(identify){var traits=identify.traits({email:"_email"});var id=identify.userId();if(id)traits.handle=id;window.heap.identify(traits)};Heap.prototype.track=function(track){window.heap.track(track.event(),track.properties())}},{"analytics.js-integration":88,alias:178}],43:[function(require,module,exports){var integration=require("analytics.js-integration");var Hellobar=module.exports=integration("Hello Bar").assumesPageview().global("_hbq").option("apiKey","").tag('<script src="//s3.amazonaws.com/scripts.hellobar.com/{{ apiKey }}.js">');Hellobar.prototype.initialize=function(page){window._hbq=window._hbq||[];this.load(this.ready)};Hellobar.prototype.loaded=function(){return!!(window._hbq&&window._hbq.push!==Array.prototype.push)}},{"analytics.js-integration":88}],44:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var HitTail=module.exports=integration("HitTail").assumesPageview().global("htk").option("siteId","").tag('<script src="//{{ siteId }}.hittail.com/mlt.js">');HitTail.prototype.initialize=function(page){this.load(this.ready)};HitTail.prototype.loaded=function(){return is.fn(window.htk)}},{"analytics.js-integration":88,is:91}],45:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_hsq");var convert=require("convert-dates");var HubSpot=module.exports=integration("HubSpot").assumesPageview().global("_hsq").option("portalId",null).tag('<script id="hs-analytics" src="https://js.hs-analytics.net/analytics/{{ cache }}/{{ portalId }}.js">');HubSpot.prototype.initialize=function(page){window._hsq=[];var cache=Math.ceil(new Date/3e5)*3e5;this.load({cache:cache},this.ready)};HubSpot.prototype.loaded=function(){return!!(window._hsq&&window._hsq.push!==Array.prototype.push)};HubSpot.prototype.page=function(page){push("_trackPageview")};HubSpot.prototype.identify=function(identify){if(!identify.email())return;var traits=identify.traits();traits=convertDates(traits);push("identify",traits)};HubSpot.prototype.track=function(track){var props=track.properties();props=convertDates(props);push("trackEvent",track.event(),props)};function convertDates(properties){return convert(properties,function(date){return date.getTime()})}},{"analytics.js-integration":88,"global-queue":174,"convert-dates":179}],46:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Improvely=module.exports=integration("Improvely").assumesPageview().global("_improvely").global("improvely").option("domain","").option("projectId",null).tag('<script src="//{{ domain }}.iljmp.com/improvely.js">');Improvely.prototype.initialize=function(page){window._improvely=[];window.improvely={init:function(e,t){window._improvely.push(["init",e,t])},goal:function(e){window._improvely.push(["goal",e])},label:function(e){window._improvely.push(["label",e])}};var domain=this.options.domain;var id=this.options.projectId;window.improvely.init(domain,id);this.load(this.ready)};Improvely.prototype.loaded=function(){return!!(window.improvely&&window.improvely.identify)};Improvely.prototype.identify=function(identify){var id=identify.userId();if(id)window.improvely.label(id)};Improvely.prototype.track=function(track){var props=track.properties({revenue:"amount"});props.type=track.event();window.improvely.goal(props)}},{"analytics.js-integration":88,alias:178}],47:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_iva");var Track=require("facade").Track;var each=require("each");var is=require("is");var has=Object.prototype.hasOwnProperty;var InsideVault=module.exports=integration("InsideVault").global("_iva").option("clientId","").option("domain","").tag('<script src="//analytics.staticiv.com/iva.js">').mapping("events");InsideVault.prototype.initialize=function(page){var domain=this.options.domain;window._iva=window._iva||[];push("setClientId",this.options.clientId);var userId=this.analytics.user().id();if(userId)push("setUserId",userId);if(domain)push("setDomain",domain);this.load(this.ready)};InsideVault.prototype.loaded=function(){return!!(window._iva&&window._iva.push!==Array.prototype.push)};InsideVault.prototype.identify=function(identify){push("setUserId",identify.userId())};InsideVault.prototype.page=function(page){push("trackEvent","click")};InsideVault.prototype.track=function(track){var user=this.analytics.user();var events=this.events(track.event());var value=track.revenue()||track.value()||0;var eventId=track.orderId()||user.id()||"";each(events,function(event){if(event!="sale"){push("trackEvent",event,value,eventId)}})}},{"analytics.js-integration":88,"global-queue":174,facade:147,each:4,is:91}],48:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("__insp");var alias=require("alias");var clone=require("clone");var Inspectlet=module.exports=integration("Inspectlet").assumesPageview().global("__insp").global("__insp_").option("wid","").tag('<script src="//cdn.inspectlet.com/inspectlet.js">');Inspectlet.prototype.initialize=function(page){push("wid",this.options.wid);this.load(this.ready)};Inspectlet.prototype.loaded=function(){return!!(window.__insp_&&window.__insp)};Inspectlet.prototype.identify=function(identify){var traits=identify.traits({id:"userid"});push("tagSession",traits)};Inspectlet.prototype.track=function(track){push("tagSession",track.event())};Inspectlet.prototype.page=function(){push("virtualPage")}},{"analytics.js-integration":88,"global-queue":174,alias:178,clone:95}],49:[function(require,module,exports){var integration=require("analytics.js-integration");var convertDates=require("convert-dates");var defaults=require("defaults");var del=require("obj-case").del;var isEmail=require("is-email");var load=require("load-script");var empty=require("is-empty");var alias=require("alias");var each=require("each");var when=require("when");var is=require("is");var Intercom=module.exports=integration("Intercom").assumesPageview().global("Intercom").option("activator","#IntercomDefaultWidget").option("appId","").option("inbox",false).tag('<script src="https://static.intercomcdn.com/intercom.v1.js">');Intercom.prototype.initialize=function(page){var self=this;this.load(function(){when(function(){return self.loaded()},self.ready)})};Intercom.prototype.loaded=function(){return is.fn(window.Intercom)};Intercom.prototype.page=function(page){window.Intercom("update")};Intercom.prototype.identify=function(identify){var traits=identify.traits({userId:"user_id"});var activator=this.options.activator;var opts=identify.options(this.name);var companyCreated=identify.companyCreated();var created=identify.created();var email=identify.email();var name=identify.name();var id=identify.userId();var group=this.analytics.group();if(!id&&!traits.email)return;traits.app_id=this.options.appId;if(null!=traits.company&&!is.object(traits.company))delete traits.company;if(traits.company)defaults(traits.company,group.traits());if(name)traits.name=name;if(created){del(traits,"created");del(traits,"createdAt");traits.created_at=created}if(companyCreated){del(traits.company,"created");del(traits.company,"createdAt");traits.company.created_at=companyCreated}traits=convertDates(traits,formatDate);if(opts.increments)traits.increments=opts.increments;if(opts.userHash)traits.user_hash=opts.userHash;if(opts.user_hash)traits.user_hash=opts.user_hash;if("#IntercomDefaultWidget"!=activator){traits.widget={activator:activator}}var method=this._id!==id?"boot":"update";this._id=id;window.Intercom(method,traits)};Intercom.prototype.group=function(group){var props=group.properties();props=alias(props,{createdAt:"created"});props=alias(props,{created:"created_at"});var id=group.groupId();if(id)props.id=id;window.Intercom("update",{company:props})};Intercom.prototype.track=function(track){window.Intercom("trackEvent",track.event(),track.properties())};function formatDate(date){return Math.floor(date/1e3)}},{"analytics.js-integration":88,"convert-dates":179,defaults:173,"obj-case":92,"is-email":170,"load-script":143,"is-empty":122,alias:178,each:4,when:146,is:91}],50:[function(require,module,exports){var integration=require("analytics.js-integration");var clone=require("clone");var Keen=module.exports=integration("Keen IO").global("Keen").option("projectId","").option("readKey","").option("writeKey","").option("ipAddon",false).option("uaAddon",false).option("urlAddon",false).option("referrerAddon",false).option("trackNamedPages",true).option("trackAllPages",false).option("trackCategorizedPages",true).tag('<script src="//d26b395fwzu5fz.cloudfront.net/3.0.7/{{ lib }}.min.js">');Keen.prototype.initialize=function(){var options=this.options;!function(a,b){if(void 0===b[a]){b["_"+a]={},b[a]=function(c){b["_"+a].clients=b["_"+a].clients||{},b["_"+a].clients[c.projectId]=this,this._config=c},b[a].ready=function(c){b["_"+a].ready=b["_"+a].ready||[],b["_"+a].ready.push(c)};for(var c=["addEvent","setGlobalProperties","trackExternalLink","on"],d=0;d<c.length;d++){var e=c[d],f=function(a){return function(){return this["_"+a]=this["_"+a]||[],this["_"+a].push(arguments),this}};b[a].prototype[e]=f(e)}}}("Keen",window);this.client=new window.Keen({projectId:options.projectId,writeKey:options.writeKey,readKey:options.readKey});var lib=this.options.readKey?"keen":"keen-tracker";this.load({lib:lib},this.ready)};Keen.prototype.loaded=function(){return!!(window.Keen&&window.Keen.prototype.configure)};Keen.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Keen.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var user={};if(id)user.userId=id;if(traits)user.traits=traits;var props={user:user};this.addons(props,identify);this.client.setGlobalProperties(function(){return clone(props)})};Keen.prototype.track=function(track){var props=track.properties();this.addons(props,track);this.client.addEvent(track.event(),props)};Keen.prototype.addons=function(obj,msg){var options=this.options;var addons=[];if(options.ipAddon){addons.push({name:"keen:ip_to_geo",input:{ip:"ip_address"},output:"ip_geo_info"});obj.ip_address="${keen.ip}"}if(options.uaAddon){addons.push({name:"keen:ua_parser",input:{ua_string:"user_agent"},output:"parsed_user_agent"});obj.user_agent="${keen.user_agent}"}if(options.urlAddon){addons.push({name:"keen:url_parser",input:{url:"page_url"},output:"parsed_page_url"});obj.page_url=document.location.href}if(options.referrerAddon){addons.push({name:"keen:referrer_parser",input:{referrer_url:"referrer_url",page_url:"page_url"},output:"referrer_info"});obj.referrer_url=document.referrer;obj.page_url=document.location.href}obj.keen={timestamp:msg.timestamp(),addons:addons}}},{"analytics.js-integration":88,clone:95}],51:[function(require,module,exports){var integration=require("analytics.js-integration");var indexof=require("indexof");var is=require("is");var Kenshoo=module.exports=integration("Kenshoo").global("k_trackevent").option("cid","").option("subdomain","").option("events",[]).tag('<script src="//{{ subdomain }}.xg4ken.com/media/getpx.php?cid={{ cid }}">');Kenshoo.prototype.initialize=function(page){this.load(this.ready)};Kenshoo.prototype.loaded=function(){return is.fn(window.k_trackevent)};Kenshoo.prototype.track=function(track){var events=this.options.events;var traits=track.traits();var event=track.event();var revenue=track.revenue()||0;if(!~indexof(events,event))return;var params=["id="+this.options.cid,"type=conv","val="+revenue,"orderId="+track.orderId(),"promoCode="+track.coupon(),"valueCurrency="+track.currency(),"GCID=","kw=","product="];window.k_trackevent(params,this.options.subdomain)}},{"analytics.js-integration":88,indexof:116,is:91}],52:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_kmq");var Track=require("facade").Track;var alias=require("alias");var each=require("each");var is=require("is");var KISSmetrics=module.exports=integration("KISSmetrics").assumesPageview().global("_kmq").global("KM").global("_kmil").option("apiKey","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("prefixProperties",true).tag("library",'<script src="//scripts.kissmetrics.com/{{ apiKey }}.2.js">');exports.isMobile=navigator.userAgent.match(/Android/i)||navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/iPhone|iPod/i)||navigator.userAgent.match(/iPad/i)||navigator.userAgent.match(/Opera Mini/i)||navigator.userAgent.match(/IEMobile/i);KISSmetrics.prototype.initialize=function(page){var self=this;window._kmq=[];if(exports.isMobile)push("set",{"Mobile Session":"Yes"});this.load("library",function(){self.trackPage(page);self.ready()})};KISSmetrics.prototype.loaded=function(){return is.object(window.KM)};KISSmetrics.prototype.page=function(page){if(!window.KM_SKIP_PAGE_VIEW)window.KM.pageView();this.trackPage(page)};KISSmetrics.prototype.trackPage=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};KISSmetrics.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();if(id)push("identify",id);if(traits)push("set",traits)};KISSmetrics.prototype.track=function(track){var mapping={revenue:"Billing Amount"};var event=track.event();var properties=track.properties(mapping);if(this.options.prefixProperties)properties=prefix(event,properties);push("record",event,properties)};KISSmetrics.prototype.alias=function(alias){push("alias",alias.to(),alias.from())};KISSmetrics.prototype.completedOrder=function(track){var products=track.products();var event=track.event();push("record",event,prefix(event,track.properties()));window._kmq.push(function(){var km=window.KM;each(products,function(product,i){var item=prefix(event,product);item._t=km.ts()+i;item._d=1;km.set(item)})})};function prefix(event,properties){var prefixed={};each(properties,function(key,val){if(key==="Billing Amount"){prefixed[key]=val}else{prefixed[event+" - "+key]=val}});return prefixed}},{"analytics.js-integration":88,"global-queue":174,facade:147,alias:178,each:4,is:91}],53:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_learnq");var tick=require("next-tick");var alias=require("alias");var aliases={id:"$id",email:"$email",firstName:"$first_name",lastName:"$last_name",phone:"$phone_number",title:"$title"};var Klaviyo=module.exports=integration("Klaviyo").assumesPageview().global("_learnq").option("apiKey","").tag('<script src="//a.klaviyo.com/media/js/learnmarklet.js">');Klaviyo.prototype.initialize=function(page){var self=this;push("account",this.options.apiKey);this.load(function(){tick(self.ready)})};Klaviyo.prototype.loaded=function(){return!!(window._learnq&&window._learnq.push!==Array.prototype.push)};Klaviyo.prototype.identify=function(identify){var traits=identify.traits(aliases);if(!traits.$id&&!traits.$email)return;push("identify",traits)};Klaviyo.prototype.group=function(group){var props=group.properties();if(!props.name)return;push("identify",{$organization:props.name})};Klaviyo.prototype.track=function(track){push("track",track.event(),track.properties({revenue:"$value"}))}},{"analytics.js-integration":88,"global-queue":174,"next-tick":103,alias:178}],54:[function(require,module,exports){var integration=require("analytics.js-integration");var clone=require("clone");var each=require("each");var Identify=require("facade").Identify;var when=require("when");var LiveChat=module.exports=integration("LiveChat").assumesPageview().global("__lc").global("__lc_inited").global("LC_API").global("LC_Invite").option("group",0).option("license","").tag('<script src="//cdn.livechatinc.com/tracking.js">');LiveChat.prototype.initialize=function(page){var self=this;var user=this.analytics.user();var identify=new Identify({userId:user.id(),traits:user.traits()});window.__lc=clone(this.options);window.__lc.visitor={name:identify.name(),email:identify.email()};this.load(function(){when(function(){return self.loaded()},self.ready)})};LiveChat.prototype.loaded=function(){return!!(window.LC_API&&window.LC_Invite)};LiveChat.prototype.identify=function(identify){var traits=identify.traits({userId:"User ID"});window.LC_API.set_custom_variables(convert(traits))};function convert(traits){var arr=[];each(traits,function(key,value){arr.push({name:key,value:value})});return arr}},{"analytics.js-integration":88,clone:95,each:4,facade:147,when:146}],55:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var useHttps=require("use-https");var LuckyOrange=module.exports=integration("Lucky Orange").assumesPageview().global("_loq").global("__wtw_watcher_added").global("__wtw_lucky_site_id").global("__wtw_lucky_is_segment_io").global("__wtw_custom_user_data").option("siteId",null).tag("http",'<script src="http://www.luckyorange.com/w.js?{{ cache }}">').tag("https",'<script src="https://ssl.luckyorange.com/w.js?{{ cache }}">');LuckyOrange.prototype.initialize=function(page){var user=this.analytics.user();window._loq||(window._loq=[]);window.__wtw_lucky_site_id=this.options.siteId;this.identify(new Identify({traits:user.traits(),userId:user.id()}));var cache=Math.floor((new Date).getTime()/6e4);var name=useHttps()?"https":"http";this.load(name,{cache:cache},this.ready)};LuckyOrange.prototype.loaded=function(){return!!window.__wtw_watcher_added};LuckyOrange.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var name=identify.name();if(name)traits.name=name;if(email)traits.email=email;window.__wtw_custom_user_data=traits}},{"analytics.js-integration":88,facade:147,"use-https":90}],56:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Lytics=module.exports=integration("Lytics").global("jstag").option("cid","").option("cookie","seerid").option("delay",2e3).option("sessionTimeout",1800).option("url","//c.lytics.io").tag('<script src="//c.lytics.io/static/io.min.js">');var aliases={sessionTimeout:"sessecs"};Lytics.prototype.initialize=function(page){var options=alias(this.options,aliases);window.jstag=function(){var t={_q:[],_c:options,ts:(new Date).getTime()};t.send=function(){this._q.push(["ready","send",Array.prototype.slice.call(arguments)]);return this};return t}();this.load(this.ready)};Lytics.prototype.loaded=function(){return!!(window.jstag&&window.jstag.bind)};Lytics.prototype.page=function(page){window.jstag.send(page.properties())};Lytics.prototype.identify=function(identify){var traits=identify.traits({userId:"_uid"});window.jstag.send(traits)};Lytics.prototype.track=function(track){var props=track.properties();props._e=track.event();window.jstag.send(props)}},{"analytics.js-integration":88,alias:178}],57:[function(require,module,exports){var alias=require("alias");var clone=require("clone");var dates=require("convert-dates");var integration=require("analytics.js-integration");var is=require("is");var iso=require("to-iso-string");var indexof=require("indexof");var del=require("obj-case").del;var some=require("some");var Mixpanel=module.exports=integration("Mixpanel").global("mixpanel").option("increments",[]).option("cookieName","").option("crossSubdomainCookie",false).option("secureCookie",false).option("nameTag",true).option("pageview",false).option("people",false).option("token","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//cdn.mxpnl.com/libs/mixpanel-2.2.min.js">');var optionsAliases={cookieName:"cookie_name",crossSubdomainCookie:"cross_subdomain_cookie",secureCookie:"secure_cookie"};Mixpanel.prototype.initialize=function(){(function(c,a){window.mixpanel=a;var b,d,h,e;a._i=[];a.init=function(b,c,f){function d(a,b){var c=b.split(".");2==c.length&&(a=a[c[0]],b=c[1]);a[b]=function(){a.push([b].concat(Array.prototype.slice.call(arguments,0)))}}var g=a;"undefined"!==typeof f?g=a[f]=[]:f="mixpanel";g.people=g.people||[];h=["disable","track","track_pageview","track_links","track_forms","register","register_once","unregister","identify","alias","name_tag","set_config","people.set","people.increment","people.track_charge","people.append"];for(e=0;e<h.length;e++)d(g,h[e]);a._i.push([b,c,f])};a.__SV=1.2})(document,window.mixpanel||[]);this.options.increments=lowercase(this.options.increments);var options=alias(this.options,optionsAliases);window.mixpanel.init(options.token,options);this.load(this.ready)};Mixpanel.prototype.loaded=function(){return!!(window.mixpanel&&window.mixpanel.config)};Mixpanel.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};var traitAliases={created:"$created",email:"$email",firstName:"$first_name",lastName:"$last_name",lastSeen:"$last_seen",name:"$name",username:"$username",phone:"$phone"};Mixpanel.prototype.identify=function(identify){var username=identify.username();var email=identify.email();var id=identify.userId();if(id)window.mixpanel.identify(id);var nametag=email||username||id;if(nametag)window.mixpanel.name_tag(nametag);var traits=identify.traits(traitAliases);if(traits.$created)del(traits,"createdAt");window.mixpanel.register(dates(traits,iso));if(this.options.people)window.mixpanel.people.set(traits)};Mixpanel.prototype.track=function(track){var increments=this.options.increments;var increment=track.event().toLowerCase();var people=this.options.people;var props=track.properties();var revenue=track.revenue();delete props.distinct_id;delete props.ip;delete props.mp_name_tag;delete props.mp_note;delete props.token;for(var key in props){var val=props[key];if(is.array(val)&&some(val,is.object))props[key]=val.length}if(people&&~indexof(increments,increment)){window.mixpanel.people.increment(track.event());window.mixpanel.people.set("Last "+track.event(),new Date)}props=dates(props,iso);window.mixpanel.track(track.event(),props);if(revenue&&people){window.mixpanel.people.track_charge(revenue)}};Mixpanel.prototype.alias=function(alias){var mp=window.mixpanel;var to=alias.to();if(mp.get_distinct_id&&mp.get_distinct_id()===to)return;if(mp.get_property&&mp.get_property("$people_distinct_id")===to)return;mp.alias(to,alias.from())};function lowercase(arr){var ret=new Array(arr.length);for(var i=0;i<arr.length;++i){ret[i]=String(arr[i]).toLowerCase()}return ret}},{alias:178,clone:95,"convert-dates":179,"analytics.js-integration":88,is:91,"to-iso-string":177,indexof:116,"obj-case":92,some:190}],190:[function(require,module,exports){var some=[].some;module.exports=function(arr,fn){if(some)return some.call(arr,fn);for(var i=0,l=arr.length;i<l;++i){if(fn(arr[i],i))return true}return false}},{}],58:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var is=require("is");var Mojn=module.exports=integration("Mojn").option("customerCode","").global("_mojnTrack").tag('<script src="https://track.idtargeting.com/{{ customerCode }}/track.js">');Mojn.prototype.initialize=function(){window._mojnTrack=window._mojnTrack||[];window._mojnTrack.push({cid:this.options.customerCode});var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Mojn.prototype.loaded=function(){return is.object(window._mojnTrack)};Mojn.prototype.identify=function(identify){var email=identify.email();if(!email)return;var img=new Image;img.src="//matcher.idtargeting.com/identify.gif?cid="+this.options.customerCode+"&_mjnctid="+email;img.width=1;img.height=1;return img};Mojn.prototype.track=function(track){var properties=track.properties();var revenue=properties.revenue;var currency=properties.currency||"";
var conv=currency+revenue;if(!revenue)return;window._mojnTrack.push({conv:conv});return conv}},{"analytics.js-integration":88,bind:101,when:146,is:91}],59:[function(require,module,exports){var push=require("global-queue")("_mfq");var integration=require("analytics.js-integration");var each=require("each");var Mouseflow=module.exports=integration("Mouseflow").assumesPageview().global("mouseflow").global("_mfq").option("apiKey","").option("mouseflowHtmlDelay",0).tag('<script src="//cdn.mouseflow.com/projects/{{ apiKey }}.js">');Mouseflow.prototype.initialize=function(page){window.mouseflowHtmlDelay=this.options.mouseflowHtmlDelay;this.load(this.ready)};Mouseflow.prototype.loaded=function(){return!!window.mouseflow};Mouseflow.prototype.page=function(page){if(!window.mouseflow)return;if("function"!=typeof mouseflow.newPageView)return;mouseflow.newPageView()};Mouseflow.prototype.identify=function(identify){set(identify.traits())};Mouseflow.prototype.track=function(track){var props=track.properties();props.event=track.event();set(props)};function set(obj){each(obj,function(key,value){push("setVariable",key,value)})}},{"global-queue":174,"analytics.js-integration":88,each:4}],60:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var each=require("each");var is=require("is");var MouseStats=module.exports=integration("MouseStats").assumesPageview().global("msaa").global("MouseStatsVisitorPlaybacks").option("accountNumber","").tag("http",'<script src="http://www2.mousestats.com/js/{{ path }}.js?{{ cache }}">').tag("https",'<script src="https://ssl.mousestats.com/js/{{ path }}.js?{{ cache }}">');MouseStats.prototype.initialize=function(page){var number=this.options.accountNumber;var path=number.slice(0,1)+"/"+number.slice(1,2)+"/"+number;var cache=Math.floor((new Date).getTime()/6e4);var name=useHttps()?"https":"http";this.load(name,{path:path,cache:cache},this.ready)};MouseStats.prototype.loaded=function(){return is.array(window.MouseStatsVisitorPlaybacks)};MouseStats.prototype.identify=function(identify){each(identify.traits(),function(key,value){window.MouseStatsVisitorPlaybacks.customVariable(key,value)})}},{"analytics.js-integration":88,"use-https":90,each:4,is:91}],61:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("__nls");var Navilytics=module.exports=integration("Navilytics").assumesPageview().global("__nls").option("memberId","").option("projectId","").tag('<script src="//www.navilytics.com/nls.js?mid={{ memberId }}&pid={{ projectId }}">');Navilytics.prototype.initialize=function(page){window.__nls=window.__nls||[];this.load(this.ready)};Navilytics.prototype.loaded=function(){return!!(window.__nls&&[].push!=window.__nls.push)};Navilytics.prototype.track=function(track){push("tagRecording",track.event())}},{"analytics.js-integration":88,"global-queue":174}],62:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Identify=require("facade").Identify;var Nudgespot=module.exports=integration("Nudgespot").assumesPageview().option("apiKey","").global("nudgespot").tag('<script id="nudgespot" src="//cdn.nudgespot.com/nudgespot.js">');Nudgespot.prototype.initialize=function(page){window.nudgespot=window.nudgespot||[];window.nudgespot.init=function(n,t){function f(n,m){var a=m.split(".");2==a.length&&(n=n[a[0]],m=a[1]);n[m]=function(){n.push([m].concat(Array.prototype.slice.call(arguments,0)))}}n._version=.1;n._globals=[t];n.people=n.people||[];n.params=n.params||[];m="track register unregister identify set_config people.delete people.create people.update people.create_property people.tag people.remove_Tag".split(" ");for(var i=0;i<m.length;i++)f(n,m[i])};window.nudgespot.init(window.nudgespot,this.options.apiKey);this.load(this.ready)};Nudgespot.prototype.loaded=function(){return!!window.nudgespot&&window.nudgespot.push!==Array.prototype.push};Nudgespot.prototype.identify=function(identify){if(!identify.userId())return this.debug("user id required");var traits=identify.traits({createdAt:"created"});traits=alias(traits,{created:"created_at"});window.nudgespot.identify(identify.userId(),traits)};Nudgespot.prototype.track=function(track){var properties=track.properties();window.nudgespot.track(track.event(),properties)}},{"analytics.js-integration":88,alias:178,facade:147}],63:[function(require,module,exports){var integration=require("analytics.js-integration");var https=require("use-https");var tick=require("next-tick");var Olark=module.exports=integration("Olark").assumesPageview().global("olark").option("identify",true).option("page",true).option("siteId","").option("groupId","").option("track",false);Olark.prototype.initialize=function(page){var self=this;this.load(function(){tick(self.ready)});var groupId=this.options.groupId;if(groupId)api("chat.setOperatorGroup",{group:groupId});api("box.onExpand",function(){self._open=true});api("box.onShrink",function(){self._open=false})};Olark.prototype.loaded=function(){return!!window.olark};Olark.prototype.load=function(callback){var el=document.getElementById("olark");window.olark||function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i," onl"+'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()}({loader:"static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});window.olark.identify(this.options.siteId);callback()};Olark.prototype.page=function(page){if(!this.options.page)return;var props=page.properties();var name=page.fullName();if(!name&&!props.url)return;name=name?name+" page":props.url;this.notify("looking at "+name)};Olark.prototype.identify=function(identify){if(!this.options.identify)return;var username=identify.username();var traits=identify.traits();var id=identify.userId();var email=identify.email();var phone=identify.phone();var name=identify.name()||identify.firstName();if(traits)api("visitor.updateCustomFields",traits);if(email)api("visitor.updateEmailAddress",{emailAddress:email});if(phone)api("visitor.updatePhoneNumber",{phoneNumber:phone});if(name)api("visitor.updateFullName",{fullName:name});var nickname=name||email||username||id;if(name&&email)nickname+=" ("+email+")";if(nickname)api("chat.updateVisitorNickname",{snippet:nickname})};Olark.prototype.track=function(track){if(!this.options.track)return;this.notify('visitor triggered "'+track.event()+'"')};Olark.prototype.notify=function(message){if(!this._open)return;message=message.toLowerCase();api("visitor.getDetails",function(data){if(!data||!data.isConversing)return;api("chat.sendNotificationToOperator",{body:message})})};function api(action,value){window.olark("api."+action,value)}},{"analytics.js-integration":88,"use-https":90,"next-tick":103}],64:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("optimizely");var callback=require("callback");var tick=require("next-tick");var bind=require("bind");var each=require("each");var Optimizely=module.exports=integration("Optimizely").option("variations",true).option("trackNamedPages",true).option("trackCategorizedPages",true);Optimizely.prototype.initialize=function(){if(this.options.variations){var self=this;tick(function(){self.replay()})}this.ready()};Optimizely.prototype.track=function(track){var props=track.properties();if(props.revenue)props.revenue*=100;push("trackEvent",track.event(),props)};Optimizely.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Optimizely.prototype.replay=function(){if(!window.optimizely)return;var data=window.optimizely.data;if(!data)return;var experiments=data.experiments;var map=data.state.variationNamesMap;var traits={};each(map,function(experimentId,variation){var experiment=experiments[experimentId].name;traits["Experiment: "+experiment]=variation});this.analytics.identify(traits)}},{"analytics.js-integration":88,"global-queue":174,callback:94,"next-tick":103,bind:101,each:4}],65:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_pq");var PerfectAudience=module.exports=integration("Perfect Audience").assumesPageview().global("_pq").option("siteId","").tag('<script src="//tag.perfectaudience.com/serve/{{ siteId }}.js">');PerfectAudience.prototype.initialize=function(page){window._pq=window._pq||[];this.load(this.ready)};PerfectAudience.prototype.loaded=function(){return!!(window._pq&&window._pq.push)};PerfectAudience.prototype.track=function(track){var total=track.total()||track.revenue();var orderId=track.orderId();var props={};var sendProps=false;if(total){props.revenue=total;sendProps=true}if(orderId){props.orderId=orderId;sendProps=true}if(!sendProps)return push("track",track.event());return push("track",track.event(),props)};PerfectAudience.prototype.viewedProduct=function(track){var product=track.sku();push("track",track.event());push("trackProduct",product)};PerfectAudience.prototype.completedOrder=function(track){var total=track.total()||track.revenue();var orderId=track.orderId();var props={};if(total)props.revenue=total;if(orderId)props.orderId=orderId;push("track",track.event(),props)}},{"analytics.js-integration":88,"global-queue":174}],66:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_prum");var date=require("load-date");var Pingdom=module.exports=integration("Pingdom").assumesPageview().global("_prum").global("PRUM_EPISODES").option("id","").tag('<script src="//rum-static.pingdom.net/prum.min.js">');Pingdom.prototype.initialize=function(page){window._prum=window._prum||[];push("id",this.options.id);push("mark","firstbyte",date.getTime());var self=this;this.load(this.ready)};Pingdom.prototype.loaded=function(){return!!(window._prum&&window._prum.push!==Array.prototype.push)}},{"analytics.js-integration":88,"global-queue":174,"load-date":175}],67:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_paq");var each=require("each");var is=require("is");var Piwik=module.exports=integration("Piwik").global("_paq").option("url",null).option("siteId","").option("customVariableLimit",5).mapping("goals").tag('<script src="{{ url }}/piwik.js">');Piwik.prototype.initialize=function(){window._paq=window._paq||[];push("setSiteId",this.options.siteId);push("setTrackerUrl",this.options.url+"/piwik.php");push("enableLinkTracking");this.load(this.ready)};Piwik.prototype.loaded=function(){return!!(window._paq&&window._paq.push!=[].push)};Piwik.prototype.page=function(page){push("trackPageView")};Piwik.prototype.track=function(track){var goals=this.goals(track.event());var revenue=track.revenue();var category=track.category()||"All";var action=track.event();var name=track.proxy("properties.name")||track.proxy("properties.label");var value=track.value()||track.revenue();var options=track.options("Piwik");var customVariables=options.customVars||options.cvar;if(!is.object(customVariables)){customVariables={}}for(var i=1;i<=this.options.customVariableLimit;i+=1){if(customVariables[i]){push("setCustomVariable",i.toString(),customVariables[i][0],customVariables[i][1],"page")}}each(goals,function(goal){push("trackGoal",goal,revenue)});push("trackEvent",category,action,name,value)}},{"analytics.js-integration":88,"global-queue":174,each:4,is:91}],68:[function(require,module,exports){var integration=require("analytics.js-integration");var convertDates=require("convert-dates");var push=require("global-queue")("_preactq");var alias=require("alias");var Preact=module.exports=integration("Preact").assumesPageview().global("_preactq").global("_lnq").option("projectCode","").tag('<script src="//d2bbvl6dq48fa6.cloudfront.net/js/preact-4.1.min.js">');Preact.prototype.initialize=function(page){window._preactq=window._preactq||[];window._lnq=window._lnq||[];push("_setCode",this.options.projectCode);this.load(this.ready)};Preact.prototype.loaded=function(){return!!(window._preactq&&window._preactq.push!==Array.prototype.push)};Preact.prototype.identify=function(identify){if(!identify.userId())return;var traits=identify.traits({created:"created_at"});traits=convertDates(traits,convertDate);push("_setPersonData",{name:identify.name(),email:identify.email(),uid:identify.userId(),properties:traits})};Preact.prototype.group=function(group){if(!group.groupId())return;push("_setAccount",group.traits())};Preact.prototype.track=function(track){var props=track.properties();var revenue=track.revenue();var event=track.event();var special={name:event};if(revenue){special.revenue=revenue*100;delete props.revenue}if(props.note){special.note=props.note;delete props.note}push("_logEvent",special,props)};function convertDate(date){return Math.floor(date/1e3)}},{"analytics.js-integration":88,"convert-dates":179,"global-queue":174,alias:178}],69:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_kiq");var Facade=require("facade");var Identify=Facade.Identify;var bind=require("bind");var when=require("when");var Qualaroo=module.exports=integration("Qualaroo").assumesPageview().global("_kiq").option("customerId","").option("siteToken","").option("track",false).tag('<script src="//s3.amazonaws.com/ki.js/{{ customerId }}/{{ siteToken }}.js">');Qualaroo.prototype.initialize=function(page){window._kiq=window._kiq||[];var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Qualaroo.prototype.loaded=function(){return!!(window._kiq&&window._kiq.push!==Array.prototype.push)};Qualaroo.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var email=identify.email();if(email)id=email;if(id)push("identify",id);if(traits)push("set",traits)};Qualaroo.prototype.track=function(track){if(!this.options.track)return;var event=track.event();var traits={};traits["Triggered: "+event]=true;this.identify(new Identify({traits:traits}))}},{"analytics.js-integration":88,"global-queue":174,facade:147,bind:101,when:146}],70:[function(require,module,exports){var push=require("global-queue")("_qevents",{wrap:false});var integration=require("analytics.js-integration");var useHttps=require("use-https");var is=require("is");var reduce=require("reduce");var Quantcast=module.exports=integration("Quantcast").assumesPageview().global("_qevents").global("__qc").option("pCode",null).option("advertise",false).tag("http",'<script src="http://edge.quantserve.com/quant.js">').tag("https",'<script src="https://secure.quantserve.com/quant.js">');Quantcast.prototype.initialize=function(page){window._qevents=window._qevents||[];var opts=this.options;var settings={qacct:opts.pCode};var user=this.analytics.user();if(user.id())settings.uid=user.id();if(page){settings.labels=this._labels("page",page.category(),page.name())}push(settings);var name=useHttps()?"https":"http";this.load(name,this.ready)};Quantcast.prototype.loaded=function(){return!!window.__qc};Quantcast.prototype.page=function(page){var category=page.category();var name=page.name();var customLabels=page.proxy("properties.label");var labels=this._labels("page",category,name,customLabels);var settings={event:"refresh",labels:labels,qacct:this.options.pCode};var user=this.analytics.user();if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.identify=function(identify){var id=identify.userId();if(id){window._qevents[0]=window._qevents[0]||{};window._qevents[0].uid=id}};Quantcast.prototype.track=function(track){var name=track.event();var revenue=track.revenue();var orderId=track.orderId();var customLabels=track.proxy("properties.label");var labels=this._labels("event",name,customLabels);var settings={event:"click",labels:labels,qacct:this.options.pCode};var user=this.analytics.user();if(null!=revenue)settings.revenue=revenue+"";if(orderId)settings.orderid=orderId;if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.completedOrder=function(track){var name=track.event();var revenue=track.total();var customLabels=track.proxy("properties.label");var labels=this._labels("event",name,customLabels);var category=track.category();if(this.options.advertise&&category){labels+=","+this._labels("pcat",category)}var settings={event:"refresh",labels:labels,revenue:revenue+"",orderid:track.orderId(),qacct:this.options.pCode};push(settings)};Quantcast.prototype._labels=function(type){var args=Array.prototype.slice.call(arguments,1);var advertise=this.options.advertise;if(advertise&&"page"==type)type="event";if(advertise)type="_fp."+type;var separator=advertise?" ":".";var ret=reduce(args,function(ret,arg){if(arg!=null){ret.push(String(arg).replace(/, /g,","))}return ret},[]).join(separator);return[type,ret].join(".")}},{"global-queue":174,"analytics.js-integration":88,"use-https":90,is:91,reduce:191}],191:[function(require,module,exports){module.exports=function(arr,fn,initial){var idx=0;var len=arr.length;var curr=arguments.length==3?initial:arr[idx++];while(idx<len){curr=fn.call(null,curr,arr[idx],++idx,arr)}return curr}},{}],71:[function(require,module,exports){var integration=require("analytics.js-integration");var extend=require("extend");var is=require("is");var RollbarIntegration=module.exports=integration("Rollbar").global("Rollbar").option("identify",true).option("accessToken","").option("environment","unknown").option("captureUncaught",true);RollbarIntegration.prototype.initialize=function(page){var _rollbarConfig=this.config={accessToken:this.options.accessToken,captureUncaught:this.options.captureUncaught,payload:{environment:this.options.environment}};(function(a,b){function c(b){this.shimId=++h,this.notifier=null,this.parentShim=b,this.logger=function(){},a.console&&void 0===a.console.shimId&&(this.logger=a.console.log)}function d(b,c,d){a._rollbarWrappedError&&(d[4]||(d[4]=a._rollbarWrappedError),d[5]||(d[5]=a._rollbarWrappedError._rollbarContext),a._rollbarWrappedError=null),b.uncaughtError.apply(b,d),c&&c.apply(a,d)}function e(b){var d=c;return g(function(){if(this.notifier)return this.notifier[b].apply(this.notifier,arguments);var c=this,e="scope"===b;e&&(c=new d(this));var f=Array.prototype.slice.call(arguments,0),g={shim:c,method:b,args:f,ts:new Date};return a._rollbarShimQueue.push(g),e?c:void 0})}function f(a,b){if(b.hasOwnProperty&&b.hasOwnProperty("addEventListener")){var c=b.addEventListener;b.addEventListener=function(b,d,e){c.call(this,b,a.wrap(d),e)};var d=b.removeEventListener;b.removeEventListener=function(a,b,c){d.call(this,a,b&&b._wrapped?b._wrapped:b,c)}}}function g(a,b){return b=b||this.logger,function(){try{return a.apply(this,arguments)}catch(c){b("Rollbar internal error:",c)}}}var h=0;c.init=function(a,b){var e=b.globalAlias||"Rollbar";if("object"==typeof a[e])return a[e];a._rollbarShimQueue=[],a._rollbarWrappedError=null,b=b||{};var h=new c;return g(function(){if(h.configure(b),b.captureUncaught){var c=a.onerror;a.onerror=function(){var a=Array.prototype.slice.call(arguments,0);d(h,c,a)};var g,i,j="EventTarget,Window,Node,ApplicationCache,AudioTrackList,ChannelMergerNode,CryptoOperation,EventSource,FileReader,HTMLUnknownElement,IDBDatabase,IDBRequest,IDBTransaction,KeyOperation,MediaController,MessagePort,ModalWindow,Notification,SVGElementInstance,Screen,TextTrack,TextTrackCue,TextTrackList,WebSocket,WebSocketWorker,Worker,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload".split(",");for(g=0;g<j.length;++g)i=j[g],a[i]&&a[i].prototype&&f(h,a[i].prototype)}return a[e]=h,h},h.logger)()},c.prototype.loadFull=function(a,b,c,d,e){var f=g(function(){var a=b.createElement("script"),e=b.getElementsByTagName("script")[0];a.src=d.rollbarJsUrl,a.async=!c,a.onload=h,e.parentNode.insertBefore(a,e)},this.logger),h=g(function(){var b;if(void 0===a._rollbarPayloadQueue){var c,d,f,g;for(b=new Error("rollbar.js did not load");c=a._rollbarShimQueue.shift();)for(f=c.args,g=0;g<f.length;++g)if(d=f[g],"function"==typeof d){d(b);break}}"function"==typeof e&&e(b)},this.logger);g(function(){c?f():a.addEventListener?a.addEventListener("load",f,!1):a.attachEvent("onload",f)},this.logger)()},c.prototype.wrap=function(b,c){try{var d;if(d="function"==typeof c?c:function(){return c||{}},"function"!=typeof b)return b;if(b._isWrap)return b;if(!b._wrapped){b._wrapped=function(){try{return b.apply(this,arguments)}catch(c){throw c._rollbarContext=d(),c._rollbarContext._wrappedSource=b.toString(),a._rollbarWrappedError=c,c}},b._wrapped._isWrap=!0;for(var e in b)b.hasOwnProperty(e)&&(b._wrapped[e]=b[e])}return b._wrapped}catch(f){return b}};for(var i="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),j=0;j<i.length;++j)c.prototype[i[j]]=e(i[j]);var k="//d37gvrvc0wt4s1.cloudfront.net/js/v1.1/rollbar.min.js";_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||k;var l=c.init(a,_rollbarConfig)})(window,document);this.load(this.ready)};RollbarIntegration.prototype.loaded=function(){return is.object(window.Rollbar)&&null==window.Rollbar.shimId};RollbarIntegration.prototype.load=function(callback){window.Rollbar.loadFull(window,document,true,this.config,callback)};RollbarIntegration.prototype.identify=function(identify){if(!this.options.identify)return;var uid=identify.userId();if(uid===null||uid===undefined)return;var rollbar=window.Rollbar;var person={id:uid};extend(person,identify.traits());rollbar.configure({payload:{person:person}})}},{"analytics.js-integration":88,extend:145,is:91}],72:[function(require,module,exports){var integration=require("analytics.js-integration");var SaaSquatch=module.exports=integration("SaaSquatch").option("tenantAlias","").option("referralImage","").global("_sqh").tag('<script src="//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js">');SaaSquatch.prototype.initialize=function(page){window._sqh=window._sqh||[];this.load(this.ready)};SaaSquatch.prototype.loaded=function(){return window._sqh&&window._sqh.push!=[].push};SaaSquatch.prototype.identify=function(identify){var sqh=window._sqh;var accountId=identify.proxy("traits.accountId");var image=identify.proxy("traits.referralImage")||this.options.referralImage;var opts=identify.options(this.name);var id=identify.userId();var email=identify.email();if(!(id||email))return;if(this.called)return;var init={tenant_alias:this.options.tenantAlias,first_name:identify.firstName(),last_name:identify.lastName(),user_image:identify.avatar(),email:email,user_id:id};if(accountId)init.account_id=accountId;if(opts.checksum)init.checksum=opts.checksum;if(image)init.fb_share_image=image;sqh.push(["init",init]);this.called=true;this.load()};SaaSquatch.prototype.group=function(group){var sqh=window._sqh;var props=group.properties();var id=group.groupId();var image=group.proxy("traits.referralImage")||this.options.referralImage;var opts=group.options(this.name);if(this.called)return;var init={tenant_alias:this.options.tenantAlias,account_id:id};if(opts.checksum)init.checksum=opts.checksum;if(image)init.fb_share_image=image;sqh.push(["init",init]);this.called=true;this.load()}},{"analytics.js-integration":88}],73:[function(require,module,exports){var integration=require("analytics.js-integration");var when=require("when");var SatisMeter=module.exports=integration("SatisMeter").global("satismeter").option("token","").tag('<script src="https://app.satismeter.com/satismeter.js">');SatisMeter.prototype.initialize=function(page){var self=this;this.load(function(){when(function(){return self.loaded()},self.ready)})};SatisMeter.prototype.loaded=function(){return!!window.satismeter};SatisMeter.prototype.identify=function(identify){var traits=identify.traits();traits.token=this.options.token;traits.user={id:identify.userId()};if(identify.name()){traits.user.name=identify.name()}if(identify.email()){traits.user.email=identify.email()}if(identify.created()){traits.user.signUpDate=identify.created().toISOString()}delete traits.id;delete traits.email;delete traits.name;delete traits.created;window.satismeter(traits)}},{"analytics.js-integration":88,when:146}],74:[function(require,module,exports){var integration=require("analytics.js-integration");var localstorage=require("store");var protocol=require("protocol");var utm=require("utm-params");var ads=require("ad-params");var send=require("send-json");var cookie=require("cookie");var clone=require("clone");var uuid=require("uuid");var top=require("top-domain");var extend=require("extend");var json=require("segmentio/[email protected]");var options={maxage:31536e6,secure:false,path:"/"};var Segment=exports=module.exports=integration("Segment.io").option("apiKey","");exports.storage=function(){return"file:"==protocol()||"chrome-extension:"==protocol()?localstorage:cookie};exports.global=window;Segment.prototype.initialize=function(page){var self=this;this.ready();this.analytics.on("invoke",function(msg){var action=msg.action();var listener="on"+msg.action();self.debug("%s %o",action,msg);if(self[listener])self[listener](msg);self.ready()})};Segment.prototype.loaded=function(){return true};Segment.prototype.onpage=function(page){this.send("/p",page.json())};Segment.prototype.onidentify=function(identify){this.send("/i",identify.json())};Segment.prototype.ongroup=function(group){this.send("/g",group.json())};Segment.prototype.ontrack=function(track){var json=track.json();delete json.traits;this.send("/t",json)};Segment.prototype.onalias=function(alias){var json=alias.json();var user=this.analytics.user();json.previousId=json.previousId||json.from||user.id()||user.anonymousId();json.userId=json.userId||json.to;delete json.from;delete json.to;this.send("/a",json)};Segment.prototype.normalize=function(msg){this.debug("normalize %o",msg);var user=this.analytics.user();var global=exports.global;var query=global.location.search;var ctx=msg.context=msg.context||msg.options||{};delete msg.options;msg.writeKey=this.options.apiKey;ctx.userAgent=navigator.userAgent;if(!ctx.library)ctx.library={name:"analytics.js",version:this.analytics.VERSION};if(query)ctx.campaign=utm(query);this.referrerId(query,ctx);msg.userId=msg.userId||user.id();msg.anonymousId=user.anonymousId();msg.messageId=uuid();msg.sentAt=new Date;this.debug("normalized %o",msg);return msg};Segment.prototype.send=function(path,msg,fn){var url=scheme()+"//api.segment.io/v1"+path;var headers={"Content-Type":"text/plain"};var fn=fn||noop;var self=this;msg=this.normalize(msg);send(url,msg,headers,function(err,res){self.debug("sent %O, received %O",msg,arguments);if(err)return fn(err);res.url=url;fn(null,res)})};Segment.prototype.cookie=function(name,val){var store=Segment.storage();if(arguments.length===1)return store(name);var global=exports.global;var href=global.location.href;var domain="."+top(href);if("."==domain)domain="";this.debug("store domain %s -> %s",href,domain);var opts=clone(options);opts.domain=domain;this.debug("store %s, %s, %o",name,val,opts);store(name,val,opts);if(store(name))return;delete opts.domain;this.debug("fallback store %s, %s, %o",name,val,opts);store(name,val,opts)};Segment.prototype.referrerId=function(query,ctx){var stored=this.cookie("s:context.referrer");var ad;if(stored)stored=json.parse(stored);if(query)ad=ads(query);ad=ad||stored;if(!ad)return;ctx.referrer=extend(ctx.referrer||{},ad);this.cookie("s:context.referrer",json.stringify(ad))};function scheme(){return"http:"==protocol()?"http:":"https:"}function noop(){}},{"analytics.js-integration":88,store:192,protocol:193,"utm-params":138,"ad-params":194,"send-json":195,cookie:196,clone:95,uuid:197,"top-domain":139,extend:145,"segmentio/[email protected]":180}],192:[function(require,module,exports){var unserialize=require("unserialize");var each=require("each");var storage;try{storage=window.localStorage}catch(e){storage=null}module.exports=store;function store(key,value){var length=arguments.length;if(0==length)return all();if(2<=length)return set(key,value);if(1!=length)return;if(null==key)return storage.clear();if("string"==typeof key)return get(key);if("object"==typeof key)return each(key,set)}store.supported=!!storage;function set(key,val){return null==val?storage.removeItem(key):storage.setItem(key,JSON.stringify(val))}function get(key){return unserialize(storage.getItem(key))}function all(){var len=storage.length;var ret={};var key;while(0<=--len){key=storage.key(len);ret[key]=get(key)}return ret}},{unserialize:198,each:112}],198:[function(require,module,exports){module.exports=function(val){try{return JSON.parse(val)}catch(e){return val||undefined}}},{}],193:[function(require,module,exports){var define=Object.defineProperty;var initialProtocol=window.location.protocol;var mockedProtocol;module.exports=function(protocol){if(arguments.length===0)return get();else return set(protocol)};module.exports.http=function(){set("http:")};module.exports.https=function(){set("https:")};module.exports.reset=function(){set(initialProtocol)};function get(){return mockedProtocol||window.location.protocol}function set(protocol){try{define(window.location,"protocol",{get:function(){return protocol}})}catch(err){mockedProtocol=protocol}}},{}],194:[function(require,module,exports){var parse=require("querystring").parse;module.exports=ads;var QUERYIDS={btid:"dataxu",urid:"millennial-media"};function ads(query){var params=parse(query);for(var key in params){for(var id in QUERYIDS){if(key===id){return{id:params[key],type:QUERYIDS[id]}}}}}},{querystring:140}],195:[function(require,module,exports){var encode=require("base64-encode");var cors=require("has-cors");var jsonp=require("jsonp");var JSON=require("json");exports=module.exports=cors?json:base64;exports.callback="callback";exports.prefix="data";exports.json=json;exports.base64=base64;exports.type=cors?"xhr":"jsonp";function json(url,obj,headers,fn){if(3==arguments.length)fn=headers,headers={};var req=new XMLHttpRequest;req.onerror=fn;req.onreadystatechange=done;req.open("POST",url,true);for(var k in headers)req.setRequestHeader(k,headers[k]);req.send(JSON.stringify(obj));function done(){if(4==req.readyState)return fn(null,req)}}function base64(url,obj,_,fn){if(3==arguments.length)fn=_;var prefix=exports.prefix;obj=encode(JSON.stringify(obj));obj=encodeURIComponent(obj);url+="?"+prefix+"="+obj;jsonp(url,{param:exports.callback},function(err,obj){if(err)return fn(err);fn(null,{url:url,body:obj})})}},{"base64-encode":199,"has-cors":200,jsonp:201,json:180}],199:[function(require,module,exports){var utf8Encode=require("utf8-encode");var keyStr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
module.exports=encode;function encode(input){var output="";var chr1,chr2,chr3,enc1,enc2,enc3,enc4;var i=0;input=utf8Encode(input);while(i<input.length){chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=(chr1&3)<<4|chr2>>4;enc3=(chr2&15)<<2|chr3>>6;enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64}else if(isNaN(chr3)){enc4=64}output=output+keyStr.charAt(enc1)+keyStr.charAt(enc2)+keyStr.charAt(enc3)+keyStr.charAt(enc4)}return output}},{"utf8-encode":202}],202:[function(require,module,exports){module.exports=encode;function encode(string){string=string.replace(/\r\n/g,"\n");var utftext="";for(var n=0;n<string.length;n++){var c=string.charCodeAt(n);if(c<128){utftext+=String.fromCharCode(c)}else if(c>127&&c<2048){utftext+=String.fromCharCode(c>>6|192);utftext+=String.fromCharCode(c&63|128)}else{utftext+=String.fromCharCode(c>>12|224);utftext+=String.fromCharCode(c>>6&63|128);utftext+=String.fromCharCode(c&63|128)}}return utftext}},{}],200:[function(require,module,exports){try{module.exports=typeof XMLHttpRequest!=="undefined"&&"withCredentials"in new XMLHttpRequest}catch(err){module.exports=false}},{}],201:[function(require,module,exports){var debug=require("debug")("jsonp");module.exports=jsonp;var count=0;function noop(){}function jsonp(url,opts,fn){if("function"==typeof opts){fn=opts;opts={}}if(!opts)opts={};var prefix=opts.prefix||"__jp";var param=opts.param||"callback";var timeout=null!=opts.timeout?opts.timeout:6e4;var enc=encodeURIComponent;var target=document.getElementsByTagName("script")[0]||document.head;var script;var timer;var id=prefix+count++;if(timeout){timer=setTimeout(function(){cleanup();if(fn)fn(new Error("Timeout"))},timeout)}function cleanup(){script.parentNode.removeChild(script);window[id]=noop}window[id]=function(data){debug("jsonp got",data);if(timer)clearTimeout(timer);cleanup();if(fn)fn(null,data)};url+=(~url.indexOf("?")?"&":"?")+param+"="+enc(id);url=url.replace("?&","?");debug('jsonp req "%s"',url);script=document.createElement("script");script.src=url;target.parentNode.insertBefore(script,target)}},{debug:203}],203:[function(require,module,exports){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}},{"./lib/debug":204,"./debug":205}],204:[function(require,module,exports){var tty=require("tty");module.exports=debug;var names=[],skips=[];(process.env.DEBUG||"").split(/[\s,]+/).forEach(function(name){name=name.replace("*",".*?");if(name[0]==="-"){skips.push(new RegExp("^"+name.substr(1)+"$"))}else{names.push(new RegExp("^"+name+"$"))}});var colors=[6,2,3,4,5,1];var prev={};var prevColor=0;var isatty=tty.isatty(2);function color(){return colors[prevColor++%colors.length]}function humanize(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"}function debug(name){function disabled(){}disabled.enabled=false;var match=skips.some(function(re){return re.test(name)});if(match)return disabled;match=names.some(function(re){return re.test(name)});if(!match)return disabled;var c=color();function colored(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(prev[name]||curr);prev[name]=curr;fmt=" [9"+c+"m"+name+" "+"[3"+c+"m[90m"+fmt+"[3"+c+"m"+" +"+humanize(ms)+"[0m";console.error.apply(this,arguments)}function plain(fmt){fmt=coerce(fmt);fmt=(new Date).toUTCString()+" "+name+" "+fmt;console.error.apply(this,arguments)}colored.enabled=plain.enabled=true;return isatty||process.env.DEBUG_COLORS?colored:plain}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{}],205:[function(require,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],196:[function(require,module,exports){var debug=require("debug")("cookie");module.exports=function(name,value,options){switch(arguments.length){case 3:case 2:return set(name,value,options);case 1:return get(name);default:return all()}};function set(name,value,options){options=options||{};var str=encode(name)+"="+encode(value);if(null==value)options.maxage=-1;if(options.maxage){options.expires=new Date(+new Date+options.maxage)}if(options.path)str+="; path="+options.path;if(options.domain)str+="; domain="+options.domain;if(options.expires)str+="; expires="+options.expires.toUTCString();if(options.secure)str+="; secure";document.cookie=str}function all(){return parse(document.cookie)}function get(name){return all()[name]}function parse(str){var obj={};var pairs=str.split(/ *; */);var pair;if(""==pairs[0])return obj;for(var i=0;i<pairs.length;++i){pair=pairs[i].split("=");obj[decode(pair[0])]=decode(pair[1])}return obj}function encode(value){try{return encodeURIComponent(value)}catch(e){debug("error `encode(%o)` - %o",value,e)}}function decode(value){try{return decodeURIComponent(value)}catch(e){debug("error `decode(%o)` - %o",value,e)}}},{debug:203}],197:[function(require,module,exports){module.exports=function uuid(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,uuid)}},{}],75:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var Sentry=module.exports=integration("Sentry").global("Raven").option("config","").tag('<script src="//cdn.ravenjs.com/1.1.16/native/raven.min.js">');Sentry.prototype.initialize=function(){var dsn=this.options.config;window.RavenConfig={dsn:dsn};this.load(this.ready)};Sentry.prototype.loaded=function(){return is.object(window.Raven)};Sentry.prototype.identify=function(identify){window.Raven.setUser(identify.traits())}},{"analytics.js-integration":88,is:91}],76:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var SnapEngage=module.exports=integration("SnapEngage").assumesPageview().global("SnapABug").option("apiKey","").tag('<script src="//commondatastorage.googleapis.com/code.snapengage.com/js/{{ apiKey }}.js">');SnapEngage.prototype.initialize=function(page){this.load(this.ready)};SnapEngage.prototype.loaded=function(){return is.object(window.SnapABug)};SnapEngage.prototype.identify=function(identify){var email=identify.email();if(!email)return;window.SnapABug.setUserEmail(email)}},{"analytics.js-integration":88,is:91}],77:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var Spinnakr=module.exports=integration("Spinnakr").assumesPageview().global("_spinnakr_site_id").global("_spinnakr").option("siteId","").tag('<script src="//d3ojzyhbolvoi5.cloudfront.net/js/so.js">');Spinnakr.prototype.initialize=function(page){window._spinnakr_site_id=this.options.siteId;var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Spinnakr.prototype.loaded=function(){return!!window._spinnakr}},{"analytics.js-integration":88,bind:101,when:146}],78:[function(require,module,exports){var integration=require("analytics.js-integration");var slug=require("slug");var push=require("global-queue")("_tsq");var Tapstream=module.exports=integration("Tapstream").assumesPageview().global("_tsq").option("accountName","").option("trackAllPages",true).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//cdn.tapstream.com/static/js/tapstream.js">');Tapstream.prototype.initialize=function(page){window._tsq=window._tsq||[];push("setAccountName",this.options.accountName);this.load(this.ready)};Tapstream.prototype.loaded=function(){return!!(window._tsq&&window._tsq.push!==Array.prototype.push)};Tapstream.prototype.page=function(page){var category=page.category();var opts=this.options;var name=page.fullName();if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Tapstream.prototype.track=function(track){var props=track.properties();push("fireHit",slug(track.event()),[props.url])}},{"analytics.js-integration":88,slug:99,"global-queue":174}],79:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var clone=require("clone");var Trakio=module.exports=integration("trak.io").assumesPageview().global("trak").option("token","").option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js">');var optionsAliases={initialPageview:"auto_track_page_view"};Trakio.prototype.initialize=function(page){var options=this.options;window.trak=window.trak||[];window.trak.io=window.trak.io||{};window.trak.push=window.trak.push||function(){};window.trak.io.load=window.trak.io.load||function(e){var r=function(e){return function(){window.trak.push([e].concat(Array.prototype.slice.call(arguments,0)))}},i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"];for(var s=0;s<i.length;s++)window.trak.io[i[s]]=r(i[s]);window.trak.io.initialize.apply(window.trak.io,arguments)};window.trak.io.load(options.token,alias(options,optionsAliases));this.load(this.ready)};Trakio.prototype.loaded=function(){return!!(window.trak&&window.trak.loaded)};Trakio.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();window.trak.io.page_view(props.path,name||props.title);if(name&&this.options.trackNamedPages){this.track(page.track(name))}if(category&&this.options.trackCategorizedPages){this.track(page.track(category))}};var traitAliases={avatar:"avatar_url",firstName:"first_name",lastName:"last_name"};Trakio.prototype.identify=function(identify){var traits=identify.traits(traitAliases);var id=identify.userId();if(id){window.trak.io.identify(id,traits)}else{window.trak.io.identify(traits)}};Trakio.prototype.track=function(track){window.trak.io.track(track.event(),track.properties())};Trakio.prototype.alias=function(alias){if(!window.trak.io.distinct_id)return;var from=alias.from();var to=alias.to();if(to===window.trak.io.distinct_id())return;if(from){window.trak.io.alias(from,to)}else{window.trak.io.alias(to)}}},{"analytics.js-integration":88,alias:178,clone:95}],80:[function(require,module,exports){var integration=require("analytics.js-integration");var each=require("each");var has=Object.prototype.hasOwnProperty;var TwitterAds=module.exports=integration("Twitter Ads").option("page","").tag('<img src="//analytics.twitter.com/i/adsct?txn_id={{ pixelId }}&p_id=Twitter"/>').mapping("events");TwitterAds.prototype.initialize=function(){this.ready()};TwitterAds.prototype.page=function(page){if(this.options.page){this.load({pixelId:this.options.page})}};TwitterAds.prototype.track=function(track){var events=this.events(track.event());var self=this;each(events,function(pixelId){self.load({pixelId:pixelId})})}},{"analytics.js-integration":88,each:4}],81:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var clone=require("clone");var Userlike=module.exports=integration("Userlike").assumesPageview().global("userlikeConfig").global("userlikeData").option("secretKey","").tag('<script src="//userlike-cdn-widgets.s3-eu-west-1.amazonaws.com/{{ secretKey }}.js">');Userlike.prototype.initialize=function(page){var self=this;var user=this.analytics.user();var identify=new Identify({userId:user.id(),traits:user.traits()});segment_base_info=clone(this.options);segment_base_info.visitor={name:identify.name(),email:identify.email()};if(!window.userlikeData)window.userlikeData={custom:{}};window.userlikeData.custom.segmentio=segment_base_info;this.load(function(){self.ready()})};Userlike.prototype.loaded=function(){return!!(window.userlikeConfig&&window.userlikeData)}},{"analytics.js-integration":88,facade:147,clone:95}],82:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("UserVoice");var convertDates=require("convert-dates");var unix=require("to-unix-timestamp");var alias=require("alias");var clone=require("clone");var UserVoice=module.exports=integration("UserVoice").assumesPageview().global("UserVoice").global("showClassicWidget").option("apiKey","").option("classic",false).option("forumId",null).option("showWidget",true).option("mode","contact").option("accentColor","#448dd6").option("screenshotEnabled",true).option("smartvote",true).option("trigger",null).option("triggerPosition","bottom-right").option("triggerColor","#ffffff").option("triggerBackgroundColor","rgba(46, 49, 51, 0.6)").option("classicMode","full").option("primaryColor","#cc6d00").option("linkColor","#007dbf").option("defaultMode","support").option("tabLabel","Feedback & Support").option("tabColor","#cc6d00").option("tabPosition","middle-right").option("tabInverted",false).option("customTicketFields",{}).tag('<script src="//widget.uservoice.com/{{ apiKey }}.js">');UserVoice.on("construct",function(integration){if(!integration.options.classic)return;integration.group=undefined;integration.identify=integration.identifyClassic;integration.initialize=integration.initializeClassic});UserVoice.prototype.initialize=function(page){var options=this.options;var opts=formatOptions(options);push("set",opts);push("autoprompt",{});if(options.showWidget){options.trigger?push("addTrigger",options.trigger,opts):push("addTrigger",opts)}this.load(this.ready)};UserVoice.prototype.loaded=function(){return!!(window.UserVoice&&window.UserVoice.push!==Array.prototype.push)};UserVoice.prototype.identify=function(identify){var traits=identify.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",traits)};UserVoice.prototype.group=function(group){var traits=group.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",{account:traits})};UserVoice.prototype.initializeClassic=function(){var options=this.options;window.showClassicWidget=showClassicWidget;if(options.showWidget)showClassicWidget("showTab",formatClassicOptions(options));this.load(this.ready)};UserVoice.prototype.identifyClassic=function(identify){push("setCustomFields",identify.traits())};function formatOptions(options){return alias(options,{forumId:"forum_id",accentColor:"accent_color",smartvote:"smartvote_enabled",triggerColor:"trigger_color",triggerBackgroundColor:"trigger_background_color",triggerPosition:"trigger_position",screenshotEnabled:"screenshot_enabled",customTicketFields:"ticket_custom_fields"})}function formatClassicOptions(options){return alias(options,{forumId:"forum_id",classicMode:"mode",primaryColor:"primary_color",tabPosition:"tab_position",tabColor:"tab_color",linkColor:"link_color",defaultMode:"default_mode",tabLabel:"tab_label",tabInverted:"tab_inverted"})}function showClassicWidget(type,options){type=type||"showLightbox";push(type,"classic_widget",options)}},{"analytics.js-integration":88,"global-queue":174,"convert-dates":179,"to-unix-timestamp":206,alias:178,clone:95}],206:[function(require,module,exports){module.exports=toUnixTimestamp;function toUnixTimestamp(date){return Math.floor(date.getTime()/1e3)}},{}],83:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_veroq");var cookie=require("component/cookie");var objCase=require("obj-case");var Vero=module.exports=integration("Vero").global("_veroq").option("apiKey","").tag('<script src="//d3qxef4rp70elm.cloudfront.net/m.js">');Vero.prototype.initialize=function(page){if(!cookie("__veroc4"))cookie("__veroc4","[]");push("init",{api_key:this.options.apiKey});this.load(this.ready)};Vero.prototype.loaded=function(){return!!(window._veroq&&window._veroq.push!==Array.prototype.push)};Vero.prototype.page=function(page){push("trackPageview")};Vero.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var id=identify.userId();if(!id||!email)return;push("user",traits)};Vero.prototype.track=function(track){var regex=/[uU]nsubscribe/;if(track.event().match(regex)){push("unsubscribe",{id:track.properties().id})}else{push("track",track.event(),track.properties())}};Vero.prototype.alias=function(alias){var to=alias.to();if(alias.from()){push("reidentify",to,alias.from())}else{push("reidentify",to)}}},{"analytics.js-integration":88,"global-queue":174,"component/cookie":196,"obj-case":92}],84:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var each=require("each");var VWO=module.exports=integration("Visual Website Optimizer").option("replay",true);VWO.prototype.initialize=function(){if(this.options.replay)this.replay();this.ready()};VWO.prototype.replay=function(){var analytics=this.analytics;tick(function(){experiments(function(err,traits){if(traits)analytics.identify(traits)})})};function experiments(fn){enqueue(function(){var data={};var ids=window._vwo_exp_ids;if(!ids)return fn();each(ids,function(id){var name=variation(id);if(name)data["Experiment: "+id]=name});fn(null,data)})}function enqueue(fn){window._vis_opt_queue=window._vis_opt_queue||[];window._vis_opt_queue.push(fn)}function variation(id){var experiments=window._vwo_exp;if(!experiments)return null;var experiment=experiments[id];var variationId=experiment.combination_chosen;return variationId?experiment.comb_n[variationId]:null}},{"analytics.js-integration":88,"next-tick":103,each:4}],85:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var WebEngage=module.exports=integration("WebEngage").assumesPageview().global("_weq").global("webengage").option("widgetVersion","4.0").option("licenseCode","").tag("http",'<script src="http://cdn.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">').tag("https",'<script src="https://ssl.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">');WebEngage.prototype.initialize=function(page){var _weq=window._weq=window._weq||{};_weq["webengage.licenseCode"]=this.options.licenseCode;_weq["webengage.widgetVersion"]=this.options.widgetVersion;var name=useHttps()?"https":"http";this.load(name,this.ready)};WebEngage.prototype.loaded=function(){return!!window.webengage}},{"analytics.js-integration":88,"use-https":90}],86:[function(require,module,exports){var integration=require("analytics.js-integration");var snake=require("to-snake-case");var isEmail=require("is-email");var extend=require("extend");var each=require("each");var type=require("type");var Woopra=module.exports=integration("Woopra").global("woopra").option("domain","").option("cookieName","wooTracker").option("cookieDomain",null).option("cookiePath","/").option("ping",true).option("pingInterval",12e3).option("idleTimeout",3e5).option("downloadTracking",true).option("outgoingTracking",true).option("outgoingIgnoreSubdomain",true).option("downloadPause",200).option("outgoingPause",400).option("ignoreQueryUrl",true).option("hideCampaign",false).tag('<script src="//static.woopra.com/js/w.js">');Woopra.prototype.initialize=function(page){(function(){var i,s,z,w=window,d=document,a=arguments,q="script",f=["config","track","identify","visit","push","call"],c=function(){var i,self=this;self._e=[];for(i=0;i<f.length;i++){(function(f){self[f]=function(){self._e.push([f].concat(Array.prototype.slice.call(arguments,0)));return self}})(f[i])}};w._w=w._w||{};for(i=0;i<a.length;i++){w._w[a[i]]=w[a[i]]=w[a[i]]||new c}})("woopra");this.load(this.ready);each(this.options,function(key,value){key=snake(key);if(null==value)return;if(""===value)return;window.woopra.config(key,value)})};Woopra.prototype.loaded=function(){return!!(window.woopra&&window.woopra.loaded)};Woopra.prototype.page=function(page){var props=page.properties();var name=page.fullName();if(name)props.title=name;window.woopra.track("pv",props)};Woopra.prototype.identify=function(identify){var traits=identify.traits();if(identify.name())traits.name=identify.name();window.woopra.identify(traits).push()};Woopra.prototype.track=function(track){window.woopra.track(track.event(),track.properties())}},{"analytics.js-integration":88,"to-snake-case":89,"is-email":170,extend:145,each:4,type:113}],87:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var bind=require("bind");var when=require("when");var Yandex=module.exports=integration("Yandex Metrica").assumesPageview().global("yandex_metrika_callbacks").global("Ya").option("counterId",null).option("clickmap",false).option("webvisor",false).tag('<script src="//mc.yandex.ru/metrika/watch.js">');Yandex.prototype.initialize=function(page){var id=this.options.counterId;var clickmap=this.options.clickmap;var webvisor=this.options.webvisor;push(function(){window["yaCounter"+id]=new window.Ya.Metrika({id:id,clickmap:clickmap,webvisor:webvisor})});var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,function(){tick(ready)})})};Yandex.prototype.loaded=function(){return!!(window.Ya&&window.Ya.Metrika)};function push(callback){window.yandex_metrika_callbacks=window.yandex_metrika_callbacks||[];window.yandex_metrika_callbacks.push(callback)}},{"analytics.js-integration":88,"next-tick":103,bind:101,when:146}],3:[function(require,module,exports){var _analytics=window.analytics;var after=require("after");var bind=require("bind");var callback=require("callback");var clone=require("clone");var cookie=require("./cookie");var debug=require("debug");var defaults=require("defaults");var each=require("each");var Emitter=require("emitter");var group=require("./group");var is=require("is");var isEmail=require("is-email");var isMeta=require("is-meta");var newDate=require("new-date");var on=require("event").bind;var pageDefaults=require("./pageDefaults");var pick=require("pick");var prevent=require("prevent");var querystring=require("querystring");var normalize=require("./normalize");var size=require("object").length;var keys=require("object").keys;var memory=require("./memory");var store=require("./store");var user=require("./user");var Facade=require("facade");var Identify=Facade.Identify;var Group=Facade.Group;var Alias=Facade.Alias;var Track=Facade.Track;var Page=Facade.Page;exports=module.exports=Analytics;exports.cookie=cookie;exports.store=store;exports.memory=memory;function Analytics(){this._options({});this.Integrations={};this._integrations={};this._readied=false;this._timeout=300;this._user=user;this.log=debug("analytics.js");bind.all(this);var self=this;this.on("initialize",function(settings,options){if(options.initialPageview)self.page();self._parseQuery()})}Emitter(Analytics.prototype);Analytics.prototype.use=function(plugin){plugin(this);return this};Analytics.prototype.addIntegration=function(Integration){var name=Integration.prototype.name;if(!name)throw new TypeError("attempted to add an invalid integration");this.Integrations[name]=Integration;return this};Analytics.prototype.init=Analytics.prototype.initialize=function(settings,options){settings=settings||{};options=options||{};this._options(options);this._readied=false;var self=this;each(settings,function(name){var Integration=self.Integrations[name];if(!Integration)delete settings[name]});each(settings,function(name,opts){var Integration=self.Integrations[name];var integration=new Integration(clone(opts));self.log("initialize %o - %o",name,opts);self.add(integration)});var integrations=this._integrations;user.load();group.load();var ready=after(size(integrations),function(){self._readied=true;self.emit("ready")});each(integrations,function(name,integration){if(options.initialPageview&&integration.options.initialPageview===false){integration.page=after(2,integration.page)}integration.analytics=self;integration.once("ready",ready);integration.initialize()});this.initialized=true;this.emit("initialize",settings,options);return this};Analytics.prototype.setAnonymousId=function(id){this.user().anonymousId(id);return this};Analytics.prototype.add=function(integration){this._integrations[integration.name]=integration;return this};Analytics.prototype.identify=function(id,traits,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=user.id();user.identify(id,traits);var msg=this.normalize({options:options,traits:user.traits(),userId:user.id()});this._invoke("identify",new Identify(msg));this.emit("identify",id,traits,options);this._callback(fn);return this};Analytics.prototype.user=function(){return user};Analytics.prototype.group=function(id,traits,options,fn){if(0===arguments.length)return group;if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=group.id();group.identify(id,traits);var msg=this.normalize({options:options,traits:group.traits(),groupId:group.id()});this._invoke("group",new Group(msg));this.emit("group",id,traits,options);this._callback(fn);return this};Analytics.prototype.track=function(event,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=null,properties=null;var plan=this.options.plan||{};var events=plan.track||{};var msg=this.normalize({properties:properties,options:options,event:event});if(plan=events[event]){this.log("plan %o - %o",event,plan);if(false==plan.enabled)return this._callback(fn);defaults(msg.integrations,plan.integrations||{})}this._invoke("track",new Track(msg));this.emit("track",event,properties,options);this._callback(fn);return this};Analytics.prototype.trackClick=Analytics.prototype.trackLink=function(links,event,properties){if(!links)return this;if(is.element(links))links=[links];var self=this;each(links,function(el){if(!is.element(el))throw new TypeError("Must pass HTMLElement to `analytics.trackLink`.");on(el,"click",function(e){var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;var href=el.getAttribute("href")||el.getAttributeNS("http://www.w3.org/1999/xlink","href")||el.getAttribute("xlink:href");self.track(ev,props);if(href&&el.target!=="_blank"&&!isMeta(e)){prevent(e);self._callback(function(){window.location.href=href})}})});return this};Analytics.prototype.trackSubmit=Analytics.prototype.trackForm=function(forms,event,properties){if(!forms)return this;if(is.element(forms))forms=[forms];var self=this;each(forms,function(el){if(!is.element(el))throw new TypeError("Must pass HTMLElement to `analytics.trackForm`.");function handler(e){prevent(e);var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);self._callback(function(){el.submit()})}var $=window.jQuery||window.Zepto;if($){$(el).submit(handler)}else{on(el,"submit",handler)}});return this};Analytics.prototype.page=function(category,name,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=properties=null;if(is.fn(name))fn=name,options=properties=name=null;if(is.object(category))options=name,properties=category,name=category=null;if(is.object(name))options=properties,properties=name,name=null;if(is.string(category)&&!is.string(name))name=category,category=null;properties=clone(properties)||{};if(name)properties.name=name;if(category)properties.category=category;var defs=pageDefaults();defaults(properties,defs);var overrides=pick(keys(defs),properties);if(!is.empty(overrides)){options=options||{};options.context=options.context||{};options.context.page=overrides}var msg=this.normalize({properties:properties,category:category,options:options,name:name});this._invoke("page",new Page(msg));this.emit("page",category,name,properties,options);this._callback(fn);return this};Analytics.prototype.pageview=function(url,options){var properties={};if(url)properties.path=url;this.page(properties);return this};Analytics.prototype.alias=function(to,from,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(from))fn=from,options=null,from=null;if(is.object(from))options=from,from=null;var msg=this.normalize({options:options,previousId:from,userId:to});this._invoke("alias",new Alias(msg));this.emit("alias",to,from,options);this._callback(fn);return this};Analytics.prototype.ready=function(fn){if(!is.fn(fn))return this;this._readied?callback.async(fn):this.once("ready",fn);return this};Analytics.prototype.timeout=function(timeout){this._timeout=timeout};Analytics.prototype.debug=function(str){if(0==arguments.length||str){debug.enable("analytics:"+(str||"*"))}else{debug.disable()}};Analytics.prototype._options=function(options){options=options||{};this.options=options;cookie.options(options.cookie);store.options(options.localStorage);user.options(options.user);group.options(options.group);return this};Analytics.prototype._callback=function(fn){callback.async(fn,this._timeout);return this};Analytics.prototype._invoke=function(method,facade){var options=facade.options();this.emit("invoke",facade);each(this._integrations,function(name,integration){if(!facade.enabled(name))return;integration.invoke.call(integration,method,facade)});return this};Analytics.prototype.push=function(args){var method=args.shift();if(!this[method])return;this[method].apply(this,args)};Analytics.prototype.reset=function(){this.user().logout();this.group().logout()};Analytics.prototype._parseQuery=function(){var q=querystring.parse(window.location.search);if(q.ajs_uid)this.identify(q.ajs_uid);if(q.ajs_event)this.track(q.ajs_event);if(q.ajs_aid)user.anonymousId(q.ajs_aid);return this};Analytics.prototype.normalize=function(msg){msg=normalize(msg,keys(this._integrations));if(msg.anonymousId)user.anonymousId(msg.anonymousId);msg.anonymousId=user.anonymousId();msg.context.page=defaults(msg.context.page||{},pageDefaults());return msg};Analytics.prototype.noConflict=function(){window.analytics=_analytics;return this}},{after:111,bind:207,callback:94,clone:95,"./cookie":208,debug:203,defaults:97,each:4,emitter:110,"./group":209,is:91,"is-email":170,"is-meta":210,"new-date":162,event:211,"./pageDefaults":212,pick:213,prevent:214,querystring:215,"./normalize":216,object:183,"./memory":217,"./store":218,"./user":219,facade:147}],207:[function(require,module,exports){try{var bind=require("bind")}catch(e){var bind=require("bind-component")}var bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;function bindMethods(obj,methods){methods=[].slice.call(arguments,1);for(var i=0,method;method=methods[i];i++){obj[method]=bind(obj,obj[method])}return obj}},{bind:101,"bind-all":102}],208:[function(require,module,exports){var debug=require("debug")("analytics.js:cookie");
var bind=require("bind");var cookie=require("cookie");var clone=require("clone");var defaults=require("defaults");var json=require("json");var topDomain=require("top-domain");function Cookie(options){this.options(options)}Cookie.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};var domain="."+topDomain(window.location.href);this._options=defaults(options,{maxage:31536e6,path:"/",domain:domain});this.set("ajs:test",true);if(!this.get("ajs:test")){debug("fallback to domain=null");this._options.domain=null}this.remove("ajs:test")};Cookie.prototype.set=function(key,value){try{value=json.stringify(value);cookie(key,value,clone(this._options));return true}catch(e){return false}};Cookie.prototype.get=function(key){try{var value=cookie(key);value=value?json.parse(value):null;return value}catch(e){return null}};Cookie.prototype.remove=function(key){try{cookie(key,null,clone(this._options));return true}catch(e){return false}};module.exports=bind.all(new Cookie);module.exports.Cookie=Cookie},{debug:203,bind:207,cookie:196,clone:95,defaults:97,json:180,"top-domain":139}],209:[function(require,module,exports){var debug=require("debug")("analytics:group");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");Group.defaults={persist:true,cookie:{key:"ajs_group_id"},localStorage:{key:"ajs_group_properties"}};function Group(options){this.defaults=Group.defaults;this.debug=debug;Entity.call(this,options)}inherit(Group,Entity);module.exports=bind.all(new Group);module.exports.Group=Group},{debug:203,"./entity":220,inherit:221,bind:207}],220:[function(require,module,exports){var debug=require("debug")("analytics:entity");var traverse=require("isodate-traverse");var defaults=require("defaults");var memory=require("./memory");var cookie=require("./cookie");var store=require("./store");var extend=require("extend");var clone=require("clone");module.exports=Entity;function Entity(options){this.options(options);this.initialize()}Entity.prototype.initialize=function(){cookie.set("ajs:cookies",true);if(cookie.get("ajs:cookies")){cookie.remove("ajs:cookies");this._storage=cookie;return}if(store.enabled){this._storage=store;return}debug("warning using memory store both cookies and localStorage are disabled");this._storage=memory};Entity.prototype.storage=function(){return this._storage};Entity.prototype.options=function(options){if(arguments.length===0)return this._options;options||(options={});defaults(options,this.defaults||{});this._options=options};Entity.prototype.id=function(id){switch(arguments.length){case 0:return this._getId();case 1:return this._setId(id)}};Entity.prototype._getId=function(){var ret=this._options.persist?this.storage().get(this._options.cookie.key):this._id;return ret===undefined?null:ret};Entity.prototype._setId=function(id){if(this._options.persist){this.storage().set(this._options.cookie.key,id)}else{this._id=id}};Entity.prototype.properties=Entity.prototype.traits=function(traits){switch(arguments.length){case 0:return this._getTraits();case 1:return this._setTraits(traits)}};Entity.prototype._getTraits=function(){var ret=this._options.persist?store.get(this._options.localStorage.key):this._traits;return ret?traverse(clone(ret)):{}};Entity.prototype._setTraits=function(traits){traits||(traits={});if(this._options.persist){store.set(this._options.localStorage.key,traits)}else{this._traits=traits}};Entity.prototype.identify=function(id,traits){traits||(traits={});var current=this.id();if(current===null||current===id)traits=extend(this.traits(),traits);if(id)this.id(id);this.debug("identify %o, %o",id,traits);this.traits(traits);this.save()};Entity.prototype.save=function(){if(!this._options.persist)return false;cookie.set(this._options.cookie.key,this.id());store.set(this._options.localStorage.key,this.traits());return true};Entity.prototype.logout=function(){this.id(null);this.traits({});cookie.remove(this._options.cookie.key);store.remove(this._options.localStorage.key)};Entity.prototype.reset=function(){this.logout();this.options({})};Entity.prototype.load=function(){this.id(cookie.get(this._options.cookie.key));this.traits(store.get(this._options.localStorage.key))}},{debug:203,"isodate-traverse":157,defaults:97,"./memory":217,"./cookie":208,"./store":218,extend:145,clone:95}],217:[function(require,module,exports){var clone=require("clone");var bind=require("bind");var has=Object.prototype.hasOwnProperty;module.exports=bind.all(new Memory);function Memory(){this.store={}}Memory.prototype.set=function(key,value){this.store[key]=clone(value);return true};Memory.prototype.get=function(key){if(!has.call(this.store,key))return;return clone(this.store[key])};Memory.prototype.remove=function(key){delete this.store[key];return true}},{clone:95,bind:207}],218:[function(require,module,exports){var bind=require("bind");var defaults=require("defaults");var store=require("store.js");function Store(options){this.options(options)}Store.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};defaults(options,{enabled:true});this.enabled=options.enabled&&store.enabled;this._options=options};Store.prototype.set=function(key,value){if(!this.enabled)return false;return store.set(key,value)};Store.prototype.get=function(key){if(!this.enabled)return null;return store.get(key)};Store.prototype.remove=function(key){if(!this.enabled)return false;return store.remove(key)};module.exports=bind.all(new Store);module.exports.Store=Store},{bind:207,defaults:97,"store.js":222}],222:[function(require,module,exports){var json=require("json"),store={},win=window,doc=win.document,localStorageName="localStorage",namespace="__storejs__",storage;store.disabled=false;store.set=function(key,value){};store.get=function(key){};store.remove=function(key){};store.clear=function(){};store.transact=function(key,defaultVal,transactionFn){var val=store.get(key);if(transactionFn==null){transactionFn=defaultVal;defaultVal=null}if(typeof val=="undefined"){val=defaultVal||{}}transactionFn(val);store.set(key,val)};store.getAll=function(){};store.serialize=function(value){return json.stringify(value)};store.deserialize=function(value){if(typeof value!="string"){return undefined}try{return json.parse(value)}catch(e){return value||undefined}};function isLocalStorageNameSupported(){try{return localStorageName in win&&win[localStorageName]}catch(err){return false}}if(isLocalStorageNameSupported()){storage=win[localStorageName];store.set=function(key,val){if(val===undefined){return store.remove(key)}storage.setItem(key,store.serialize(val));return val};store.get=function(key){return store.deserialize(storage.getItem(key))};store.remove=function(key){storage.removeItem(key)};store.clear=function(){storage.clear()};store.getAll=function(){var ret={};for(var i=0;i<storage.length;++i){var key=storage.key(i);ret[key]=store.get(key)}return ret}}else if(doc.documentElement.addBehavior){var storageOwner,storageContainer;try{storageContainer=new ActiveXObject("htmlfile");storageContainer.open();storageContainer.write("<s"+"cript>document.w=window</s"+'cript><iframe src="/favicon.ico"></iframe>');storageContainer.close();storageOwner=storageContainer.w.frames[0].document;storage=storageOwner.createElement("div")}catch(e){storage=doc.createElement("div");storageOwner=doc.body}function withIEStorage(storeFunction){return function(){var args=Array.prototype.slice.call(arguments,0);args.unshift(storage);storageOwner.appendChild(storage);storage.addBehavior("#default#userData");storage.load(localStorageName);var result=storeFunction.apply(store,args);storageOwner.removeChild(storage);return result}}var forbiddenCharsRegex=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");function ieKeyFix(key){return key.replace(forbiddenCharsRegex,"___")}store.set=withIEStorage(function(storage,key,val){key=ieKeyFix(key);if(val===undefined){return store.remove(key)}storage.setAttribute(key,store.serialize(val));storage.save(localStorageName);return val});store.get=withIEStorage(function(storage,key){key=ieKeyFix(key);return store.deserialize(storage.getAttribute(key))});store.remove=withIEStorage(function(storage,key){key=ieKeyFix(key);storage.removeAttribute(key);storage.save(localStorageName)});store.clear=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;storage.load(localStorageName);for(var i=0,attr;attr=attributes[i];i++){storage.removeAttribute(attr.name)}storage.save(localStorageName)});store.getAll=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;var ret={};for(var i=0,attr;attr=attributes[i];++i){var key=ieKeyFix(attr.name);ret[attr.name]=store.deserialize(storage.getAttribute(key))}return ret})}try{store.set(namespace,namespace);if(store.get(namespace)!=namespace){store.disabled=true}store.remove(namespace)}catch(e){store.disabled=true}store.enabled=!store.disabled;module.exports=store},{json:180}],221:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],210:[function(require,module,exports){module.exports=function isMeta(e){if(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)return true;var which=e.which,button=e.button;if(!which&&button!==undefined){return!button&1&&!button&2&&button&4}else if(which===2){return true}return false}},{}],211:[function(require,module,exports){exports.bind=function(el,type,fn,capture){if(el.addEventListener){el.addEventListener(type,fn,capture||false)}else{el.attachEvent("on"+type,fn)}return fn};exports.unbind=function(el,type,fn,capture){if(el.removeEventListener){el.removeEventListener(type,fn,capture||false)}else{el.detachEvent("on"+type,fn)}return fn}},{}],212:[function(require,module,exports){var canonical=require("canonical");var url=require("url");function pageDefaults(){return{path:canonicalPath(),referrer:document.referrer,search:location.search,title:document.title,url:canonicalUrl(location.search)}}function canonicalPath(){var canon=canonical();if(!canon)return window.location.pathname;var parsed=url.parse(canon);return parsed.pathname}function canonicalUrl(search){var canon=canonical();if(canon)return~canon.indexOf("?")?canon:canon+search;var url=window.location.href;var i=url.indexOf("#");return-1===i?url:url.slice(0,i)}module.exports=pageDefaults},{canonical:184,url:186}],213:[function(require,module,exports){"use strict";var objToString=Object.prototype.toString;var existy=function(val){return val!=null};var isArray=function(val){return objToString.call(val)==="[object Array]"};var isString=function(val){return typeof val==="string"||objToString.call(val)==="[object String]"};var isObject=function(val){return val!=null&&typeof val==="object"};var pick=function pick(props,object){if(!existy(object)||!isObject(object)){return{}}if(isString(props)){props=[props]}if(!isArray(props)){props=[]}var result={};for(var i=0;i<props.length;i+=1){if(isString(props[i])&&props[i]in object){result[props[i]]=object[props[i]]}}return result};module.exports=pick},{}],214:[function(require,module,exports){module.exports=function(e){e=e||window.event;return e.preventDefault?e.preventDefault():e.returnValue=false}},{}],215:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=/(\w+)\[(\d+)\]/.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:141,type:7}],216:[function(require,module,exports){var debug=require("debug")("analytics.js:normalize");var indexof=require("component/indexof");var defaults=require("defaults");var map=require("component/map");var each=require("each");var is=require("is");var has=Object.prototype.hasOwnProperty;module.exports=normalize;var toplevel=["integrations","anonymousId","timestamp","context"];function normalize(msg,list){var lower=map(list,function(s){return s.toLowerCase()});var opts=msg.options||{};var integrations=opts.integrations||{};var providers=opts.providers||{};var context=opts.context||{};var ret={};debug("<-",msg);each(opts,function(key,value){if(!integration(key))return;if(!has.call(integrations,key))integrations[key]=value;delete opts[key]});delete opts.providers;each(providers,function(key,value){if(!integration(key))return;if(is.object(integrations[key]))return;if(has.call(integrations,key)&&"boolean"==typeof providers[key])return;integrations[key]=value});each(opts,function(key){if(~indexof(toplevel,key)){ret[key]=opts[key]}else{context[key]=opts[key]}});delete msg.options;ret.integrations=integrations;ret.context=context;ret=defaults(ret,msg);debug("->",ret);return ret;function integration(name){return!!(~indexof(list,name)||"all"==name.toLowerCase()||~indexof(lower,name.toLowerCase()))}}},{debug:203,"component/indexof":116,defaults:97,"component/map":223,each:4,is:91}],223:[function(require,module,exports){var toFunction=require("to-function");module.exports=function(arr,fn){var ret=[];fn=toFunction(fn);for(var i=0;i<arr.length;++i){ret.push(fn(arr[i],i))}return ret}},{"to-function":187}],219:[function(require,module,exports){var debug=require("debug")("analytics:user");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");var cookie=require("./cookie");var uuid=require("uuid");var rawCookie=require("cookie");User.defaults={persist:true,cookie:{key:"ajs_user_id",oldKey:"ajs_user"},localStorage:{key:"ajs_user_traits"}};function User(options){this.defaults=User.defaults;this.debug=debug;Entity.call(this,options)}inherit(User,Entity);User.prototype.id=function(id){var prev=this._getId();var ret=Entity.prototype.id.apply(this,arguments);if(null==prev)return ret;if(prev!=id&&id)this.anonymousId(null);return ret};User.prototype.anonymousId=function(anonId){var store=this.storage();if(arguments.length){store.set("ajs_anonymous_id",anonId);return this}if(anonId=store.get("ajs_anonymous_id")){return anonId}if(anonId=rawCookie("_sio")){anonId=anonId.split("----")[0];store.set("ajs_anonymous_id",anonId);store.remove("_sio");return anonId}anonId=uuid();store.set("ajs_anonymous_id",anonId);return store.get("ajs_anonymous_id")};User.prototype.logout=function(){Entity.prototype.logout.call(this);this.anonymousId(null)};User.prototype.load=function(){if(this._loadOldCookie())return;Entity.prototype.load.call(this)};User.prototype._loadOldCookie=function(){var user=cookie.get(this._options.cookie.oldKey);if(!user)return false;this.id(user.id);this.traits(user.traits);cookie.remove(this._options.cookie.oldKey);return true};module.exports=bind.all(new User);module.exports.User=User},{debug:203,"./entity":220,inherit:221,bind:207,"./cookie":208,uuid:197,cookie:196}],5:[function(require,module,exports){module.exports={name:"analytics",version:"2.8.1",main:"analytics.js",dependencies:{},devDependencies:{}}},{}]},{},{1:""})); |
node_modules/react-bootstrap/es/ControlLabel.js | okristian1/react-info | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import warning from 'warning';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
/**
* Uses `controlId` from `<FormGroup>` if not explicitly specified.
*/
htmlFor: React.PropTypes.string,
srOnly: React.PropTypes.bool
};
var defaultProps = {
srOnly: false
};
var contextTypes = {
$bs_formGroup: React.PropTypes.object
};
var ControlLabel = function (_React$Component) {
_inherits(ControlLabel, _React$Component);
function ControlLabel() {
_classCallCheck(this, ControlLabel);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
ControlLabel.prototype.render = function render() {
var formGroup = this.context.$bs_formGroup;
var controlId = formGroup && formGroup.controlId;
var _props = this.props,
_props$htmlFor = _props.htmlFor,
htmlFor = _props$htmlFor === undefined ? controlId : _props$htmlFor,
srOnly = _props.srOnly,
className = _props.className,
props = _objectWithoutProperties(_props, ['htmlFor', 'srOnly', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
process.env.NODE_ENV !== 'production' ? warning(controlId == null || htmlFor === controlId, '`controlId` is ignored on `<ControlLabel>` when `htmlFor` is specified.') : void 0;
var classes = _extends({}, getClassSet(bsProps), {
'sr-only': srOnly
});
return React.createElement('label', _extends({}, elementProps, {
htmlFor: htmlFor,
className: classNames(className, classes)
}));
};
return ControlLabel;
}(React.Component);
ControlLabel.propTypes = propTypes;
ControlLabel.defaultProps = defaultProps;
ControlLabel.contextTypes = contextTypes;
export default bsClass('control-label', ControlLabel); |
2/bower_components/bootstrap/js/tests/vendor/jquery.js | Chitrank-Dixit/bootswatch | /*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.min.map
*/(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;
return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="<a name='"+x+"'></a><div name='"+x+"'></div>",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&>(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Nt=/^(?:checkbox|radio)$/i,Ct=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:b.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l)
}b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("<div>").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window); |
public/js/components/trends/trendbox.react.js | rajikaimal/Coupley | import React from 'react';
import List from 'material-ui/lib/lists/list';
import ListItem from 'material-ui/lib/lists/list-item';
import ActionGrade from 'material-ui/lib/svg-icons/action/grade';
import ActionInfo from 'material-ui/lib/svg-icons/action/info';
import ContentInbox from 'material-ui/lib/svg-icons/content/inbox';
import ContentDrafts from 'material-ui/lib/svg-icons/content/drafts';
import ContentSend from 'material-ui/lib/svg-icons/content/send';
import Divider from 'material-ui/lib/divider';
const Trends = React.createClass({
changeHandler: function(e) {
this.props.abc(this.props.trends);
},
render:function(){
return(
<ListItem primaryText={this.props.trends} id={this.props.tid} onTouchTap={this.changeHandler}/>
);
}
});
export default Trends;
|
src/svg-icons/action/timeline.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionTimeline = (props) => (
<SvgIcon {...props}>
<path d="M23 8c0 1.1-.9 2-2 2-.18 0-.35-.02-.51-.07l-3.56 3.55c.05.16.07.34.07.52 0 1.1-.9 2-2 2s-2-.9-2-2c0-.18.02-.36.07-.52l-2.55-2.55c-.16.05-.34.07-.52.07s-.36-.02-.52-.07l-4.55 4.56c.05.16.07.33.07.51 0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2c.18 0 .35.02.51.07l4.56-4.55C8.02 9.36 8 9.18 8 9c0-1.1.9-2 2-2s2 .9 2 2c0 .18-.02.36-.07.52l2.55 2.55c.16-.05.34-.07.52-.07s.36.02.52.07l3.55-3.56C19.02 8.35 19 8.18 19 8c0-1.1.9-2 2-2s2 .9 2 2z"/>
</SvgIcon>
);
ActionTimeline = pure(ActionTimeline);
ActionTimeline.displayName = 'ActionTimeline';
export default ActionTimeline;
|
packages/demos/todomvc/src/components/List/index.js | fopsdev/cerebral | import React from 'react'
import Todo from '../Todo'
import { connect } from '@cerebral/react'
import { state, signal } from 'cerebral/tags'
import computedIsAllChecked from '../../computed/isAllChecked'
import computedTodosUid from '../../computed/visibleTodosUids'
export default connect(
{
editingUid: state`editingUid`,
isAllChecked: computedIsAllChecked,
todosUids: computedTodosUid,
toggleAllChanged: signal`toggleAllChanged`,
},
function List({ editingUid, isAllChecked, todosUids, toggleAllChanged }) {
return (
<section className="main">
<input
className="toggle-all"
type="checkbox"
checked={isAllChecked}
onChange={() => toggleAllChanged()}
/>
<label htmlFor="toggle-all">
Mark all as complete
</label>
<ul className="todo-list">
{todosUids.map((todoUid, index) => {
const isEditing = todoUid === editingUid
return <Todo key={todoUid} uid={todoUid} isEditing={isEditing} />
})}
</ul>
</section>
)
}
)
|
ajax/libs/styled-components/4.0.0-beta.10/styled-components.browser.cjs.js | sufuf3/cdnjs | 'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var Stylis = _interopDefault(require('stylis/stylis.min'));
var _insertRulePlugin = _interopDefault(require('stylis-rule-sheet'));
var React = require('react');
var React__default = _interopDefault(React);
var reactIs = require('react-is');
var memoize = _interopDefault(require('memoize-one'));
var PropTypes = _interopDefault(require('prop-types'));
var validAttr = _interopDefault(require('@emotion/is-prop-valid'));
//
var interleave = (function (strings, interpolations) {
var result = [strings[0]];
for (var i = 0, len = interpolations.length; i < len; i += 1) {
result.push(interpolations[i], strings[i + 1]);
}
return result;
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var objectWithoutProperties = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
//
var isPlainObject = (function (x) {
return (typeof x === 'undefined' ? 'undefined' : _typeof(x)) === 'object' && x.constructor === Object;
});
//
var EMPTY_ARRAY = Object.freeze([]);
var EMPTY_OBJECT = Object.freeze({});
//
function isFunction(test) {
return typeof test === 'function';
}
//
function isStyledComponent(target) {
return target && typeof target.styledComponentId === 'string';
}
//
var SC_ATTR = typeof process !== 'undefined' && process.env.SC_ATTR || 'data-styled';
var SC_VERSION_ATTR = 'data-styled-version';
var SC_STREAM_ATTR = 'data-styled-streamed';
var IS_BROWSER = typeof window !== 'undefined' && 'HTMLElement' in window;
var DISABLE_SPEEDY = process.env.NODE_ENV !== 'production';
// Shared empty execution context when generating static styles
var STATIC_EXECUTION_CONTEXT = {};
//
/**
* Parse errors.md and turn it into a simple hash of code: message
*/
var ERRORS = process.env.NODE_ENV !== 'production' ? {
"1": "Cannot create styled-component for component: %s.\n\n",
"2": "Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n",
"3": "Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n",
"4": "The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n",
"5": "The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n",
"6": "Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n",
"7": "ThemeProvider: Please return an object from your \"theme\" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n",
"8": "ThemeProvider: Please make your \"theme\" prop an object.\n\n",
"9": "Missing document `<head>`\n\n",
"10": "Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n",
"11": "_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n"
} : {};
/**
* super basic version of sprintf
*/
function format() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var a = args[0];
var b = [];
var c = void 0;
for (c = 1; c < args.length; c += 1) {
b.push(args[c]);
}
b.forEach(function (d) {
a = a.replace(/%[a-z]/, d);
});
return a;
}
/**
* Create an error file out of errors.md for development and a simple web link to the full errors
* in production mode.
*/
var StyledComponentsError = function (_Error) {
inherits(StyledComponentsError, _Error);
function StyledComponentsError(code) {
classCallCheck(this, StyledComponentsError);
for (var _len2 = arguments.length, interpolations = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
interpolations[_key2 - 1] = arguments[_key2];
}
if (process.env.NODE_ENV === 'production') {
var _this = possibleConstructorReturn(this, _Error.call(this, 'An error occurred. See https://github.com/styled-components/styled-components/blob/master/src/utils/errors.md#' + code + ' for more information. ' + (interpolations ? 'Additional arguments: ' + interpolations.join(', ') : '')));
} else {
var _this = possibleConstructorReturn(this, _Error.call(this, format.apply(undefined, [ERRORS[code]].concat(interpolations)).trim()));
}
return possibleConstructorReturn(_this);
}
return StyledComponentsError;
}(Error);
//
var SC_COMPONENT_ID = /^[^\S\n]*?\/\* sc-component-id:\s*(\S+)\s+\*\//gm;
var extractComps = (function (maybeCSS) {
var css = '' + (maybeCSS || ''); // Definitely a string, and a clone
var existingComponents = [];
css.replace(SC_COMPONENT_ID, function (match, componentId, matchIndex) {
existingComponents.push({ componentId: componentId, matchIndex: matchIndex });
return match;
});
return existingComponents.map(function (_ref, i) {
var componentId = _ref.componentId,
matchIndex = _ref.matchIndex;
var nextComp = existingComponents[i + 1];
var cssFromDOM = nextComp ? css.slice(matchIndex, nextComp.matchIndex) : css.slice(matchIndex);
return { componentId: componentId, cssFromDOM: cssFromDOM };
});
});
//
var COMMENT_REGEX = /^\s*\/\/.*$/gm;
// NOTE: This stylis instance is only used to split rules from SSR'd style tags
var stylisSplitter = new Stylis({
global: false,
cascade: true,
keyframe: false,
prefix: false,
compress: false,
semicolon: true
});
var stylis = new Stylis({
global: false,
cascade: true,
keyframe: false,
prefix: true,
compress: false,
semicolon: false // NOTE: This means "autocomplete missing semicolons"
});
// Wrap `insertRulePlugin to build a list of rules,
// and then make our own plugin to return the rules. This
// makes it easier to hook into the existing SSR architecture
var parsingRules = [];
// eslint-disable-next-line consistent-return
var returnRulesPlugin = function returnRulesPlugin(context) {
if (context === -2) {
var parsedRules = parsingRules;
parsingRules = [];
return parsedRules;
}
};
var parseRulesPlugin = _insertRulePlugin(function (rule) {
parsingRules.push(rule);
});
stylis.use([parseRulesPlugin, returnRulesPlugin]);
stylisSplitter.use([parseRulesPlugin, returnRulesPlugin]);
var stringifyRules = function stringifyRules(rules, selector, prefix) {
var flatCSS = rules.join('').replace(COMMENT_REGEX, ''); // replace JS comments
var cssStr = selector && prefix ? prefix + ' ' + selector + ' { ' + flatCSS + ' }' : flatCSS;
return stylis(prefix || !selector ? '' : selector, cssStr);
};
var splitByRules = function splitByRules(css) {
return stylisSplitter('', css);
};
//
/* eslint-disable camelcase, no-undef */
var getNonce = (function () {
return typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : null;
});
//
// Helper to call a given function, only once
var once = (function (cb) {
var called = false;
return function () {
if (!called) {
called = true;
cb();
}
};
});
//
/* These are helpers for the StyleTags to keep track of the injected
* rule names for each (component) ID that they're keeping track of.
* They're crucial for detecting whether a name has already been
* injected.
* (This excludes rehydrated names) */
/* adds a new ID:name pairing to a names dictionary */
var addNameForId = function addNameForId(names, id, name) {
if (name) {
// eslint-disable-next-line no-param-reassign
var namesForId = names[id] || (names[id] = Object.create(null));
namesForId[name] = true;
}
};
/* resets an ID entirely by overwriting it in the dictionary */
var resetIdNames = function resetIdNames(names, id) {
// eslint-disable-next-line no-param-reassign
names[id] = Object.create(null);
};
/* factory for a names dictionary checking the existance of an ID:name pairing */
var hasNameForId = function hasNameForId(names) {
return function (id, name) {
return names[id] !== undefined && names[id][name];
};
};
/* stringifies names for the html/element output */
var stringifyNames = function stringifyNames(names) {
var str = '';
// eslint-disable-next-line guard-for-in
for (var id in names) {
str += Object.keys(names[id]).join(' ') + ' ';
}
return str.trim();
};
/* clones the nested names dictionary */
var cloneNames = function cloneNames(names) {
var clone = Object.create(null);
// eslint-disable-next-line guard-for-in
for (var id in names) {
clone[id] = _extends({}, names[id]);
}
return clone;
};
//
/* These are helpers that deal with the insertRule (aka speedy) API
* They are used in the StyleTags and specifically the speedy tag
*/
/* retrieve a sheet for a given style tag */
var sheetForTag = function sheetForTag(tag) {
// $FlowFixMe
if (tag.sheet) return tag.sheet;
/* Firefox quirk requires us to step through all stylesheets to find one owned by the given tag */
var size = document.styleSheets.length;
for (var i = 0; i < size; i += 1) {
var sheet = document.styleSheets[i];
// $FlowFixMe
if (sheet.ownerNode === tag) return sheet;
}
/* we should always be able to find a tag */
throw new StyledComponentsError(10);
};
/* insert a rule safely and return whether it was actually injected */
var safeInsertRule = function safeInsertRule(sheet, cssRule, index) {
/* abort early if cssRule string is falsy */
if (!cssRule) return false;
var maxIndex = sheet.cssRules.length;
try {
/* use insertRule and cap passed index with maxIndex (no of cssRules) */
sheet.insertRule(cssRule, index <= maxIndex ? index : maxIndex);
} catch (err) {
/* any error indicates an invalid rule */
return false;
}
return true;
};
/* deletes `size` rules starting from `removalIndex` */
var deleteRules = function deleteRules(sheet, removalIndex, size) {
var lowerBound = removalIndex - size;
for (var i = removalIndex; i > lowerBound; i -= 1) {
sheet.deleteRule(i);
}
};
//
/* this marker separates component styles and is important for rehydration */
var makeTextMarker = function makeTextMarker(id) {
return '\n/* sc-component-id: ' + id + ' */\n';
};
/* add up all numbers in array up until and including the index */
var addUpUntilIndex = function addUpUntilIndex(sizes, index) {
var totalUpToIndex = 0;
for (var i = 0; i <= index; i += 1) {
totalUpToIndex += sizes[i];
}
return totalUpToIndex;
};
/* create a new style tag after lastEl */
var makeStyleTag = function makeStyleTag(target, tagEl, insertBefore) {
var el = document.createElement('style');
el.setAttribute(SC_ATTR, '');
el.setAttribute(SC_VERSION_ATTR, "4.0.0-beta.10");
var nonce = getNonce();
if (nonce) {
el.setAttribute('nonce', nonce);
}
/* Work around insertRule quirk in EdgeHTML */
el.appendChild(document.createTextNode(''));
if (target && !tagEl) {
/* Append to target when no previous element was passed */
target.appendChild(el);
} else {
if (!tagEl || !target || !tagEl.parentNode) {
throw new StyledComponentsError(6);
}
/* Insert new style tag after the previous one */
tagEl.parentNode.insertBefore(el, insertBefore ? tagEl : tagEl.nextSibling);
}
return el;
};
/* takes a css factory function and outputs an html styled tag factory */
var wrapAsHtmlTag = function wrapAsHtmlTag(css, names) {
return function (additionalAttrs) {
var nonce = getNonce();
var attrs = [nonce && 'nonce="' + nonce + '"', SC_ATTR + '="' + stringifyNames(names) + '"', SC_VERSION_ATTR + '="' + "4.0.0-beta.10" + '"', additionalAttrs];
var htmlAttr = attrs.filter(Boolean).join(' ');
return '<style ' + htmlAttr + '>' + css() + '</style>';
};
};
/* takes a css factory function and outputs an element factory */
var wrapAsElement = function wrapAsElement(css, names) {
return function () {
var _props;
var props = (_props = {}, _props[SC_ATTR] = stringifyNames(names), _props[SC_VERSION_ATTR] = "4.0.0-beta.10", _props);
var nonce = getNonce();
if (nonce) {
// $FlowFixMe
props.nonce = nonce;
}
// eslint-disable-next-line react/no-danger
return React__default.createElement('style', _extends({}, props, { dangerouslySetInnerHTML: { __html: css() } }));
};
};
var getIdsFromMarkersFactory = function getIdsFromMarkersFactory(markers) {
return function () {
return Object.keys(markers);
};
};
/* speedy tags utilise insertRule */
var makeSpeedyTag = function makeSpeedyTag(el, getImportRuleTag) {
var names = Object.create(null);
var markers = Object.create(null);
var sizes = [];
var extractImport = getImportRuleTag !== undefined;
/* indicates whther getImportRuleTag was called */
var usedImportRuleTag = false;
var insertMarker = function insertMarker(id) {
var prev = markers[id];
if (prev !== undefined) {
return prev;
}
markers[id] = sizes.length;
sizes.push(0);
resetIdNames(names, id);
return markers[id];
};
var insertRules = function insertRules(id, cssRules, name) {
var marker = insertMarker(id);
var sheet = sheetForTag(el);
var insertIndex = addUpUntilIndex(sizes, marker);
var injectedRules = 0;
var importRules = [];
var cssRulesSize = cssRules.length;
for (var i = 0; i < cssRulesSize; i += 1) {
var cssRule = cssRules[i];
var mayHaveImport = extractImport; /* @import rules are reordered to appear first */
if (mayHaveImport && cssRule.indexOf('@import') !== -1) {
importRules.push(cssRule);
} else if (safeInsertRule(sheet, cssRule, insertIndex + injectedRules)) {
mayHaveImport = false;
injectedRules += 1;
}
}
if (extractImport && importRules.length > 0) {
usedImportRuleTag = true;
// $FlowFixMe
getImportRuleTag().insertRules(id + '-import', importRules);
}
sizes[marker] += injectedRules; /* add up no of injected rules */
addNameForId(names, id, name);
};
var removeRules = function removeRules(id) {
var marker = markers[id];
if (marker === undefined) return;
var size = sizes[marker];
var sheet = sheetForTag(el);
var removalIndex = addUpUntilIndex(sizes, marker) - 1;
deleteRules(sheet, removalIndex, size);
sizes[marker] = 0;
resetIdNames(names, id);
if (extractImport && usedImportRuleTag) {
// $FlowFixMe
getImportRuleTag().removeRules(id + '-import');
}
};
var css = function css() {
var _sheetForTag = sheetForTag(el),
cssRules = _sheetForTag.cssRules;
var str = '';
// eslint-disable-next-line guard-for-in
for (var id in markers) {
str += makeTextMarker(id);
var marker = markers[id];
var end = addUpUntilIndex(sizes, marker);
var size = sizes[marker];
for (var i = end - size; i < end; i += 1) {
var rule = cssRules[i];
if (rule !== undefined) {
str += rule.cssText;
}
}
}
return str;
};
return {
clone: function clone() {
throw new StyledComponentsError(5);
},
css: css,
getIds: getIdsFromMarkersFactory(markers),
hasNameForId: hasNameForId(names),
insertMarker: insertMarker,
insertRules: insertRules,
removeRules: removeRules,
sealed: false,
styleTag: el,
toElement: wrapAsElement(css, names),
toHTML: wrapAsHtmlTag(css, names)
};
};
var makeTextNode = function makeTextNode(id) {
return document.createTextNode(makeTextMarker(id));
};
var makeBrowserTag = function makeBrowserTag(el, getImportRuleTag) {
var names = Object.create(null);
var markers = Object.create(null);
var extractImport = getImportRuleTag !== undefined;
/* indicates whther getImportRuleTag was called */
var usedImportRuleTag = false;
var insertMarker = function insertMarker(id) {
var prev = markers[id];
if (prev !== undefined) {
return prev;
}
markers[id] = makeTextNode(id);
el.appendChild(markers[id]);
names[id] = Object.create(null);
return markers[id];
};
var insertRules = function insertRules(id, cssRules, name) {
var marker = insertMarker(id);
var importRules = [];
var cssRulesSize = cssRules.length;
for (var i = 0; i < cssRulesSize; i += 1) {
var rule = cssRules[i];
var mayHaveImport = extractImport;
if (mayHaveImport && rule.indexOf('@import') !== -1) {
importRules.push(rule);
} else {
mayHaveImport = false;
var separator = i === cssRulesSize - 1 ? '' : ' ';
marker.appendData('' + rule + separator);
}
}
addNameForId(names, id, name);
if (extractImport && importRules.length > 0) {
usedImportRuleTag = true;
// $FlowFixMe
getImportRuleTag().insertRules(id + '-import', importRules);
}
};
var removeRules = function removeRules(id) {
var marker = markers[id];
if (marker === undefined) return;
/* create new empty text node and replace the current one */
var newMarker = makeTextNode(id);
el.replaceChild(newMarker, marker);
markers[id] = newMarker;
resetIdNames(names, id);
if (extractImport && usedImportRuleTag) {
// $FlowFixMe
getImportRuleTag().removeRules(id + '-import');
}
};
var css = function css() {
var str = '';
// eslint-disable-next-line guard-for-in
for (var id in markers) {
str += markers[id].data;
}
return str;
};
return {
clone: function clone() {
throw new StyledComponentsError(5);
},
css: css,
getIds: getIdsFromMarkersFactory(markers),
hasNameForId: hasNameForId(names),
insertMarker: insertMarker,
insertRules: insertRules,
removeRules: removeRules,
sealed: false,
styleTag: el,
toElement: wrapAsElement(css, names),
toHTML: wrapAsHtmlTag(css, names)
};
};
var makeServerTag = function makeServerTag(namesArg, markersArg) {
var names = namesArg === undefined ? Object.create(null) : namesArg;
var markers = markersArg === undefined ? Object.create(null) : markersArg;
var insertMarker = function insertMarker(id) {
var prev = markers[id];
if (prev !== undefined) {
return prev;
}
return markers[id] = [''];
};
var insertRules = function insertRules(id, cssRules, name) {
var marker = insertMarker(id);
marker[0] += cssRules.join(' ');
addNameForId(names, id, name);
};
var removeRules = function removeRules(id) {
var marker = markers[id];
if (marker === undefined) return;
marker[0] = '';
resetIdNames(names, id);
};
var css = function css() {
var str = '';
// eslint-disable-next-line guard-for-in
for (var id in markers) {
var cssForId = markers[id][0];
if (cssForId) {
str += makeTextMarker(id) + cssForId;
}
}
return str;
};
var clone = function clone() {
var namesClone = cloneNames(names);
var markersClone = Object.create(null);
// eslint-disable-next-line guard-for-in
for (var id in markers) {
markersClone[id] = [markers[id][0]];
}
return makeServerTag(namesClone, markersClone);
};
var tag = {
clone: clone,
css: css,
getIds: getIdsFromMarkersFactory(markers),
hasNameForId: hasNameForId(names),
insertMarker: insertMarker,
insertRules: insertRules,
removeRules: removeRules,
sealed: false,
styleTag: null,
toElement: wrapAsElement(css, names),
toHTML: wrapAsHtmlTag(css, names)
};
return tag;
};
var makeTag = function makeTag(target, tagEl, forceServer, insertBefore, getImportRuleTag) {
if (IS_BROWSER && !forceServer) {
var el = makeStyleTag(target, tagEl, insertBefore);
if (DISABLE_SPEEDY) {
return makeBrowserTag(el, getImportRuleTag);
} else {
return makeSpeedyTag(el, getImportRuleTag);
}
}
return makeServerTag();
};
/* wraps a given tag so that rehydration is performed once when necessary */
var makeRehydrationTag = function makeRehydrationTag(tag, els, extracted, immediateRehydration) {
/* rehydration function that adds all rules to the new tag */
var rehydrate = once(function () {
/* add all extracted components to the new tag */
for (var i = 0, len = extracted.length; i < len; i += 1) {
var _extracted$i = extracted[i],
componentId = _extracted$i.componentId,
cssFromDOM = _extracted$i.cssFromDOM;
var cssRules = splitByRules(cssFromDOM);
tag.insertRules(componentId, cssRules);
}
/* remove old HTMLStyleElements, since they have been rehydrated */
for (var _i = 0, _len = els.length; _i < _len; _i += 1) {
var el = els[_i];
if (el.parentNode) {
el.parentNode.removeChild(el);
}
}
});
if (immediateRehydration) rehydrate();
return _extends({}, tag, {
/* add rehydration hook to methods */
insertMarker: function insertMarker(id) {
rehydrate();
return tag.insertMarker(id);
},
insertRules: function insertRules(id, cssRules, name) {
rehydrate();
return tag.insertRules(id, cssRules, name);
},
removeRules: function removeRules(id) {
rehydrate();
return tag.removeRules(id);
}
});
};
//
var SPLIT_REGEX = /\s+/;
/* determine the maximum number of components before tags are sharded */
var MAX_SIZE = void 0;
if (IS_BROWSER) {
/* in speedy mode we can keep a lot more rules in a sheet before a slowdown can be expected */
MAX_SIZE = DISABLE_SPEEDY ? 40 : 1000;
} else {
/* for servers we do not need to shard at all */
MAX_SIZE = -1;
}
var sheetRunningId = 0;
var master = void 0;
var StyleSheet = function () {
/* a map from ids to tags */
/* deferred rules for a given id */
/* this is used for not reinjecting rules via hasNameForId() */
/* when rules for an id are removed using remove() we have to ignore rehydratedNames for it */
/* a list of tags belonging to this StyleSheet */
/* a tag for import rules */
/* current capacity until a new tag must be created */
/* children (aka clones) of this StyleSheet inheriting all and future injections */
function StyleSheet() {
var _this = this;
var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : IS_BROWSER ? document.head : null;
var forceServer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
classCallCheck(this, StyleSheet);
this.getImportRuleTag = function () {
var importRuleTag = _this.importRuleTag;
if (importRuleTag !== undefined) {
return importRuleTag;
}
var firstTag = _this.tags[0];
var insertBefore = true;
return _this.importRuleTag = makeTag(_this.target, firstTag ? firstTag.styleTag : null, _this.forceServer, insertBefore);
};
sheetRunningId += 1;
this.id = sheetRunningId;
this.forceServer = forceServer;
this.target = forceServer ? null : target;
this.tagMap = {};
this.deferred = {};
this.rehydratedNames = {};
this.ignoreRehydratedNames = {};
this.tags = [];
this.capacity = 1;
this.clones = [];
}
/* rehydrate all SSR'd style tags */
StyleSheet.prototype.rehydrate = function rehydrate() {
if (!IS_BROWSER || this.forceServer) {
return this;
}
var els = [];
var extracted = [];
var isStreamed = false;
/* retrieve all of our SSR style elements from the DOM */
var nodes = document.querySelectorAll('style[' + SC_ATTR + '][' + SC_VERSION_ATTR + '="' + "4.0.0-beta.10" + '"]');
var nodesSize = nodes.length;
/* abort rehydration if no previous style tags were found */
if (nodesSize === 0) {
return this;
}
for (var i = 0; i < nodesSize; i += 1) {
// $FlowFixMe: We can trust that all elements in this query are style elements
var el = nodes[i];
/* check if style tag is a streamed tag */
if (!isStreamed) isStreamed = !!el.getAttribute(SC_STREAM_ATTR);
/* retrieve all component names */
var elNames = (el.getAttribute(SC_ATTR) || '').trim().split(SPLIT_REGEX);
var elNamesSize = elNames.length;
for (var j = 0; j < elNamesSize; j += 1) {
var name = elNames[j];
/* add rehydrated name to sheet to avoid readding styles */
this.rehydratedNames[name] = true;
}
/* extract all components and their CSS */
extracted.push.apply(extracted, extractComps(el.textContent));
/* store original HTMLStyleElement */
els.push(el);
}
/* abort rehydration if nothing was extracted */
var extractedSize = extracted.length;
if (extractedSize === 0) {
return this;
}
/* create a tag to be used for rehydration */
var tag = this.makeTag(null);
var rehydrationTag = makeRehydrationTag(tag, els, extracted, isStreamed);
/* reset capacity and adjust MAX_SIZE by the initial size of the rehydration */
this.capacity = Math.max(1, MAX_SIZE - extractedSize);
this.tags.push(rehydrationTag);
/* retrieve all component ids */
for (var _j = 0; _j < extractedSize; _j += 1) {
this.tagMap[extracted[_j].componentId] = rehydrationTag;
}
return this;
};
/* retrieve a "master" instance of StyleSheet which is typically used when no other is available
* The master StyleSheet is targeted by createGlobalStyle, keyframes, and components outside of any
* StyleSheetManager's context */
/* reset the internal "master" instance */
StyleSheet.reset = function reset() {
var forceServer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
master = new StyleSheet(undefined, forceServer).rehydrate();
};
/* adds "children" to the StyleSheet that inherit all of the parents' rules
* while their own rules do not affect the parent */
StyleSheet.prototype.clone = function clone() {
var sheet = new StyleSheet(this.target, this.forceServer);
/* add to clone array */
this.clones.push(sheet);
/* clone all tags */
sheet.tags = this.tags.map(function (tag) {
var ids = tag.getIds();
var newTag = tag.clone();
/* reconstruct tagMap */
for (var i = 0; i < ids.length; i += 1) {
sheet.tagMap[ids[i]] = newTag;
}
return newTag;
});
/* clone other maps */
sheet.rehydratedNames = _extends({}, this.rehydratedNames);
sheet.deferred = _extends({}, this.deferred);
return sheet;
};
/* force StyleSheet to create a new tag on the next injection */
StyleSheet.prototype.sealAllTags = function sealAllTags() {
this.capacity = 1;
this.tags.forEach(function (tag) {
// eslint-disable-next-line no-param-reassign
tag.sealed = true;
});
};
StyleSheet.prototype.makeTag = function makeTag$$1(tag) {
var lastEl = tag ? tag.styleTag : null;
var insertBefore = false;
return makeTag(this.target, lastEl, this.forceServer, insertBefore, this.getImportRuleTag);
};
/* get a tag for a given componentId, assign the componentId to one, or shard */
StyleSheet.prototype.getTagForId = function getTagForId(id) {
/* simply return a tag, when the componentId was already assigned one */
var prev = this.tagMap[id];
if (prev !== undefined && !prev.sealed) {
return prev;
}
var tag = this.tags[this.tags.length - 1];
/* shard (create a new tag) if the tag is exhausted (See MAX_SIZE) */
this.capacity -= 1;
if (this.capacity === 0) {
this.capacity = MAX_SIZE;
tag = this.makeTag(tag);
this.tags.push(tag);
}
return this.tagMap[id] = tag;
};
/* mainly for createGlobalStyle to check for its id */
StyleSheet.prototype.hasId = function hasId(id) {
return this.tagMap[id] !== undefined;
};
/* caching layer checking id+name to already have a corresponding tag and injected rules */
StyleSheet.prototype.hasNameForId = function hasNameForId(id, name) {
/* exception for rehydrated names which are checked separately */
if (this.ignoreRehydratedNames[id] === undefined && this.rehydratedNames[name]) {
return true;
}
var tag = this.tagMap[id];
return tag !== undefined && tag.hasNameForId(id, name);
};
/* registers a componentId and registers it on its tag */
StyleSheet.prototype.deferredInject = function deferredInject(id, cssRules) {
/* don't inject when the id is already registered */
if (this.tagMap[id] !== undefined) return;
var clones = this.clones;
for (var i = 0; i < clones.length; i += 1) {
clones[i].deferredInject(id, cssRules);
}
this.getTagForId(id).insertMarker(id);
this.deferred[id] = cssRules;
};
/* injects rules for a given id with a name that will need to be cached */
StyleSheet.prototype.inject = function inject(id, cssRules, name) {
var clones = this.clones;
for (var i = 0; i < clones.length; i += 1) {
clones[i].inject(id, cssRules, name);
}
var tag = this.getTagForId(id);
/* add deferred rules for component */
if (this.deferred[id] !== undefined) {
// Combine passed cssRules with previously deferred CSS rules
// NOTE: We cannot mutate the deferred array itself as all clones
// do the same (see clones[i].inject)
var rules = this.deferred[id].concat(cssRules);
tag.insertRules(id, rules, name);
this.deferred[id] = undefined;
} else {
tag.insertRules(id, cssRules, name);
}
};
/* removes all rules for a given id, which doesn't remove its marker but resets it */
StyleSheet.prototype.remove = function remove(id) {
var tag = this.tagMap[id];
if (tag === undefined) return;
var clones = this.clones;
for (var i = 0; i < clones.length; i += 1) {
clones[i].remove(id);
}
/* remove all rules from the tag */
tag.removeRules(id);
/* ignore possible rehydrated names */
this.ignoreRehydratedNames[id] = true;
/* delete possible deferred rules */
this.deferred[id] = undefined;
};
StyleSheet.prototype.toHTML = function toHTML() {
return this.tags.map(function (tag) {
return tag.toHTML();
}).join('');
};
StyleSheet.prototype.toReactElements = function toReactElements() {
var id = this.id;
return this.tags.map(function (tag, i) {
var key = 'sc-' + id + '-' + i;
return React.cloneElement(tag.toElement(), { key: key });
});
};
createClass(StyleSheet, null, [{
key: 'master',
get: function get$$1() {
return master || (master = new StyleSheet().rehydrate());
}
/* NOTE: This is just for backwards-compatibility with jest-styled-components */
}, {
key: 'instance',
get: function get$$1() {
return StyleSheet.master;
}
}]);
return StyleSheet;
}();
//
var Keyframes = function () {
function Keyframes(name, rules) {
var _this = this;
classCallCheck(this, Keyframes);
this.inject = function (styleSheet) {
if (!styleSheet.hasNameForId(_this.id, _this.name)) {
styleSheet.inject(_this.id, _this.rules, _this.name);
}
};
this.name = name;
this.rules = rules;
this.id = 'sc-keyframes-' + name;
}
Keyframes.prototype.getName = function getName() {
return this.name;
};
return Keyframes;
}();
//
/**
* inlined version of
* https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/hyphenateStyleName.js
*/
var uppercasePattern = /([A-Z])/g;
var msPattern = /^ms-/;
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*
* @param {string} string
* @return {string}
*/
function hyphenateStyleName(string) {
return string.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
}
//
var objToCss = function objToCss(obj, prevKey) {
var css = Object.keys(obj).filter(function (key) {
var chunk = obj[key];
return chunk !== undefined && chunk !== null && chunk !== false && chunk !== '';
}).map(function (key) {
if (isPlainObject(obj[key])) return objToCss(obj[key], key);
return hyphenateStyleName(key) + ': ' + obj[key] + ';';
}).join(' ');
return prevKey ? prevKey + ' {\n ' + css + '\n}' : css;
};
/**
* It's falsish not falsy because 0 is allowed.
*/
var isFalsish = function isFalsish(chunk) {
return chunk === undefined || chunk === null || chunk === false || chunk === '';
};
function flatten(chunk, executionContext, styleSheet) {
if (Array.isArray(chunk)) {
var ruleSet = [];
for (var i = 0, len = chunk.length, result; i < len; i += 1) {
result = flatten(chunk[i], executionContext, styleSheet);
if (result === null) continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result);
}
return ruleSet;
}
if (isFalsish(chunk)) {
return null;
}
/* Handle other components */
if (isStyledComponent(chunk)) {
return '.' + chunk.styledComponentId;
}
/* Either execute or defer the function */
if (isFunction(chunk)) {
if (executionContext) {
return flatten(chunk(executionContext), executionContext, styleSheet);
} else return chunk;
}
if (chunk instanceof Keyframes) {
if (styleSheet) {
chunk.inject(styleSheet);
return chunk.getName();
} else return chunk;
}
/* Handle objects */
return isPlainObject(chunk) ? objToCss(chunk) : chunk.toString();
}
//
function css(styles) {
for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
interpolations[_key - 1] = arguments[_key];
}
if (isFunction(styles) || isPlainObject(styles)) {
// $FlowFixMe
return flatten(interleave(EMPTY_ARRAY, [styles].concat(interpolations)));
}
// $FlowFixMe
return flatten(interleave(styles, interpolations));
}
//
function constructWithOptions(componentConstructor, tag) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EMPTY_OBJECT;
if (!reactIs.isValidElementType(tag)) {
throw new StyledComponentsError(1, String(tag));
}
/* This is callable directly as a template function */
// $FlowFixMe: Not typed to avoid destructuring arguments
var templateFunction = function templateFunction() {
return componentConstructor(tag, options, css.apply(undefined, arguments));
};
/* If config methods are called, wrap up a new template function and merge options */
templateFunction.withConfig = function (config) {
return constructWithOptions(componentConstructor, tag, _extends({}, options, config));
};
templateFunction.attrs = function (attrs) {
return constructWithOptions(componentConstructor, tag, _extends({}, options, {
attrs: _extends({}, options.attrs || EMPTY_OBJECT, attrs)
}));
};
return templateFunction;
}
//
// Source: https://github.com/garycourt/murmurhash-js/blob/master/murmurhash2_gc.js
function murmurhash(c) {
for (var e = c.length | 0, a = e | 0, d = 0, b; e >= 4;) {
b = c.charCodeAt(d) & 255 | (c.charCodeAt(++d) & 255) << 8 | (c.charCodeAt(++d) & 255) << 16 | (c.charCodeAt(++d) & 255) << 24, b = 1540483477 * (b & 65535) + ((1540483477 * (b >>> 16) & 65535) << 16), b ^= b >>> 24, b = 1540483477 * (b & 65535) + ((1540483477 * (b >>> 16) & 65535) << 16), a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16) ^ b, e -= 4, ++d;
}
switch (e) {
case 3:
a ^= (c.charCodeAt(d + 2) & 255) << 16;
case 2:
a ^= (c.charCodeAt(d + 1) & 255) << 8;
case 1:
a ^= c.charCodeAt(d) & 255, a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16);
}
a ^= a >>> 13;
a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16);
return (a ^ a >>> 15) >>> 0;
}
//
/* eslint-disable no-bitwise */
/* This is the "capacity" of our alphabet i.e. 2x26 for all letters plus their capitalised
* counterparts */
var charsLength = 52;
/* start at 75 for 'a' until 'z' (25) and then start at 65 for capitalised letters */
var getAlphabeticChar = function getAlphabeticChar(code) {
return String.fromCharCode(code + (code > 25 ? 39 : 97));
};
/* input a number, usually a hash and convert it to base-52 */
function generateAlphabeticName(code) {
var name = '';
var x = void 0;
/* get a char and divide by alphabet-length */
for (x = code; x > charsLength; x = Math.floor(x / charsLength)) {
name = getAlphabeticChar(x % charsLength) + name;
}
return getAlphabeticChar(x % charsLength) + name;
}
//
function isStaticRules(rules, attrs) {
for (var i = 0; i < rules.length; i += 1) {
var rule = rules[i];
// recursive case
if (Array.isArray(rule) && !isStaticRules(rule)) {
return false;
} else if (isFunction(rule) && !isStyledComponent(rule)) {
// functions are allowed to be static if they're just being
// used to get the classname of a nested styled component
return false;
}
}
if (attrs !== undefined) {
// eslint-disable-next-line guard-for-in, no-restricted-syntax
for (var key in attrs) {
var value = attrs[key];
if (isFunction(value)) {
return false;
}
}
}
return true;
}
//
//
var isHMREnabled = process.env.NODE_ENV !== 'production' && typeof module !== 'undefined' && module.hot;
/* combines hashStr (murmurhash) and nameGenerator for convenience */
var hasher = function hasher(str) {
return generateAlphabeticName(murmurhash(str));
};
/*
ComponentStyle is all the CSS-specific stuff, not
the React-specific stuff.
*/
var ComponentStyle = function () {
function ComponentStyle(rules, attrs, componentId) {
classCallCheck(this, ComponentStyle);
this.rules = rules;
this.isStatic = !isHMREnabled && isStaticRules(rules, attrs);
this.componentId = componentId;
if (!StyleSheet.master.hasId(componentId)) {
var placeholder = process.env.NODE_ENV !== 'production' ? ['.' + componentId + ' {}'] : [];
StyleSheet.master.deferredInject(componentId, placeholder);
}
}
/*
* Flattens a rule set into valid CSS
* Hashes it, wraps the whole chunk in a .hash1234 {}
* Returns the hash to be injected on render()
* */
ComponentStyle.prototype.generateAndInjectStyles = function generateAndInjectStyles(executionContext, styleSheet) {
var isStatic = this.isStatic,
componentId = this.componentId,
lastClassName = this.lastClassName;
if (IS_BROWSER && isStatic && lastClassName !== undefined && styleSheet.hasNameForId(componentId, lastClassName)) {
return lastClassName;
}
var flatCSS = flatten(this.rules, executionContext, styleSheet);
var name = hasher(this.componentId + flatCSS.join(''));
if (!styleSheet.hasNameForId(componentId, name)) {
styleSheet.inject(this.componentId, stringifyRules(flatCSS, '.' + name), name);
}
this.lastClassName = name;
return name;
};
ComponentStyle.generateName = function generateName(str) {
return hasher(str);
};
return ComponentStyle;
}();
//
var LIMIT = 200;
var createWarnTooManyClasses = (function (displayName) {
var generatedClasses = {};
var warningSeen = false;
return function (className) {
if (!warningSeen) {
generatedClasses[className] = true;
if (Object.keys(generatedClasses).length >= LIMIT) {
// Unable to find latestRule in test environment.
/* eslint-disable no-console, prefer-template */
console.warn('Over ' + LIMIT + ' classes were generated for component ' + displayName + '. \n' + 'Consider using the attrs method, together with a style object for frequently changed styles.\n' + 'Example:\n' + ' const Component = styled.div.attrs({\n' + ' style: ({ background }) => ({\n' + ' background,\n' + ' }),\n' + ' })`width: 100%;`\n\n' + ' <Component />');
warningSeen = true;
generatedClasses = {};
}
}
};
});
//
var determineTheme = (function (props, fallbackTheme) {
var defaultProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EMPTY_OBJECT;
// Props should take precedence over ThemeProvider, which should take precedence over
// defaultProps, but React automatically puts defaultProps on props.
/* eslint-disable react/prop-types, flowtype-errors/show-errors */
var isDefaultTheme = defaultProps ? props.theme === defaultProps.theme : false;
var theme = props.theme && !isDefaultTheme ? props.theme : fallbackTheme || defaultProps.theme;
/* eslint-enable */
return theme;
});
//
var escapeRegex = /[[\].#*$><+~=|^:(),"'`-]+/g;
var dashesAtEnds = /(^-|-$)/g;
/**
* TODO: Explore using CSS.escape when it becomes more available
* in evergreen browsers.
*/
function escape(str) {
return str
// Replace all possible CSS selectors
.replace(escapeRegex, '-')
// Remove extraneous hyphens at the start and end
.replace(dashesAtEnds, '');
}
//
function getComponentName(target) {
return target.displayName || target.name || 'Component';
}
//
function isTag(target) /* : %checks */{
return typeof target === 'string';
}
//
function generateDisplayName(target) {
return isTag(target) ? 'styled.' + target : 'Styled(' + getComponentName(target) + ')';
}
var _TYPE_STATICS;
var REACT_STATICS = {
childContextTypes: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDerivedStateFromProps: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
callee: true,
arguments: true,
arity: true
};
var TYPE_STATICS = (_TYPE_STATICS = {}, _TYPE_STATICS[reactIs.ForwardRef] = {
$$typeof: true,
render: true
}, _TYPE_STATICS);
var defineProperty$1 = Object.defineProperty,
getOwnPropertyNames = Object.getOwnPropertyNames,
_Object$getOwnPropert = Object.getOwnPropertySymbols,
getOwnPropertySymbols = _Object$getOwnPropert === undefined ? function () {
return [];
} : _Object$getOwnPropert,
getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor,
getPrototypeOf = Object.getPrototypeOf,
objectPrototype = Object.prototype;
var arrayPrototype = Array.prototype;
function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
if (typeof sourceComponent !== 'string') {
// don't hoist over string (html) components
var inheritedComponent = getPrototypeOf(sourceComponent);
if (inheritedComponent && inheritedComponent !== objectPrototype) {
hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
}
var keys = arrayPrototype.concat(getOwnPropertyNames(sourceComponent),
// $FlowFixMe
getOwnPropertySymbols(sourceComponent));
var targetStatics = TYPE_STATICS[targetComponent.$$typeof] || REACT_STATICS;
var sourceStatics = TYPE_STATICS[sourceComponent.$$typeof] || REACT_STATICS;
var i = keys.length;
var descriptor = void 0;
var key = void 0;
// eslint-disable-next-line no-plusplus
while (i--) {
key = keys[i];
if (
// $FlowFixMe
!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) &&
// $FlowFixMe
!(targetStatics && targetStatics[key])) {
descriptor = getOwnPropertyDescriptor(sourceComponent, key);
if (descriptor) {
try {
// Avoid failures from read-only properties
defineProperty$1(targetComponent, key, descriptor);
} catch (e) {
/* fail silently */
}
}
}
}
return targetComponent;
}
return targetComponent;
}
//
function isDerivedReactComponent(fn) {
return !!(fn && fn.prototype && fn.prototype.isReactComponent);
}
//
var ThemeContext = React.createContext();
var ThemeConsumer = ThemeContext.Consumer;
/**
* Provide a theme to an entire react component tree via context
*/
var ThemeProvider = function (_Component) {
inherits(ThemeProvider, _Component);
function ThemeProvider(props) {
classCallCheck(this, ThemeProvider);
var _this = possibleConstructorReturn(this, _Component.call(this, props));
_this.getContext = memoize(_this.getContext.bind(_this));
_this.renderInner = _this.renderInner.bind(_this);
return _this;
}
ThemeProvider.prototype.render = function render() {
if (!this.props.children) return null;
return React__default.createElement(
ThemeContext.Consumer,
null,
this.renderInner
);
};
ThemeProvider.prototype.renderInner = function renderInner(outerTheme) {
var context = this.getContext(this.props.theme, outerTheme);
return React__default.createElement(
ThemeContext.Provider,
{ value: context },
React__default.Children.only(this.props.children)
);
};
/**
* Get the theme from the props, supporting both (outerTheme) => {}
* as well as object notation
*/
ThemeProvider.prototype.getTheme = function getTheme(theme, outerTheme) {
if (isFunction(theme)) {
var mergedTheme = theme(outerTheme);
if (process.env.NODE_ENV !== 'production' && (mergedTheme === null || Array.isArray(mergedTheme) || (typeof mergedTheme === 'undefined' ? 'undefined' : _typeof(mergedTheme)) !== 'object')) {
throw new StyledComponentsError(7);
}
return mergedTheme;
}
if (theme === null || Array.isArray(theme) || (typeof theme === 'undefined' ? 'undefined' : _typeof(theme)) !== 'object') {
throw new StyledComponentsError(8);
}
return _extends({}, outerTheme, theme);
};
ThemeProvider.prototype.getContext = function getContext(theme, outerTheme) {
return this.getTheme(theme, outerTheme);
};
return ThemeProvider;
}(React.Component);
//
var ServerStyleSheet = function () {
function ServerStyleSheet() {
classCallCheck(this, ServerStyleSheet);
/* The master sheet might be reset, so keep a reference here */
this.masterSheet = StyleSheet.master;
this.instance = this.masterSheet.clone();
this.sealed = false;
}
/**
* Mark the ServerStyleSheet as being fully emitted and manually GC it from the
* StyleSheet singleton.
*/
ServerStyleSheet.prototype.seal = function seal() {
if (!this.sealed) {
/* Remove sealed StyleSheets from the master sheet */
var index = this.masterSheet.clones.indexOf(this.instance);
this.masterSheet.clones.splice(index, 1);
this.sealed = true;
}
};
ServerStyleSheet.prototype.collectStyles = function collectStyles(children) {
if (this.sealed) {
throw new StyledComponentsError(2);
}
return React__default.createElement(
StyleSheetManager,
{ sheet: this.instance },
children
);
};
ServerStyleSheet.prototype.getStyleTags = function getStyleTags() {
this.seal();
return this.instance.toHTML();
};
ServerStyleSheet.prototype.getStyleElement = function getStyleElement() {
this.seal();
return this.instance.toReactElements();
};
ServerStyleSheet.prototype.interleaveWithNodeStream = function interleaveWithNodeStream(readableStream) {
var _this = this;
{
throw new StyledComponentsError(3);
}
/* the tag index keeps track of which tags have already been emitted */
var instance = this.instance;
var instanceTagIndex = 0;
var streamAttr = SC_STREAM_ATTR + '="true"';
var transformer = new stream.Transform({
transform: function appendStyleChunks(chunk, /* encoding */_, callback) {
var tags = instance.tags;
var html = '';
/* retrieve html for each new style tag */
for (; instanceTagIndex < tags.length; instanceTagIndex += 1) {
var tag = tags[instanceTagIndex];
html += tag.toHTML(streamAttr);
}
/* force our StyleSheets to emit entirely new tags */
instance.sealAllTags();
/* prepend style html to chunk */
this.push(html + chunk);
callback();
}
});
readableStream.on('end', function () {
return _this.seal();
});
readableStream.on('error', function (err) {
_this.seal();
// forward the error to the transform stream
transformer.emit('error', err);
});
return readableStream.pipe(transformer);
};
return ServerStyleSheet;
}();
//
var StyleSheetContext = React.createContext();
var StyleSheetConsumer = StyleSheetContext.Consumer;
var StyleSheetManager = function (_Component) {
inherits(StyleSheetManager, _Component);
function StyleSheetManager(props) {
classCallCheck(this, StyleSheetManager);
var _this = possibleConstructorReturn(this, _Component.call(this, props));
_this.getContext = memoize(_this.getContext);
return _this;
}
StyleSheetManager.prototype.getContext = function getContext(sheet, target) {
if (sheet) {
return sheet;
} else if (target) {
return new StyleSheet(target);
} else {
throw new StyledComponentsError(4);
}
};
StyleSheetManager.prototype.render = function render() {
var _props = this.props,
children = _props.children,
sheet = _props.sheet,
target = _props.target;
var context = this.getContext(sheet, target);
return React__default.createElement(
StyleSheetContext.Provider,
{ value: context },
React__default.Children.only(children)
);
};
return StyleSheetManager;
}(React.Component);
process.env.NODE_ENV !== "production" ? StyleSheetManager.propTypes = {
sheet: PropTypes.oneOfType([PropTypes.instanceOf(StyleSheet), PropTypes.instanceOf(ServerStyleSheet)]),
target: PropTypes.shape({
appendChild: PropTypes.func.isRequired
})
} : void 0;
//
var identifiers = {};
/* We depend on components having unique IDs */
function generateId(_ComponentStyle, _displayName, parentComponentId) {
var displayName = typeof _displayName !== 'string' ? 'sc' : escape(_displayName);
/**
* This ensures uniqueness if two components happen to share
* the same displayName.
*/
var nr = (identifiers[displayName] || 0) + 1;
identifiers[displayName] = nr;
var componentId = displayName + '-' + _ComponentStyle.generateName(displayName + nr);
return parentComponentId ? parentComponentId + '-' + componentId : componentId;
}
var warnInnerRef = once(function () {
return (
// eslint-disable-next-line no-console
console.warn('The "innerRef" API has been removed in styled-components v4 in favor of React 16 ref forwarding, use "ref" instead like a typical component.')
);
});
// $FlowFixMe
var StyledComponent = function (_Component) {
inherits(StyledComponent, _Component);
function StyledComponent() {
classCallCheck(this, StyledComponent);
var _this = possibleConstructorReturn(this, _Component.call(this));
_this.attrs = {};
_this.renderOuter = _this.renderOuter.bind(_this);
_this.renderInner = _this.renderInner.bind(_this);
return _this;
}
StyledComponent.prototype.render = function render() {
return React__default.createElement(
StyleSheetConsumer,
null,
this.renderOuter
);
};
StyledComponent.prototype.renderOuter = function renderOuter(styleSheet) {
this.styleSheet = styleSheet;
return React__default.createElement(
ThemeConsumer,
null,
this.renderInner
);
};
StyledComponent.prototype.renderInner = function renderInner(theme) {
var _props$forwardedClass = this.props.forwardedClass,
componentStyle = _props$forwardedClass.componentStyle,
defaultProps = _props$forwardedClass.defaultProps,
styledComponentId = _props$forwardedClass.styledComponentId,
target = _props$forwardedClass.target;
var generatedClassName = void 0;
if (componentStyle.isStatic) {
generatedClassName = this.generateAndInjectStyles(EMPTY_OBJECT, this.props, this.styleSheet);
} else if (theme !== undefined) {
generatedClassName = this.generateAndInjectStyles(determineTheme(this.props, theme, defaultProps), this.props, this.styleSheet);
} else {
generatedClassName = this.generateAndInjectStyles(this.props.theme || EMPTY_OBJECT, this.props, this.styleSheet);
}
var elementToBeCreated = this.props.as || this.attrs.as || target;
var isTargetTag = isTag(elementToBeCreated);
var propsForElement = _extends({}, this.attrs);
var key = void 0;
// eslint-disable-next-line guard-for-in
for (key in this.props) {
if (process.env.NODE_ENV !== 'production' && key === 'innerRef') {
warnInnerRef();
}
if (key === 'forwardedClass' || key === 'as') continue;else if (key === 'forwardedRef') propsForElement.ref = this.props[key];else if (!isTargetTag || validAttr(key)) {
// Don't pass through non HTML tags through to HTML elements
propsForElement[key] = key === 'style' && key in this.attrs ? _extends({}, this.attrs[key], this.props[key]) : this.props[key];
}
}
propsForElement.className = [this.props.className, styledComponentId, this.attrs.className, generatedClassName].filter(Boolean).join(' ');
return React.createElement(elementToBeCreated, propsForElement);
};
StyledComponent.prototype.buildExecutionContext = function buildExecutionContext(theme, props, attrs) {
var context = _extends({}, props, { theme: theme });
if (attrs === undefined) return context;
this.attrs = {};
var attr = void 0;
var key = void 0;
/* eslint-disable guard-for-in */
for (key in attrs) {
attr = attrs[key];
this.attrs[key] = isFunction(attr) && !isDerivedReactComponent(attr) && !isStyledComponent(attr) ? attr(context) : attr;
}
/* eslint-enable */
return _extends({}, context, this.attrs);
};
StyledComponent.prototype.generateAndInjectStyles = function generateAndInjectStyles(theme, props) {
var styleSheet = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : StyleSheet.master;
var _props$forwardedClass2 = props.forwardedClass,
attrs = _props$forwardedClass2.attrs,
componentStyle = _props$forwardedClass2.componentStyle,
warnTooManyClasses = _props$forwardedClass2.warnTooManyClasses;
// statically styled-components don't need to build an execution context object,
// and shouldn't be increasing the number of class names
if (componentStyle.isStatic && attrs === undefined) {
return componentStyle.generateAndInjectStyles(EMPTY_OBJECT, styleSheet);
}
var className = componentStyle.generateAndInjectStyles(this.buildExecutionContext(theme, props, props.forwardedClass.attrs), styleSheet);
if (warnTooManyClasses) {
warnTooManyClasses(className);
}
return className;
};
return StyledComponent;
}(React.Component);
function createStyledComponent(target, options, rules) {
var isTargetStyledComp = isStyledComponent(target);
var isClass = !isTag(target);
var _options$displayName = options.displayName,
displayName = _options$displayName === undefined ? generateDisplayName(target) : _options$displayName,
_options$componentId = options.componentId,
componentId = _options$componentId === undefined ? generateId(ComponentStyle, options.displayName, options.parentComponentId) : _options$componentId,
_options$ParentCompon = options.ParentComponent,
ParentComponent = _options$ParentCompon === undefined ? StyledComponent : _options$ParentCompon,
attrs = options.attrs;
var styledComponentId = options.displayName && options.componentId ? escape(options.displayName) + '-' + options.componentId : options.componentId || componentId;
// fold the underlying StyledComponent attrs up (implicit extend)
var finalAttrs =
// $FlowFixMe
isTargetStyledComp && target.attrs ? _extends({}, target.attrs, attrs) : attrs;
var componentStyle = new ComponentStyle(isTargetStyledComp ? // fold the underlying StyledComponent rules up (implicit extend)
// $FlowFixMe
target.componentStyle.rules.concat(rules) : rules, finalAttrs, styledComponentId);
/**
* forwardRef creates a new interim component, which we'll take advantage of
* instead of extending ParentComponent to create _another_ interim class
*/
var WrappedStyledComponent = React__default.forwardRef(function (props, ref) {
return React__default.createElement(ParentComponent, _extends({}, props, { forwardedClass: WrappedStyledComponent, forwardedRef: ref }));
});
// $FlowFixMe
WrappedStyledComponent.attrs = finalAttrs;
// $FlowFixMe
WrappedStyledComponent.componentStyle = componentStyle;
WrappedStyledComponent.displayName = displayName;
// $FlowFixMe
WrappedStyledComponent.styledComponentId = styledComponentId;
// fold the underlying StyledComponent target up since we folded the styles
// $FlowFixMe
WrappedStyledComponent.target = isTargetStyledComp ? target.target : target;
// $FlowFixMe
WrappedStyledComponent.withComponent = function withComponent(tag) {
var previousComponentId = options.componentId,
optionsToCopy = objectWithoutProperties(options, ['componentId']);
var newComponentId = previousComponentId && previousComponentId + '-' + (isTag(tag) ? tag : escape(getComponentName(tag)));
var newOptions = _extends({}, optionsToCopy, {
attrs: finalAttrs,
componentId: newComponentId,
ParentComponent: ParentComponent
});
return createStyledComponent(tag, newOptions, rules);
};
if (process.env.NODE_ENV !== 'production') {
// $FlowFixMe
WrappedStyledComponent.warnTooManyClasses = createWarnTooManyClasses(displayName);
}
if (isClass) {
hoistNonReactStatics(WrappedStyledComponent, target, {
// all SC-specific things should not be hoisted
attrs: true,
componentStyle: true,
displayName: true,
styledComponentId: true,
target: true,
warnTooManyClasses: true,
withComponent: true
});
}
return WrappedStyledComponent;
}
//
// Thanks to ReactDOMFactories for this handy list!
var domElements = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr',
// SVG
'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan'];
//
var styled = function styled(tag) {
return constructWithOptions(createStyledComponent, tag);
};
// Shorthands for all valid HTML Elements
domElements.forEach(function (domElement) {
styled[domElement] = styled(domElement);
});
//
var GlobalStyle = function () {
function GlobalStyle(rules, componentId) {
classCallCheck(this, GlobalStyle);
this.rules = rules;
this.componentId = componentId;
this.isStatic = isStaticRules(rules);
if (!StyleSheet.master.hasId(componentId)) {
StyleSheet.master.deferredInject(componentId, []);
}
}
GlobalStyle.prototype.createStyles = function createStyles(executionContext, styleSheet) {
var flatCSS = flatten(this.rules, executionContext, styleSheet);
var css = stringifyRules(flatCSS, '');
styleSheet.inject(this.componentId, css);
};
GlobalStyle.prototype.removeStyles = function removeStyles(styleSheet) {
var componentId = this.componentId;
if (styleSheet.hasId(componentId)) {
styleSheet.remove(componentId);
}
};
// TODO: overwrite in-place instead of remove+create?
GlobalStyle.prototype.renderStyles = function renderStyles(executionContext, styleSheet) {
this.removeStyles(styleSheet);
this.createStyles(executionContext, styleSheet);
};
return GlobalStyle;
}();
//
function createGlobalStyle(strings) {
for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
interpolations[_key - 1] = arguments[_key];
}
var rules = css.apply(undefined, [strings].concat(interpolations));
var id = 'sc-global-' + murmurhash(JSON.stringify(rules));
var style = new GlobalStyle(rules, id);
var count = 0;
var GlobalStyleComponent = function (_React$Component) {
inherits(GlobalStyleComponent, _React$Component);
function GlobalStyleComponent() {
classCallCheck(this, GlobalStyleComponent);
var _this = possibleConstructorReturn(this, _React$Component.call(this));
count += 1;
/**
* This fixes HMR compatiblility. Don't ask me why, but this combination of
* caching the closure variables via statics and then persisting the statics in
* state works across HMR where no other combination did. ¯\_(ツ)_/¯
*/
_this.state = {
globalStyle: _this.constructor.globalStyle,
styledComponentId: _this.constructor.styledComponentId
};
return _this;
}
GlobalStyleComponent.prototype.componentDidMount = function componentDidMount() {
if (process.env.NODE_ENV !== 'production' && IS_BROWSER && count > 1) {
console.warn('The global style component ' + this.state.styledComponentId + ' was composed and rendered multiple times in your React component tree. Only the last-rendered copy will have its styles remain in <head> (or your StyleSheetManager target.)');
}
};
GlobalStyleComponent.prototype.componentWillUnmount = function componentWillUnmount() {
count -= 1;
/**
* Depending on the order "render" is called this can cause the styles to be lost
* until the next render pass of the remaining instance, which may
* not be immediate.
*/
if (count === 0) this.state.globalStyle.removeStyles(this.styleSheet);
};
GlobalStyleComponent.prototype.render = function render() {
var _this2 = this;
if (process.env.NODE_ENV !== 'production' && React__default.Children.count(this.props.children)) {
console.warn('The global style component ' + this.state.styledComponentId + ' was given child JSX. createGlobalStyle does not render children.');
}
return React__default.createElement(
StyleSheetConsumer,
null,
function (styleSheet) {
_this2.styleSheet = styleSheet || StyleSheet.master;
var globalStyle = _this2.state.globalStyle;
if (globalStyle.isStatic) {
globalStyle.renderStyles(STATIC_EXECUTION_CONTEXT, _this2.styleSheet);
return null;
} else {
return React__default.createElement(
ThemeConsumer,
null,
function (theme) {
var defaultProps = _this2.constructor.defaultProps;
var context = _extends({}, _this2.props);
if (typeof theme !== 'undefined') {
context.theme = determineTheme(_this2.props, theme, defaultProps);
}
globalStyle.renderStyles(context, _this2.styleSheet);
return null;
}
);
}
}
);
};
return GlobalStyleComponent;
}(React__default.Component);
GlobalStyleComponent.globalStyle = style;
GlobalStyleComponent.styledComponentId = id;
return GlobalStyleComponent;
}
//
var replaceWhitespace = function replaceWhitespace(str) {
return str.replace(/\s|\\n/g, '');
};
function keyframes(strings) {
/* Warning if you've used keyframes on React Native */
if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {
console.warn('`keyframes` cannot be used on ReactNative, only on the web. To do animation in ReactNative please use Animated.');
}
for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
interpolations[_key - 1] = arguments[_key];
}
var rules = css.apply(undefined, [strings].concat(interpolations));
var name = generateAlphabeticName(murmurhash(replaceWhitespace(JSON.stringify(rules))));
return new Keyframes(name, stringifyRules(rules, name, '@keyframes'));
}
//
var withTheme = (function (Component) {
var WithTheme = React__default.forwardRef(function (props, ref) {
return React__default.createElement(
ThemeConsumer,
null,
function (theme) {
// $FlowFixMe
var defaultProps = Component.defaultProps;
var themeProp = determineTheme(props, theme, defaultProps);
if (process.env.NODE_ENV !== 'production' && themeProp === undefined) {
// eslint-disable-next-line no-console
console.warn('[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class ' + getComponentName(Component));
}
return React__default.createElement(Component, _extends({}, props, { theme: themeProp, ref: ref }));
}
);
});
hoistNonReactStatics(WithTheme, Component);
WithTheme.displayName = 'WithTheme(' + getComponentName(Component) + ')';
return WithTheme;
});
//
/* eslint-disable */
var __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS = {
StyleSheet: StyleSheet
};
//
/* Warning if you've imported this file on React Native */
if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {
// eslint-disable-next-line no-console
console.warn("It looks like you've imported 'styled-components' on React Native.\n" + "Perhaps you're looking to import 'styled-components/native'?\n" + 'Read more about this at https://www.styled-components.com/docs/basics#react-native');
}
/* Warning if there are several instances of styled-components */
if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test' && typeof window !== 'undefined' && typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Node.js') === -1 && navigator.userAgent.indexOf('jsdom') === -1) {
window['__styled-components-init__'] = window['__styled-components-init__'] || 0;
if (window['__styled-components-init__'] === 1) {
// eslint-disable-next-line no-console
console.warn("It looks like there are several instances of 'styled-components' initialized in this application. " + 'This may cause dynamic styles not rendering properly, errors happening during rehydration process ' + 'and makes your application bigger without a good reason.\n\n' + 'See https://s-c.sh/2BAXzed for more info.');
}
window['__styled-components-init__'] += 1;
}
//
exports.default = styled;
exports.css = css;
exports.keyframes = keyframes;
exports.createGlobalStyle = createGlobalStyle;
exports.isStyledComponent = isStyledComponent;
exports.ThemeConsumer = ThemeConsumer;
exports.ThemeProvider = ThemeProvider;
exports.withTheme = withTheme;
exports.ServerStyleSheet = ServerStyleSheet;
exports.StyleSheetManager = StyleSheetManager;
exports.__DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS = __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS;
//# sourceMappingURL=styled-components.browser.cjs.js.map
|
src/routes/dashboardPages/finances/index.js | happyboy171/Feeding-Fish-View- | import React from 'react';
import Finances from './Finances';
export default {
path: '/finances',
action() {
return <Finances />;
}
};
|
assets/javascripts/kitten/components/graphics/icons/blockquote-icon/index.js | KissKissBankBank/kitten | import React from 'react'
import PropTypes from 'prop-types'
export const BlockquoteIcon = ({ color, title, ...props }) => (
<svg
width="11"
height="8"
viewBox="0 0 11 8"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
{title && <title>{title}</title>}
<path
d="M.794 8c1.188 0 2.177-.341 2.968-1.023.79-.682 1.366-1.694 1.724-3.034.341.547.713.948 1.116 1.204.403.255.869.383 1.398.383.194 0 .403-.028.626-.083.224-.056.453-.137.688-.243a3.187 3.187 0 01-1.376 1.667c-.647.388-1.505.626-2.575.714L5.724 8h.31c.493 0 .978-.07 1.454-.212.477-.14.9-.34 1.27-.6a4.643 4.643 0 001.509-1.746c.353-.706.529-1.476.529-2.31 0-.918-.262-1.67-.785-2.254C9.488.293 8.817 0 8 0c-.594 0-1.104.156-1.53.467-.427.312-.796.794-1.107 1.447-.306-.659-.668-1.142-1.085-1.45C3.86.153 3.355 0 2.76 0 1.99 0 1.338.269.803.807A2.679 2.679 0 000 2.77c0 .776.266 1.43.798 1.962s1.187.798 1.963.798c.2 0 .408-.026.626-.08.218-.052.45-.134.697-.246a3.286 3.286 0 01-1.385 1.667c-.64.388-1.5.626-2.576.714L.485 8h.309z"
fill={color}
/>
</svg>
)
BlockquoteIcon.propTypes = {
color: PropTypes.string,
title: PropTypes.string,
}
BlockquoteIcon.defaultProps = {
color: '#222',
title: '',
}
|
src/renderers/dom/client/eventPlugins/__tests__/SelectEventPlugin-test.js | mnordick/react | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
var EventConstants;
var React;
var ReactDOM;
var ReactMount;
var ReactTestUtils;
var SelectEventPlugin;
var topLevelTypes;
describe('SelectEventPlugin', function() {
function extract(node, topLevelEvent) {
return SelectEventPlugin.extractEvents(
topLevelEvent,
node,
ReactMount.getID(node),
{target: node},
node
);
}
beforeEach(function() {
EventConstants = require('EventConstants');
React = require('React');
ReactDOM = require('ReactDOM');
ReactMount = require('ReactMount');
ReactTestUtils = require('ReactTestUtils');
SelectEventPlugin = require('SelectEventPlugin');
topLevelTypes = EventConstants.topLevelTypes;
});
it('should skip extraction if no listeners are present', function() {
var WithoutSelect = React.createClass({
render: function() {
return <input type="text" />;
},
});
var rendered = ReactTestUtils.renderIntoDocument(<WithoutSelect />);
var node = ReactDOM.findDOMNode(rendered);
node.focus();
var mousedown = extract(node, topLevelTypes.topMouseDown);
expect(mousedown).toBe(null);
var mouseup = extract(node, topLevelTypes.topMouseUp);
expect(mouseup).toBe(null);
});
it('should extract if an `onSelect` listener is present', function() {
var mocks = require('mocks');
var WithSelect = React.createClass({
render: function() {
return <input type="text" onSelect={this.props.onSelect} />;
},
});
var cb = mocks.getMockFunction();
var rendered = ReactTestUtils.renderIntoDocument(
<WithSelect onSelect={cb} />
);
var node = ReactDOM.findDOMNode(rendered);
node.selectionStart = 0;
node.selectionEnd = 0;
node.focus();
var focus = extract(node, topLevelTypes.topFocus);
expect(focus).toBe(null);
var mousedown = extract(node, topLevelTypes.topMouseDown);
expect(mousedown).toBe(null);
var mouseup = extract(node, topLevelTypes.topMouseUp);
expect(mouseup).not.toBe(null);
expect(typeof mouseup).toBe('object');
expect(mouseup.type).toBe('select');
expect(mouseup.target).toBe(node);
});
});
|
app/react-icons/fa/location-arrow.js | scampersand/sonos-front | import React from 'react';
import IconBase from 'react-icon-base';
export default class FaLocationArrow extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m35.8 7.8l-14.3 28.6q-0.4 0.7-1.3 0.7-0.1 0-0.3 0-0.5-0.1-0.8-0.5t-0.3-0.9v-12.8h-12.9q-0.5 0-0.9-0.3t-0.5-0.8 0.1-1 0.7-0.6l28.6-14.3q0.2-0.2 0.6-0.2 0.6 0 1 0.4 0.3 0.4 0.4 0.8t-0.1 0.9z"/></g>
</IconBase>
);
}
}
|
client/react/src/js/components/static-header.js | ChrisBauer/cb.io | import React from 'react';
import {Injector} from 'js-di';
import swapPageC from './swap-page';
import progressTrackerC from './progress-tracker';
const SwapPage = Injector.invoke(swapPageC);
const ProgressTracker = Injector.invoke(progressTrackerC);
export default function StaticHeader () {
return React.createClass({
displayName: 'StaticHeader',
render: function () {
return (
<header>
<div className="title">Chris Bauer</div>
<ProgressTracker />
<SwapPage options={this.props.frontEnds} />
</header>
);
}
});
};
|
editor/src/CodeMirrorDemo.js | alcat2008/web-demo |
import React from 'react';
import CodeMirror from 'react-codemirror';
import 'codemirror/lib/codemirror.css';
import 'codemirror/mode/jsx/jsx';
class CodeMirrorDemo extends React.Component {
constructor(props) {
super(props);
// initial state
this.state = {
code: '// Code \n' +
'import React from \'react\'; \n' +
'\n' +
'class CodeMirrorDemo extends React.Component {\n' +
' render() {\n' +
' return (\n' +
' <div>CodeMirrorDemo</div>\n' +
' );\n' +
' }\n' +
'}\n' +
'\n' +
'export default CodeMirrorDemo;\n',
};
}
updateCode = (newCode) => {
this.setState({
code: newCode,
});
}
render() {
const options = {
lineNumbers: true,
mode: 'javascript',
tabSize: 2,
};
return (
<CodeMirror
className="codemirror"
value={this.state.code}
onChange={this.updateCode}
options={options}
/>
);
}
}
export default CodeMirrorDemo;
|
ajax/libs/ember-data.js/1.0.0-beta.19.1/ember-data.prod.js | shelsonjava/cdnjs | (function() {
"use strict";
var ember$data$lib$system$model$errors$invalid$$create = Ember.create;
var ember$data$lib$system$model$errors$invalid$$EmberError = Ember.Error;
/**
A `DS.InvalidError` is used by an adapter to signal the external API
was unable to process a request because the content was not
semantically correct or meaningful per the API. Usually this means a
record failed some form of server side validation. When a promise
from an adapter is rejected with a `DS.InvalidError` the record will
transition to the `invalid` state and the errors will be set to the
`errors` property on the record.
For Ember Data to correctly map errors to their corresponding
properties on the model, Ember Data expects each error to be
namespaced under a key that matches the property name. For example
if you had a Post model that looked like this.
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr('string'),
content: DS.attr('string')
});
```
To show an error from the server related to the `title` and
`content` properties your adapter could return a promise that
rejects with a `DS.InvalidError` object that looks like this:
```app/adapters/post.js
import Ember from 'ember';
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
updateRecord: function() {
// Fictional adapter that always rejects
return Ember.RSVP.reject(new DS.InvalidError({
title: ['Must be unique'],
content: ['Must not be blank'],
}));
}
});
```
Your backend may use different property names for your records the
store will attempt extract and normalize the errors using the
serializer's `extractErrors` method before the errors get added to
the the model. As a result, it is safe for the `InvalidError` to
wrap the error payload unaltered.
Example
```app/adapters/application.js
import Ember from 'ember';
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
// 422 is used by this fictional server to signal a validation error
if (jqXHR && jqXHR.status === 422) {
var jsonErrors = Ember.$.parseJSON(jqXHR.responseText);
return new DS.InvalidError(jsonErrors);
} else {
// The ajax request failed however it is not a result of this
// record being in an invalid state so we do not return a
// `InvalidError` object.
return error;
}
}
});
```
@class InvalidError
@namespace DS
*/
function ember$data$lib$system$model$errors$invalid$$InvalidError(errors) {
ember$data$lib$system$model$errors$invalid$$EmberError.call(this, "The backend rejected the commit because it was invalid: " + Ember.inspect(errors));
this.errors = errors;
}
ember$data$lib$system$model$errors$invalid$$InvalidError.prototype = ember$data$lib$system$model$errors$invalid$$create(ember$data$lib$system$model$errors$invalid$$EmberError.prototype);
var ember$data$lib$system$model$errors$invalid$$default = ember$data$lib$system$model$errors$invalid$$InvalidError;
/**
@module ember-data
*/
var ember$data$lib$system$adapter$$get = Ember.get;
/**
An adapter is an object that receives requests from a store and
translates them into the appropriate action to take against your
persistence layer. The persistence layer is usually an HTTP API, but
may be anything, such as the browser's local storage. Typically the
adapter is not invoked directly instead its functionality is accessed
through the `store`.
### Creating an Adapter
Create a new subclass of `DS.Adapter` in the `app/adapters` folder:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
// ...your code here
});
```
Model-specific adapters can be created by putting your adapter
class in an `app/adapters/` + `model-name` + `.js` file of the application.
```app/adapters/post.js
import DS from 'ember-data';
export default DS.Adapter.extend({
// ...Post-specific adapter code goes here
});
```
`DS.Adapter` is an abstract base class that you should override in your
application to customize it for your backend. The minimum set of methods
that you should implement is:
* `find()`
* `createRecord()`
* `updateRecord()`
* `deleteRecord()`
* `findAll()`
* `findQuery()`
To improve the network performance of your application, you can optimize
your adapter by overriding these lower-level methods:
* `findMany()`
For an example implementation, see `DS.RESTAdapter`, the
included REST adapter.
@class Adapter
@namespace DS
@extends Ember.Object
*/
var ember$data$lib$system$adapter$$Adapter = Ember.Object.extend({
/**
If you would like your adapter to use a custom serializer you can
set the `defaultSerializer` property to be the name of the custom
serializer.
Note the `defaultSerializer` serializer has a lower priority than
a model specific serializer (i.e. `PostSerializer`) or the
`application` serializer.
```app/adapters/django.js
import DS from 'ember-data';
export default DS.Adapter.extend({
defaultSerializer: 'django'
});
```
@property defaultSerializer
@type {String}
*/
defaultSerializer: '-default',
/**
The `find()` method is invoked when the store is asked for a record that
has not previously been loaded. In response to `find()` being called, you
should query your persistence layer for a record with the given ID. Once
found, you can asynchronously call the store's `push()` method to push
the record into the store.
Here is an example `find` implementation:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
find: function(store, type, id, snapshot) {
var url = [type.modelName, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method find
@param {DS.Store} store
@param {DS.Model} type
@param {String} id
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
find: null,
/**
The `findAll()` method is called when you call `find` on the store
without an ID (i.e. `store.find('post')`).
Example
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
findAll: function(store, type, sinceToken) {
var url = type;
var query = { since: sinceToken };
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url, query).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@private
@method findAll
@param {DS.Store} store
@param {DS.Model} type
@param {String} sinceToken
@return {Promise} promise
*/
findAll: null,
/**
This method is called when you call `find` on the store with a
query object as the second parameter (i.e. `store.find('person', {
page: 1 })`).
Example
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
findQuery: function(store, type, query) {
var url = type;
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url, query).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@private
@method findQuery
@param {DS.Store} store
@param {DS.Model} type
@param {Object} query
@param {DS.AdapterPopulatedRecordArray} recordArray
@return {Promise} promise
*/
findQuery: null,
/**
If the globally unique IDs for your records should be generated on the client,
implement the `generateIdForRecord()` method. This method will be invoked
each time you create a new record, and the value returned from it will be
assigned to the record's `primaryKey`.
Most traditional REST-like HTTP APIs will not use this method. Instead, the ID
of the record will be set by the server, and your adapter will update the store
with the new ID when it calls `didCreateRecord()`. Only implement this method if
you intend to generate record IDs on the client-side.
The `generateIdForRecord()` method will be invoked with the requesting store as
the first parameter and the newly created record as the second parameter:
```javascript
generateIdForRecord: function(store, inputProperties) {
var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision();
return uuid;
}
```
@method generateIdForRecord
@param {DS.Store} store
@param {DS.Model} type the DS.Model class of the record
@param {Object} inputProperties a hash of properties to set on the
newly created record.
@return {(String|Number)} id
*/
generateIdForRecord: null,
/**
Proxies to the serializer's `serialize` method.
Example
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
createRecord: function(store, type, snapshot) {
var data = this.serialize(snapshot, { includeId: true });
var url = type;
// ...
}
});
```
@method serialize
@param {DS.Snapshot} snapshot
@param {Object} options
@return {Object} serialized snapshot
*/
serialize: function (snapshot, options) {
return ember$data$lib$system$adapter$$get(snapshot.record, 'store').serializerFor(snapshot.modelName).serialize(snapshot, options);
},
/**
Implement this method in a subclass to handle the creation of
new records.
Serializes the record and send it to the server.
Example
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
createRecord: function(store, type, snapshot) {
var data = this.serialize(snapshot, { includeId: true });
var url = type;
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method createRecord
@param {DS.Store} store
@param {DS.Model} type the DS.Model class of the record
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
createRecord: null,
/**
Implement this method in a subclass to handle the updating of
a record.
Serializes the record update and send it to the server.
Example
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
updateRecord: function(store, type, snapshot) {
var data = this.serialize(snapshot, { includeId: true });
var id = snapshot.id;
var url = [type, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'PUT',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method updateRecord
@param {DS.Store} store
@param {DS.Model} type the DS.Model class of the record
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
updateRecord: null,
/**
Implement this method in a subclass to handle the deletion of
a record.
Sends a delete request for the record to the server.
Example
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
deleteRecord: function(store, type, snapshot) {
var data = this.serialize(snapshot, { includeId: true });
var id = snapshot.id;
var url = [type, id].join('/');
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.ajax({
type: 'DELETE',
url: url,
dataType: 'json',
data: data
}).then(function(data) {
Ember.run(null, resolve, data);
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
```
@method deleteRecord
@param {DS.Store} store
@param {DS.Model} type the DS.Model class of the record
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
deleteRecord: null,
/**
By default the store will try to coalesce all `fetchRecord` calls within the same runloop
into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call.
You can opt out of this behaviour by either not implementing the findMany hook or by setting
coalesceFindRequests to false
@property coalesceFindRequests
@type {boolean}
*/
coalesceFindRequests: true,
/**
Find multiple records at once if coalesceFindRequests is true
@method findMany
@param {DS.Store} store
@param {DS.Model} type the DS.Model class of the records
@param {Array} ids
@param {Array} snapshots
@return {Promise} promise
*/
/**
Organize records into groups, each of which is to be passed to separate
calls to `findMany`.
For example, if your api has nested URLs that depend on the parent, you will
want to group records by their parent.
The default implementation returns the records as a single group.
@method groupRecordsForFindMany
@param {DS.Store} store
@param {Array} snapshots
@return {Array} an array of arrays of records, each of which is to be
loaded separately by `findMany`.
*/
groupRecordsForFindMany: function (store, snapshots) {
return [snapshots];
}
});
var ember$data$lib$system$adapter$$default = ember$data$lib$system$adapter$$Adapter;
/**
@module ember-data
*/
var ember$data$lib$adapters$fixture$adapter$$get = Ember.get;
var ember$data$lib$adapters$fixture$adapter$$fmt = Ember.String.fmt;
var ember$data$lib$adapters$fixture$adapter$$indexOf = Ember.EnumerableUtils.indexOf;
var ember$data$lib$adapters$fixture$adapter$$counter = 0;
var ember$data$lib$adapters$fixture$adapter$$default = ember$data$lib$system$adapter$$default.extend({
// by default, fixtures are already in normalized form
serializer: null,
// The fixture adapter does not support coalesceFindRequests
coalesceFindRequests: false,
/**
If `simulateRemoteResponse` is `true` the `FixtureAdapter` will
wait a number of milliseconds before resolving promises with the
fixture values. The wait time can be configured via the `latency`
property.
@property simulateRemoteResponse
@type {Boolean}
@default true
*/
simulateRemoteResponse: true,
/**
By default the `FixtureAdapter` will simulate a wait of the
`latency` milliseconds before resolving promises with the fixture
values. This behavior can be turned off via the
`simulateRemoteResponse` property.
@property latency
@type {Number}
@default 50
*/
latency: 50,
/**
Implement this method in order to provide data associated with a type
@method fixturesForType
@param {DS.Model} typeClass
@return {Array}
*/
fixturesForType: function (typeClass) {
if (typeClass.FIXTURES) {
var fixtures = Ember.A(typeClass.FIXTURES);
return fixtures.map(function (fixture) {
var fixtureIdType = typeof fixture.id;
if (fixtureIdType !== "number" && fixtureIdType !== "string") {
throw new Error(ember$data$lib$adapters$fixture$adapter$$fmt("the id property must be defined as a number or string for fixture %@", [fixture]));
}
fixture.id = fixture.id + "";
return fixture;
});
}
return null;
},
/**
Implement this method in order to query fixtures data
@method queryFixtures
@param {Array} fixtures
@param {Object} query
@param {DS.Model} typeClass
@return {(Promise|Array)}
*/
queryFixtures: function (fixtures, query, typeClass) {
},
/**
@method updateFixtures
@param {DS.Model} typeClass
@param {Array} fixture
*/
updateFixtures: function (typeClass, fixture) {
if (!typeClass.FIXTURES) {
typeClass.FIXTURES = [];
}
var fixtures = typeClass.FIXTURES;
this.deleteLoadedFixture(typeClass, fixture);
fixtures.push(fixture);
},
/**
Implement this method in order to provide json for CRUD methods
@method mockJSON
@param {DS.Store} store
@param {DS.Model} typeClass
@param {DS.Snapshot} snapshot
*/
mockJSON: function (store, typeClass, snapshot) {
return store.serializerFor(snapshot.modelName).serialize(snapshot, { includeId: true });
},
/**
@method generateIdForRecord
@param {DS.Store} store
@return {String} id
*/
generateIdForRecord: function (store) {
return "fixture-" + ember$data$lib$adapters$fixture$adapter$$counter++;
},
/**
@method find
@param {DS.Store} store
@param {DS.Model} typeClass
@param {String} id
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
find: function (store, typeClass, id, snapshot) {
var fixtures = this.fixturesForType(typeClass);
var fixture;
if (fixtures) {
fixture = Ember.A(fixtures).findBy("id", id);
}
if (fixture) {
return this.simulateRemoteCall(function () {
return fixture;
}, this);
}
},
/**
@method findMany
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Array} ids
@param {Array} snapshots
@return {Promise} promise
*/
findMany: function (store, typeClass, ids, snapshots) {
var fixtures = this.fixturesForType(typeClass);
if (fixtures) {
fixtures = fixtures.filter(function (item) {
return ember$data$lib$adapters$fixture$adapter$$indexOf(ids, item.id) !== -1;
});
}
if (fixtures) {
return this.simulateRemoteCall(function () {
return fixtures;
}, this);
}
},
/**
@private
@method findAll
@param {DS.Store} store
@param {DS.Model} typeClass
@return {Promise} promise
*/
findAll: function (store, typeClass) {
var fixtures = this.fixturesForType(typeClass);
return this.simulateRemoteCall(function () {
return fixtures;
}, this);
},
/**
@private
@method findQuery
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} query
@param {DS.AdapterPopulatedRecordArray} array
@return {Promise} promise
*/
findQuery: function (store, typeClass, query, array) {
var fixtures = this.fixturesForType(typeClass);
fixtures = this.queryFixtures(fixtures, query, typeClass);
if (fixtures) {
return this.simulateRemoteCall(function () {
return fixtures;
}, this);
}
},
/**
@method createRecord
@param {DS.Store} store
@param {DS.Model} typeClass
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
createRecord: function (store, typeClass, snapshot) {
var fixture = this.mockJSON(store, typeClass, snapshot);
this.updateFixtures(typeClass, fixture);
return this.simulateRemoteCall(function () {
return fixture;
}, this);
},
/**
@method updateRecord
@param {DS.Store} store
@param {DS.Model} typeClass
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
updateRecord: function (store, typeClass, snapshot) {
var fixture = this.mockJSON(store, typeClass, snapshot);
this.updateFixtures(typeClass, fixture);
return this.simulateRemoteCall(function () {
return fixture;
}, this);
},
/**
@method deleteRecord
@param {DS.Store} store
@param {DS.Model} typeClass
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
deleteRecord: function (store, typeClass, snapshot) {
this.deleteLoadedFixture(typeClass, snapshot);
return this.simulateRemoteCall(function () {
// no payload in a deletion
return null;
});
},
/*
@method deleteLoadedFixture
@private
@param typeClass
@param snapshot
*/
deleteLoadedFixture: function (typeClass, snapshot) {
var existingFixture = this.findExistingFixture(typeClass, snapshot);
if (existingFixture) {
var index = ember$data$lib$adapters$fixture$adapter$$indexOf(typeClass.FIXTURES, existingFixture);
typeClass.FIXTURES.splice(index, 1);
return true;
}
},
/*
@method findExistingFixture
@private
@param typeClass
@param snapshot
*/
findExistingFixture: function (typeClass, snapshot) {
var fixtures = this.fixturesForType(typeClass);
var id = snapshot.id;
return this.findFixtureById(fixtures, id);
},
/*
@method findFixtureById
@private
@param fixtures
@param id
*/
findFixtureById: function (fixtures, id) {
return Ember.A(fixtures).find(function (r) {
if ("" + ember$data$lib$adapters$fixture$adapter$$get(r, "id") === "" + id) {
return true;
} else {
return false;
}
});
},
/*
@method simulateRemoteCall
@private
@param callback
@param context
*/
simulateRemoteCall: function (callback, context) {
var adapter = this;
return new Ember.RSVP.Promise(function (resolve) {
var value = Ember.copy(callback.call(context), true);
if (ember$data$lib$adapters$fixture$adapter$$get(adapter, "simulateRemoteResponse")) {
// Schedule with setTimeout
Ember.run.later(function () {
resolve(value);
}, ember$data$lib$adapters$fixture$adapter$$get(adapter, "latency"));
} else {
// Asynchronous, but at the of the runloop with zero latency
Ember.run.schedule("actions", null, function () {
resolve(value);
});
}
}, "DS: FixtureAdapter#simulateRemoteCall");
}
});
var ember$data$lib$system$map$$Map = Ember.Map;
var ember$data$lib$system$map$$MapWithDefault = Ember.MapWithDefault;
var ember$data$lib$system$map$$default = ember$data$lib$system$map$$Map;
var ember$data$lib$adapters$build$url$mixin$$get = Ember.get;
var ember$data$lib$adapters$build$url$mixin$$default = Ember.Mixin.create({
/**
Builds a URL for a given type and optional ID.
By default, it pluralizes the type's name (for example, 'post'
becomes 'posts' and 'person' becomes 'people'). To override the
pluralization see [pathForType](#method_pathForType).
If an ID is specified, it adds the ID to the path generated
for the type, separated by a `/`.
When called by RESTAdapter.findMany() the `id` and `snapshot` parameters
will be arrays of ids and snapshots.
@method buildURL
@param {String} modelName
@param {(String|Array|Object)} id single id or array of ids or query
@param {(DS.Snapshot|Array)} snapshot single snapshot or array of snapshots
@param {String} requestType
@param {Object} query object of query parameters to send for findQuery requests.
@return {String} url
*/
buildURL: function (modelName, id, snapshot, requestType, query) {
switch (requestType) {
case 'find':
return this.urlForFind(id, modelName, snapshot);
case 'findAll':
return this.urlForFindAll(modelName);
case 'findQuery':
return this.urlForFindQuery(query, modelName);
case 'findMany':
return this.urlForFindMany(id, modelName, snapshot);
case 'findHasMany':
return this.urlForFindHasMany(id, modelName);
case 'findBelongsTo':
return this.urlForFindBelongsTo(id, modelName);
case 'createRecord':
return this.urlForCreateRecord(modelName, snapshot);
case 'updateRecord':
return this.urlForUpdateRecord(id, modelName, snapshot);
case 'deleteRecord':
return this.urlForDeleteRecord(id, modelName, snapshot);
default:
return this._buildURL(modelName, id);
}
},
/**
@method _buildURL
@private
@param {String} modelName
@param {String} id
@return {String} url
*/
_buildURL: function (modelName, id) {
var url = [];
var host = ember$data$lib$adapters$build$url$mixin$$get(this, 'host');
var prefix = this.urlPrefix();
var path;
if (modelName) {
path = this.pathForType(modelName);
if (path) {
url.push(path);
}
}
if (id) {
url.push(encodeURIComponent(id));
}
if (prefix) {
url.unshift(prefix);
}
url = url.join('/');
if (!host && url && url.charAt(0) !== '/') {
url = '/' + url;
}
return url;
},
/**
* @method urlForFind
* @param {String} id
* @param {String} modelName
* @param {DS.Snapshot} snapshot
* @return {String} url
*/
urlForFind: function (id, modelName, snapshot) {
return this._buildURL(modelName, id);
},
/**
* @method urlForFindAll
* @param {String} modelName
* @return {String} url
*/
urlForFindAll: function (modelName) {
return this._buildURL(modelName);
},
/**
* @method urlForFindQuery
* @param {Object} query
* @param {String} modelName
* @return {String} url
*/
urlForFindQuery: function (query, modelName) {
return this._buildURL(modelName);
},
/**
* @method urlForFindMany
* @param {Array} ids
* @param {String} modelName
* @param {Array} snapshots
* @return {String} url
*/
urlForFindMany: function (ids, modelName, snapshots) {
return this._buildURL(modelName);
},
/**
* @method urlForFindHasMany
* @param {String} id
* @param {String} modelName
* @return {String} url
*/
urlForFindHasMany: function (id, modelName) {
return this._buildURL(modelName, id);
},
/**
* @method urlForFindBelongTo
* @param {String} id
* @param {String} modelName
* @return {String} url
*/
urlForFindBelongsTo: function (id, modelName) {
return this._buildURL(modelName, id);
},
/**
* @method urlForCreateRecord
* @param {String} modelName
* @param {DS.Snapshot} snapshot
* @return {String} url
*/
urlForCreateRecord: function (modelName, snapshot) {
return this._buildURL(modelName);
},
/**
* @method urlForUpdateRecord
* @param {String} id
* @param {String} modelName
* @param {DS.Snapshot} snapshot
* @return {String} url
*/
urlForUpdateRecord: function (id, modelName, snapshot) {
return this._buildURL(modelName, id);
},
/**
* @method urlForDeleteRecord
* @param {String} id
* @param {String} modelName
* @param {DS.Snapshot} snapshot
* @return {String} url
*/
urlForDeleteRecord: function (id, modelName, snapshot) {
return this._buildURL(modelName, id);
},
/**
@method urlPrefix
@private
@param {String} path
@param {String} parentURL
@return {String} urlPrefix
*/
urlPrefix: function (path, parentURL) {
var host = ember$data$lib$adapters$build$url$mixin$$get(this, 'host');
var namespace = ember$data$lib$adapters$build$url$mixin$$get(this, 'namespace');
var url = [];
if (path) {
// Protocol relative url
//jscs:disable disallowEmptyBlocks
if (/^\/\//.test(path)) {} else if (path.charAt(0) === '/') {
//jscs:enable disallowEmptyBlocks
if (host) {
path = path.slice(1);
url.push(host);
}
// Relative path
} else if (!/^http(s)?:\/\//.test(path)) {
url.push(parentURL);
}
} else {
if (host) {
url.push(host);
}
if (namespace) {
url.push(namespace);
}
}
if (path) {
url.push(path);
}
return url.join('/');
},
/**
Determines the pathname for a given type.
By default, it pluralizes the type's name (for example,
'post' becomes 'posts' and 'person' becomes 'people').
### Pathname customization
For example if you have an object LineItem with an
endpoint of "/line_items/".
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
pathForType: function(modelName) {
var decamelized = Ember.String.decamelize(modelName);
return Ember.String.pluralize(decamelized);
}
});
```
@method pathForType
@param {String} modelName
@return {String} path
**/
pathForType: function (modelName) {
var camelized = Ember.String.camelize(modelName);
return Ember.String.pluralize(camelized);
}
});
var ember$data$lib$adapters$rest$adapter$$get = Ember.get;
var ember$data$lib$adapters$rest$adapter$$set = Ember.set;
var ember$data$lib$adapters$rest$adapter$$forEach = Ember.ArrayPolyfills.forEach;/**
The REST adapter allows your store to communicate with an HTTP server by
transmitting JSON via XHR. Most Ember.js apps that consume a JSON API
should use the REST adapter.
This adapter is designed around the idea that the JSON exchanged with
the server should be conventional.
## JSON Structure
The REST adapter expects the JSON returned from your server to follow
these conventions.
### Object Root
The JSON payload should be an object that contains the record inside a
root property. For example, in response to a `GET` request for
`/posts/1`, the JSON should look like this:
```js
{
"post": {
"id": 1,
"title": "I'm Running to Reform the W3C's Tag",
"author": "Yehuda Katz"
}
}
```
Similarly, in response to a `GET` request for `/posts`, the JSON should
look like this:
```js
{
"posts": [
{
"id": 1,
"title": "I'm Running to Reform the W3C's Tag",
"author": "Yehuda Katz"
},
{
"id": 2,
"title": "Rails is omakase",
"author": "D2H"
}
]
}
```
### Conventional Names
Attribute names in your JSON payload should be the camelCased versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"person": {
"id": 5,
"firstName": "Barack",
"lastName": "Obama",
"occupation": "President"
}
}
```
## Customization
### Endpoint path customization
Endpoint paths can be prefixed with a `namespace` by setting the namespace
property on the adapter:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
namespace: 'api/1'
});
```
Requests for `App.Person` would now target `/api/1/people/1`.
### Host customization
An adapter can target other hosts by setting the `host` property.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
host: 'https://api.example.com'
});
```
### Headers customization
Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary
headers can be set as key/value pairs on the `RESTAdapter`'s `headers`
object and Ember Data will send them along with each ajax request.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
headers: {
"API_KEY": "secret key",
"ANOTHER_HEADER": "Some header value"
}
});
```
`headers` can also be used as a computed property to support dynamic
headers. In the example below, the `session` object has been
injected into an adapter by Ember's container.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
headers: function() {
return {
"API_KEY": this.get("session.authToken"),
"ANOTHER_HEADER": "Some header value"
};
}.property("session.authToken")
});
```
In some cases, your dynamic headers may require data from some
object outside of Ember's observer system (for example
`document.cookie`). You can use the
[volatile](/api/classes/Ember.ComputedProperty.html#method_volatile)
function to set the property into a non-cached mode causing the headers to
be recomputed with every request.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
headers: function() {
return {
"API_KEY": Ember.get(document.cookie.match(/apiKey\=([^;]*)/), "1"),
"ANOTHER_HEADER": "Some header value"
};
}.property().volatile()
});
```
@class RESTAdapter
@constructor
@namespace DS
@extends DS.Adapter
@uses DS.BuildURLMixin
*/
var ember$data$lib$adapters$rest$adapter$$RestAdapter = ember$data$lib$system$adapter$$Adapter.extend(ember$data$lib$adapters$build$url$mixin$$default, {
defaultSerializer: "-rest",
/**
By default, the RESTAdapter will send the query params sorted alphabetically to the
server.
For example:
```js
store.find('posts', {sort: 'price', category: 'pets'});
```
will generate a requests like this `/posts?category=pets&sort=price`, even if the
parameters were specified in a different order.
That way the generated URL will be deterministic and that simplifies caching mechanisms
in the backend.
Setting `sortQueryParams` to a falsey value will respect the original order.
In case you want to sort the query parameters with a different criteria, set
`sortQueryParams` to your custom sort function.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
sortQueryParams: function(params) {
var sortedKeys = Object.keys(params).sort().reverse();
var len = sortedKeys.length, newParams = {};
for (var i = 0; i < len; i++) {
newParams[sortedKeys[i]] = params[sortedKeys[i]];
}
return newParams;
}
});
```
@method sortQueryParams
@param {Object} obj
@return {Object}
*/
sortQueryParams: function (obj) {
var keys = Ember.keys(obj);
var len = keys.length;
if (len < 2) {
return obj;
}
var newQueryParams = {};
var sortedKeys = keys.sort();
for (var i = 0; i < len; i++) {
newQueryParams[sortedKeys[i]] = obj[sortedKeys[i]];
}
return newQueryParams;
},
/**
By default the RESTAdapter will send each find request coming from a `store.find`
or from accessing a relationship separately to the server. If your server supports passing
ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests
within a single runloop.
For example, if you have an initial payload of:
```javascript
{
post: {
id: 1,
comments: [1, 2]
}
}
```
By default calling `post.get('comments')` will trigger the following requests(assuming the
comments haven't been loaded before):
```
GET /comments/1
GET /comments/2
```
If you set coalesceFindRequests to `true` it will instead trigger the following request:
```
GET /comments?ids[]=1&ids[]=2
```
Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo`
relationships accessed within the same runloop. If you set `coalesceFindRequests: true`
```javascript
store.find('comment', 1);
store.find('comment', 2);
```
will also send a request to: `GET /comments?ids[]=1&ids[]=2`
Note: Requests coalescing rely on URL building strategy. So if you override `buildURL` in your app
`groupRecordsForFindMany` more likely should be overridden as well in order for coalescing to work.
@property coalesceFindRequests
@type {boolean}
*/
coalesceFindRequests: false,
/**
Endpoint paths can be prefixed with a `namespace` by setting the namespace
property on the adapter:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
namespace: 'api/1'
});
```
Requests for `App.Post` would now target `/api/1/post/`.
@property namespace
@type {String}
*/
/**
An adapter can target other hosts by setting the `host` property.
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
host: 'https://api.example.com'
});
```
Requests for `App.Post` would now target `https://api.example.com/post/`.
@property host
@type {String}
*/
/**
Some APIs require HTTP headers, e.g. to provide an API
key. Arbitrary headers can be set as key/value pairs on the
`RESTAdapter`'s `headers` object and Ember Data will send them
along with each ajax request. For dynamic headers see [headers
customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization).
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
headers: {
"API_KEY": "secret key",
"ANOTHER_HEADER": "Some header value"
}
});
```
@property headers
@type {Object}
*/
/**
Called by the store in order to fetch the JSON for a given
type and ID.
The `find` method makes an Ajax request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
This method performs an HTTP `GET` request with the id provided as part of the query string.
@method find
@param {DS.Store} store
@param {DS.Model} type
@param {String} id
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
find: function (store, type, id, snapshot) {
return this.ajax(this.buildURL(type.modelName, id, snapshot, "find"), "GET");
},
/**
Called by the store in order to fetch a JSON array for all
of the records for a given type.
The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
@private
@method findAll
@param {DS.Store} store
@param {DS.Model} type
@param {String} sinceToken
@return {Promise} promise
*/
findAll: function (store, type, sinceToken) {
var query, url;
if (sinceToken) {
query = { since: sinceToken };
}
url = this.buildURL(type.modelName, null, null, "findAll");
return this.ajax(url, "GET", { data: query });
},
/**
Called by the store in order to fetch a JSON array for
the records that match a particular query.
The `findQuery` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
The `query` argument is a simple JavaScript object that will be passed directly
to the server as parameters.
@private
@method findQuery
@param {DS.Store} store
@param {DS.Model} type
@param {Object} query
@return {Promise} promise
*/
findQuery: function (store, type, query) {
var url = this.buildURL(type.modelName, null, null, "findQuery", query);
if (this.sortQueryParams) {
query = this.sortQueryParams(query);
}
return this.ajax(url, "GET", { data: query });
},
/**
Called by the store in order to fetch several records together if `coalesceFindRequests` is true
For example, if the original payload looks like:
```js
{
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2, 3 ]
}
```
The IDs will be passed as a URL-encoded Array of IDs, in this form:
```
ids[]=1&ids[]=2&ids[]=3
```
Many servers, such as Rails and PHP, will automatically convert this URL-encoded array
into an Array for you on the server-side. If you want to encode the
IDs, differently, just override this (one-line) method.
The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
@method findMany
@param {DS.Store} store
@param {DS.Model} type
@param {Array} ids
@param {Array} snapshots
@return {Promise} promise
*/
findMany: function (store, type, ids, snapshots) {
var url = this.buildURL(type.modelName, ids, snapshots, "findMany");
return this.ajax(url, "GET", { data: { ids: ids } });
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a has-many relationship that were originally
specified as a URL (inside of `links`).
For example, if your original payload looks like this:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "comments": "/posts/1/comments" }
}
}
```
This method will be called with the parent record and `/posts/1/comments`.
The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL.
@method findHasMany
@param {DS.Store} store
@param {DS.Snapshot} snapshot
@param {String} url
@return {Promise} promise
*/
findHasMany: function (store, snapshot, url, relationship) {
var id = snapshot.id;
var type = snapshot.modelName;
url = this.urlPrefix(url, this.buildURL(type, id, null, "findHasMany"));
return this.ajax(url, "GET");
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a belongs-to relationship that were originally
specified as a URL (inside of `links`).
For example, if your original payload looks like this:
```js
{
"person": {
"id": 1,
"name": "Tom Dale",
"links": { "group": "/people/1/group" }
}
}
```
This method will be called with the parent record and `/people/1/group`.
The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL.
@method findBelongsTo
@param {DS.Store} store
@param {DS.Snapshot} snapshot
@param {String} url
@return {Promise} promise
*/
findBelongsTo: function (store, snapshot, url, relationship) {
var id = snapshot.id;
var type = snapshot.modelName;
url = this.urlPrefix(url, this.buildURL(type, id, null, "findBelongsTo"));
return this.ajax(url, "GET");
},
/**
Called by the store when a newly created record is
saved via the `save` method on a model record instance.
The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request
to a URL computed by `buildURL`.
See `serialize` for information on how to customize the serialized form
of a record.
@method createRecord
@param {DS.Store} store
@param {DS.Model} type
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
createRecord: function (store, type, snapshot) {
var data = {};
var serializer = store.serializerFor(type.modelName);
var url = this.buildURL(type.modelName, null, snapshot, "createRecord");
serializer.serializeIntoHash(data, type, snapshot, { includeId: true });
return this.ajax(url, "POST", { data: data });
},
/**
Called by the store when an existing record is saved
via the `save` method on a model record instance.
The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request
to a URL computed by `buildURL`.
See `serialize` for information on how to customize the serialized form
of a record.
@method updateRecord
@param {DS.Store} store
@param {DS.Model} type
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
updateRecord: function (store, type, snapshot) {
var data = {};
var serializer = store.serializerFor(type.modelName);
serializer.serializeIntoHash(data, type, snapshot);
var id = snapshot.id;
var url = this.buildURL(type.modelName, id, snapshot, "updateRecord");
return this.ajax(url, "PUT", { data: data });
},
/**
Called by the store when a record is deleted.
The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`.
@method deleteRecord
@param {DS.Store} store
@param {DS.Model} type
@param {DS.Snapshot} snapshot
@return {Promise} promise
*/
deleteRecord: function (store, type, snapshot) {
var id = snapshot.id;
return this.ajax(this.buildURL(type.modelName, id, snapshot, "deleteRecord"), "DELETE");
},
_stripIDFromURL: function (store, snapshot) {
var url = this.buildURL(snapshot.modelName, snapshot.id, snapshot);
var expandedURL = url.split("/");
//Case when the url is of the format ...something/:id
var lastSegment = expandedURL[expandedURL.length - 1];
var id = snapshot.id;
if (lastSegment === id) {
expandedURL[expandedURL.length - 1] = "";
} else if (ember$data$lib$adapters$rest$adapter$$endsWith(lastSegment, "?id=" + id)) {
//Case when the url is of the format ...something?id=:id
expandedURL[expandedURL.length - 1] = lastSegment.substring(0, lastSegment.length - id.length - 1);
}
return expandedURL.join("/");
},
// http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers
maxURLLength: 2048,
/**
Organize records into groups, each of which is to be passed to separate
calls to `findMany`.
This implementation groups together records that have the same base URL but
differing ids. For example `/comments/1` and `/comments/2` will be grouped together
because we know findMany can coalesce them together as `/comments?ids[]=1&ids[]=2`
It also supports urls where ids are passed as a query param, such as `/comments?id=1`
but not those where there is more than 1 query param such as `/comments?id=2&name=David`
Currently only the query param of `id` is supported. If you need to support others, please
override this or the `_stripIDFromURL` method.
It does not group records that have differing base urls, such as for example: `/posts/1/comments/2`
and `/posts/2/comments/3`
@method groupRecordsForFindMany
@param {DS.Store} store
@param {Array} snapshots
@return {Array} an array of arrays of records, each of which is to be
loaded separately by `findMany`.
*/
groupRecordsForFindMany: function (store, snapshots) {
var groups = ember$data$lib$system$map$$MapWithDefault.create({ defaultValue: function () {
return [];
} });
var adapter = this;
var maxURLLength = this.maxURLLength;
ember$data$lib$adapters$rest$adapter$$forEach.call(snapshots, function (snapshot) {
var baseUrl = adapter._stripIDFromURL(store, snapshot);
groups.get(baseUrl).push(snapshot);
});
function splitGroupToFitInUrl(group, maxURLLength, paramNameLength) {
var baseUrl = adapter._stripIDFromURL(store, group[0]);
var idsSize = 0;
var splitGroups = [[]];
ember$data$lib$adapters$rest$adapter$$forEach.call(group, function (snapshot) {
var additionalLength = encodeURIComponent(snapshot.id).length + paramNameLength;
if (baseUrl.length + idsSize + additionalLength >= maxURLLength) {
idsSize = 0;
splitGroups.push([]);
}
idsSize += additionalLength;
var lastGroupIndex = splitGroups.length - 1;
splitGroups[lastGroupIndex].push(snapshot);
});
return splitGroups;
}
var groupsArray = [];
groups.forEach(function (group, key) {
var paramNameLength = "&ids%5B%5D=".length;
var splitGroups = splitGroupToFitInUrl(group, maxURLLength, paramNameLength);
ember$data$lib$adapters$rest$adapter$$forEach.call(splitGroups, function (splitGroup) {
groupsArray.push(splitGroup);
});
});
return groupsArray;
},
/**
Takes an ajax response, and returns an error payload.
Returning a `DS.InvalidError` from this method will cause the
record to transition into the `invalid` state and make the
`errors` object available on the record. When returning an
`InvalidError` the store will attempt to normalize the error data
returned from the server using the serializer's `extractErrors`
method.
Example
```app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var jsonErrors = Ember.$.parseJSON(jqXHR.responseText);
return new DS.InvalidError(jsonErrors);
} else {
return error;
}
}
});
```
Note: As a correctness optimization, the default implementation of
the `ajaxError` method strips out the `then` method from jquery's
ajax response (jqXHR). This is important because the jqXHR's
`then` method fulfills the promise with itself resulting in a
circular "thenable" chain which may cause problems for some
promise libraries.
@method ajaxError
@param {Object} jqXHR
@param {Object} responseText
@param {Object} errorThrown
@return {Object} jqXHR
*/
ajaxError: function (jqXHR, responseText, errorThrown) {
var isObject = jqXHR !== null && typeof jqXHR === "object";
if (isObject) {
jqXHR.then = null;
if (!jqXHR.errorThrown) {
if (typeof errorThrown === "string") {
jqXHR.errorThrown = new Error(errorThrown);
} else {
jqXHR.errorThrown = errorThrown;
}
}
}
return jqXHR;
},
/**
Takes an ajax response, and returns the json payload.
By default this hook just returns the jsonPayload passed to it.
You might want to override it in two cases:
1. Your API might return useful results in the request headers.
If you need to access these, you can override this hook to copy them
from jqXHR to the payload object so they can be processed in you serializer.
2. Your API might return errors as successful responses with status code
200 and an Errors text or object. You can return a DS.InvalidError from
this hook and it will automatically reject the promise and put your record
into the invalid state.
@method ajaxSuccess
@param {Object} jqXHR
@param {Object} jsonPayload
@return {Object} jsonPayload
*/
ajaxSuccess: function (jqXHR, jsonPayload) {
return jsonPayload;
},
/**
Takes a URL, an HTTP method and a hash of data, and makes an
HTTP request.
When the server responds with a payload, Ember Data will call into `extractSingle`
or `extractArray` (depending on whether the original query was for one record or
many records).
By default, `ajax` method has the following behavior:
* It sets the response `dataType` to `"json"`
* If the HTTP method is not `"GET"`, it sets the `Content-Type` to be
`application/json; charset=utf-8`
* If the HTTP method is not `"GET"`, it stringifies the data passed in. The
data is the serialized record in the case of a save.
* Registers success and failure handlers.
@method ajax
@private
@param {String} url
@param {String} type The request type GET, POST, PUT, DELETE etc.
@param {Object} options
@return {Promise} promise
*/
ajax: function (url, type, options) {
var adapter = this;
return new Ember.RSVP.Promise(function (resolve, reject) {
var hash = adapter.ajaxOptions(url, type, options);
hash.success = function (json, textStatus, jqXHR) {
json = adapter.ajaxSuccess(jqXHR, json);
if (json instanceof ember$data$lib$system$model$errors$invalid$$default) {
Ember.run(null, reject, json);
} else {
Ember.run(null, resolve, json);
}
};
hash.error = function (jqXHR, textStatus, errorThrown) {
Ember.run(null, reject, adapter.ajaxError(jqXHR, jqXHR.responseText, errorThrown));
};
Ember.$.ajax(hash);
}, "DS: RESTAdapter#ajax " + type + " to " + url);
},
/**
@method ajaxOptions
@private
@param {String} url
@param {String} type The request type GET, POST, PUT, DELETE etc.
@param {Object} options
@return {Object}
*/
ajaxOptions: function (url, type, options) {
var hash = options || {};
hash.url = url;
hash.type = type;
hash.dataType = "json";
hash.context = this;
if (hash.data && type !== "GET") {
hash.contentType = "application/json; charset=utf-8";
hash.data = JSON.stringify(hash.data);
}
var headers = ember$data$lib$adapters$rest$adapter$$get(this, "headers");
if (headers !== undefined) {
hash.beforeSend = function (xhr) {
ember$data$lib$adapters$rest$adapter$$forEach.call(Ember.keys(headers), function (key) {
xhr.setRequestHeader(key, headers[key]);
});
};
}
return hash;
}
});
//From http://stackoverflow.com/questions/280634/endswith-in-javascript
function ember$data$lib$adapters$rest$adapter$$endsWith(string, suffix) {
if (typeof String.prototype.endsWith !== "function") {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
} else {
return string.endsWith(suffix);
}
}
if (Ember.platform.hasPropertyAccessors) {
Ember.defineProperty(ember$data$lib$adapters$rest$adapter$$RestAdapter.prototype, "maxUrlLength", {
enumerable: false,
get: function () {
return this.maxURLLength;
},
set: function (value) {
ember$data$lib$adapters$rest$adapter$$set(this, "maxURLLength", value);
}
});
}
var ember$data$lib$adapters$rest$adapter$$default = ember$data$lib$adapters$rest$adapter$$RestAdapter;
var ember$lib$main$$default = Ember;
var ember$inflector$lib$lib$system$inflector$$capitalize = ember$lib$main$$default.String.capitalize;
var ember$inflector$lib$lib$system$inflector$$BLANK_REGEX = /^\s*$/;
var ember$inflector$lib$lib$system$inflector$$LAST_WORD_DASHED_REGEX = /(\w+[_-])([a-z\d]+$)/;
var ember$inflector$lib$lib$system$inflector$$LAST_WORD_CAMELIZED_REGEX = /(\w+)([A-Z][a-z\d]*$)/;
var ember$inflector$lib$lib$system$inflector$$CAMELIZED_REGEX = /[A-Z][a-z\d]*$/;
function ember$inflector$lib$lib$system$inflector$$loadUncountable(rules, uncountable) {
for (var i = 0, length = uncountable.length; i < length; i++) {
rules.uncountable[uncountable[i].toLowerCase()] = true;
}
}
function ember$inflector$lib$lib$system$inflector$$loadIrregular(rules, irregularPairs) {
var pair;
for (var i = 0, length = irregularPairs.length; i < length; i++) {
pair = irregularPairs[i];
//pluralizing
rules.irregular[pair[0].toLowerCase()] = pair[1];
rules.irregular[pair[1].toLowerCase()] = pair[1];
//singularizing
rules.irregularInverse[pair[1].toLowerCase()] = pair[0];
rules.irregularInverse[pair[0].toLowerCase()] = pair[0];
}
}
/**
Inflector.Ember provides a mechanism for supplying inflection rules for your
application. Ember includes a default set of inflection rules, and provides an
API for providing additional rules.
Examples:
Creating an inflector with no rules.
```js
var inflector = new Ember.Inflector();
```
Creating an inflector with the default ember ruleset.
```js
var inflector = new Ember.Inflector(Ember.Inflector.defaultRules);
inflector.pluralize('cow'); //=> 'kine'
inflector.singularize('kine'); //=> 'cow'
```
Creating an inflector and adding rules later.
```javascript
var inflector = Ember.Inflector.inflector;
inflector.pluralize('advice'); // => 'advices'
inflector.uncountable('advice');
inflector.pluralize('advice'); // => 'advice'
inflector.pluralize('formula'); // => 'formulas'
inflector.irregular('formula', 'formulae');
inflector.pluralize('formula'); // => 'formulae'
// you would not need to add these as they are the default rules
inflector.plural(/$/, 's');
inflector.singular(/s$/i, '');
```
Creating an inflector with a nondefault ruleset.
```javascript
var rules = {
plurals: [ /$/, 's' ],
singular: [ /\s$/, '' ],
irregularPairs: [
[ 'cow', 'kine' ]
],
uncountable: [ 'fish' ]
};
var inflector = new Ember.Inflector(rules);
```
@class Inflector
@namespace Ember
*/
function ember$inflector$lib$lib$system$inflector$$Inflector(ruleSet) {
ruleSet = ruleSet || {};
ruleSet.uncountable = ruleSet.uncountable || ember$inflector$lib$lib$system$inflector$$makeDictionary();
ruleSet.irregularPairs = ruleSet.irregularPairs || ember$inflector$lib$lib$system$inflector$$makeDictionary();
var rules = this.rules = {
plurals: ruleSet.plurals || [],
singular: ruleSet.singular || [],
irregular: ember$inflector$lib$lib$system$inflector$$makeDictionary(),
irregularInverse: ember$inflector$lib$lib$system$inflector$$makeDictionary(),
uncountable: ember$inflector$lib$lib$system$inflector$$makeDictionary()
};
ember$inflector$lib$lib$system$inflector$$loadUncountable(rules, ruleSet.uncountable);
ember$inflector$lib$lib$system$inflector$$loadIrregular(rules, ruleSet.irregularPairs);
this.enableCache();
}
if (!Object.create && !Object.create(null).hasOwnProperty) {
throw new Error('This browser does not support Object.create(null), please polyfil with es5-sham: http://git.io/yBU2rg');
}
function ember$inflector$lib$lib$system$inflector$$makeDictionary() {
var cache = Object.create(null);
cache['_dict'] = null;
delete cache['_dict'];
return cache;
}
ember$inflector$lib$lib$system$inflector$$Inflector.prototype = {
/**
@public
As inflections can be costly, and commonly the same subset of words are repeatedly
inflected an optional cache is provided.
@method enableCache
*/
enableCache: function () {
this.purgeCache();
this.singularize = function (word) {
this._cacheUsed = true;
return this._sCache[word] || (this._sCache[word] = this._singularize(word));
};
this.pluralize = function (word) {
this._cacheUsed = true;
return this._pCache[word] || (this._pCache[word] = this._pluralize(word));
};
},
/**
@public
@method purgedCache
*/
purgeCache: function () {
this._cacheUsed = false;
this._sCache = ember$inflector$lib$lib$system$inflector$$makeDictionary();
this._pCache = ember$inflector$lib$lib$system$inflector$$makeDictionary();
},
/**
@public
disable caching
@method disableCache;
*/
disableCache: function () {
this._sCache = null;
this._pCache = null;
this.singularize = function (word) {
return this._singularize(word);
};
this.pluralize = function (word) {
return this._pluralize(word);
};
},
/**
@method plural
@param {RegExp} regex
@param {String} string
*/
plural: function (regex, string) {
if (this._cacheUsed) {
this.purgeCache();
}
this.rules.plurals.push([regex, string.toLowerCase()]);
},
/**
@method singular
@param {RegExp} regex
@param {String} string
*/
singular: function (regex, string) {
if (this._cacheUsed) {
this.purgeCache();
}
this.rules.singular.push([regex, string.toLowerCase()]);
},
/**
@method uncountable
@param {String} regex
*/
uncountable: function (string) {
if (this._cacheUsed) {
this.purgeCache();
}
ember$inflector$lib$lib$system$inflector$$loadUncountable(this.rules, [string.toLowerCase()]);
},
/**
@method irregular
@param {String} singular
@param {String} plural
*/
irregular: function (singular, plural) {
if (this._cacheUsed) {
this.purgeCache();
}
ember$inflector$lib$lib$system$inflector$$loadIrregular(this.rules, [[singular, plural]]);
},
/**
@method pluralize
@param {String} word
*/
pluralize: function (word) {
return this._pluralize(word);
},
_pluralize: function (word) {
return this.inflect(word, this.rules.plurals, this.rules.irregular);
},
/**
@method singularize
@param {String} word
*/
singularize: function (word) {
return this._singularize(word);
},
_singularize: function (word) {
return this.inflect(word, this.rules.singular, this.rules.irregularInverse);
},
/**
@protected
@method inflect
@param {String} word
@param {Object} typeRules
@param {Object} irregular
*/
inflect: function (word, typeRules, irregular) {
var inflection, substitution, result, lowercase, wordSplit, firstPhrase, lastWord, isBlank, isCamelized, isUncountable, isIrregular, rule;
isBlank = !word || ember$inflector$lib$lib$system$inflector$$BLANK_REGEX.test(word);
isCamelized = ember$inflector$lib$lib$system$inflector$$CAMELIZED_REGEX.test(word);
firstPhrase = '';
if (isBlank) {
return word;
}
lowercase = word.toLowerCase();
wordSplit = ember$inflector$lib$lib$system$inflector$$LAST_WORD_DASHED_REGEX.exec(word) || ember$inflector$lib$lib$system$inflector$$LAST_WORD_CAMELIZED_REGEX.exec(word);
if (wordSplit) {
firstPhrase = wordSplit[1];
lastWord = wordSplit[2].toLowerCase();
}
isUncountable = this.rules.uncountable[lowercase] || this.rules.uncountable[lastWord];
if (isUncountable) {
return word;
}
isIrregular = irregular && (irregular[lowercase] || irregular[lastWord]);
if (isIrregular) {
if (irregular[lowercase]) {
return isIrregular;
} else {
isIrregular = isCamelized ? ember$inflector$lib$lib$system$inflector$$capitalize(isIrregular) : isIrregular;
return firstPhrase + isIrregular;
}
}
for (var i = typeRules.length, min = 0; i > min; i--) {
inflection = typeRules[i - 1];
rule = inflection[0];
if (rule.test(word)) {
break;
}
}
inflection = inflection || [];
rule = inflection[0];
substitution = inflection[1];
result = word.replace(rule, substitution);
return result;
}
};
var ember$inflector$lib$lib$system$inflector$$default = ember$inflector$lib$lib$system$inflector$$Inflector;
function ember$inflector$lib$lib$system$string$$pluralize(word) {
return ember$inflector$lib$lib$system$inflector$$default.inflector.pluralize(word);
}
function ember$inflector$lib$lib$system$string$$singularize(word) {
return ember$inflector$lib$lib$system$inflector$$default.inflector.singularize(word);
}
var ember$inflector$lib$lib$system$inflections$$default = {
plurals: [[/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status)$/i, '$1es'], [/(bu)s$/i, '$1ses'], [/(buffal|tomat)o$/i, '$1oes'], [/([ti])um$/i, '$1a'], [/([ti])a$/i, '$1a'], [/sis$/i, 'ses'], [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], [/(hive)$/i, '$1s'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/(x|ch|ss|sh)$/i, '$1es'], [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'], [/^(m|l)ouse$/i, '$1ice'], [/^(m|l)ice$/i, '$1ice'], [/^(ox)$/i, '$1en'], [/^(oxen)$/i, '$1'], [/(quiz)$/i, '$1zes']],
singular: [[/s$/i, ''], [/(ss)$/i, '$1'], [/(n)ews$/i, '$1ews'], [/([ti])a$/i, '$1um'], [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'], [/(^analy)(sis|ses)$/i, '$1sis'], [/([^f])ves$/i, '$1fe'], [/(hive)s$/i, '$1'], [/(tive)s$/i, '$1'], [/([lr])ves$/i, '$1f'], [/([^aeiouy]|qu)ies$/i, '$1y'], [/(s)eries$/i, '$1eries'], [/(m)ovies$/i, '$1ovie'], [/(x|ch|ss|sh)es$/i, '$1'], [/^(m|l)ice$/i, '$1ouse'], [/(bus)(es)?$/i, '$1'], [/(o)es$/i, '$1'], [/(shoe)s$/i, '$1'], [/(cris|test)(is|es)$/i, '$1is'], [/^(a)x[ie]s$/i, '$1xis'], [/(octop|vir)(us|i)$/i, '$1us'], [/(alias|status)(es)?$/i, '$1'], [/^(ox)en/i, '$1'], [/(vert|ind)ices$/i, '$1ex'], [/(matr)ices$/i, '$1ix'], [/(quiz)zes$/i, '$1'], [/(database)s$/i, '$1']],
irregularPairs: [['person', 'people'], ['man', 'men'], ['child', 'children'], ['sex', 'sexes'], ['move', 'moves'], ['cow', 'kine'], ['zombie', 'zombies']],
uncountable: ['equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police']
};
ember$inflector$lib$lib$system$inflector$$default.inflector = new ember$inflector$lib$lib$system$inflector$$default(ember$inflector$lib$lib$system$inflections$$default);
var ember$inflector$lib$lib$utils$register$helper$$default = ember$inflector$lib$lib$utils$register$helper$$registerHelper;
function ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration1(name, helperFunction) {
//earlier versions of ember with htmlbars used this
ember$lib$main$$default.HTMLBars.helpers[name] = helperFunction;
}
function ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration2(name, helperFunction) {
//registerHelper has been made private as _registerHelper
//this is kept here if anyone is using it
ember$lib$main$$default.HTMLBars.registerHelper(name, helperFunction);
}
function ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration3(name, helperFunction) {
//latest versin of ember uses this
ember$lib$main$$default.HTMLBars._registerHelper(name, helperFunction);
}
function ember$inflector$lib$lib$utils$register$helper$$registerHelper(name, helperFunction) {
if (ember$lib$main$$default.HTMLBars) {
var fn = ember$lib$main$$default.HTMLBars.makeBoundHelper(helperFunction);
if (ember$lib$main$$default.HTMLBars._registerHelper) {
if (ember$lib$main$$default.HTMLBars.helpers) {
ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration1(name, fn);
} else {
ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration3(name, fn);
}
} else if (ember$lib$main$$default.HTMLBars.registerHelper) {
ember$inflector$lib$lib$utils$register$helper$$registerHelperIteration2(name, fn);
}
} else if (ember$lib$main$$default.Handlebars) {
ember$lib$main$$default.Handlebars.helper(name, helperFunction);
}
}
/**
*
* If you have Ember Inflector (such as if Ember Data is present),
* singularize a word. For example, turn "oxen" into "ox".
*
* Example:
*
* {{singularize myProperty}}
* {{singularize "oxen"}}
*
* @for Ember.HTMLBars.helpers
* @method singularize
* @param {String|Property} word word to singularize
*/
ember$inflector$lib$lib$utils$register$helper$$default('singularize', function (params) {
return ember$inflector$lib$lib$system$string$$singularize(params[0]);
});
/**
*
* If you have Ember Inflector (such as if Ember Data is present),
* pluralize a word. For example, turn "ox" into "oxen".
*
* Example:
*
* {{pluralize count myProperty}}
* {{pluralize 1 "oxen"}}
* {{pluralize myProperty}}
* {{pluralize "ox"}}
*
* @for Ember.HTMLBars.helpers
* @method pluralize
* @param {Number|Property} [count] count of objects
* @param {String|Property} word word to pluralize
*/
ember$inflector$lib$lib$utils$register$helper$$default('pluralize', function (params) {
var count, word;
if (params.length === 1) {
word = params[0];
return ember$inflector$lib$lib$system$string$$pluralize(word);
} else {
count = params[0];
word = params[1];
if (count !== 1) {
word = ember$inflector$lib$lib$system$string$$pluralize(word);
}
return count + ' ' + word;
}
});
if (ember$lib$main$$default.EXTEND_PROTOTYPES === true || ember$lib$main$$default.EXTEND_PROTOTYPES.String) {
/**
See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}}
@method pluralize
@for String
*/
String.prototype.pluralize = function () {
return ember$inflector$lib$lib$system$string$$pluralize(this);
};
/**
See {{#crossLink "Ember.String/singularize"}}{{/crossLink}}
@method singularize
@for String
*/
String.prototype.singularize = function () {
return ember$inflector$lib$lib$system$string$$singularize(this);
};
}
ember$inflector$lib$lib$system$inflector$$default.defaultRules = ember$inflector$lib$lib$system$inflections$$default;
ember$lib$main$$default.Inflector = ember$inflector$lib$lib$system$inflector$$default;
ember$lib$main$$default.String.pluralize = ember$inflector$lib$lib$system$string$$pluralize;
ember$lib$main$$default.String.singularize = ember$inflector$lib$lib$system$string$$singularize;
var ember$inflector$lib$main$$default = ember$inflector$lib$lib$system$inflector$$default;
if (typeof define !== "undefined" && define.amd) {
define("ember-inflector", ["exports"], function (__exports__) {
__exports__["default"] = ember$inflector$lib$lib$system$inflector$$default;
return ember$inflector$lib$lib$system$inflector$$default;
});
} else if (typeof module !== "undefined" && module["exports"]) {
module["exports"] = ember$inflector$lib$lib$system$inflector$$default;
}
/**
@module ember-data
*/
var activemodel$adapter$lib$system$active$model$adapter$$decamelize = Ember.String.decamelize;
var activemodel$adapter$lib$system$active$model$adapter$$underscore = Ember.String.underscore;
/**
The ActiveModelAdapter is a subclass of the RESTAdapter designed to integrate
with a JSON API that uses an underscored naming convention instead of camelCasing.
It has been designed to work out of the box with the
[active\_model\_serializers](http://github.com/rails-api/active_model_serializers)
Ruby gem. This Adapter expects specific settings using ActiveModel::Serializers,
`embed :ids, embed_in_root: true` which sideloads the records.
This adapter extends the DS.RESTAdapter by making consistent use of the camelization,
decamelization and pluralization methods to normalize the serialized JSON into a
format that is compatible with a conventional Rails backend and Ember Data.
## JSON Structure
The ActiveModelAdapter expects the JSON returned from your server to follow
the REST adapter conventions substituting underscored keys for camelcased ones.
Unlike the DS.RESTAdapter, async relationship keys must be the singular form
of the relationship name, followed by "_id" for DS.belongsTo relationships,
or "_ids" for DS.hasMany relationships.
### Conventional Names
Attribute names in your JSON payload should be the underscored versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```js
App.FamousPerson = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"famous_person": {
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation": "President"
}
}
```
Let's imagine that `Occupation` is just another model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.belongsTo('occupation')
});
App.Occupation = DS.Model.extend({
name: DS.attr('string'),
salary: DS.attr('number'),
people: DS.hasMany('person')
});
```
The JSON needed to avoid extra server calls, should look like this:
```js
{
"people": [{
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation_id": 1
}],
"occupations": [{
"id": 1,
"name": "President",
"salary": 100000,
"person_ids": [1]
}]
}
```
@class ActiveModelAdapter
@constructor
@namespace DS
@extends DS.RESTAdapter
**/
var activemodel$adapter$lib$system$active$model$adapter$$ActiveModelAdapter = ember$data$lib$adapters$rest$adapter$$default.extend({
defaultSerializer: "-active-model",
/**
The ActiveModelAdapter overrides the `pathForType` method to build
underscored URLs by decamelizing and pluralizing the object type name.
```js
this.pathForType("famousPerson");
//=> "famous_people"
```
@method pathForType
@param {String} modelName
@return String
*/
pathForType: function (modelName) {
var decamelized = activemodel$adapter$lib$system$active$model$adapter$$decamelize(modelName);
var underscored = activemodel$adapter$lib$system$active$model$adapter$$underscore(decamelized);
return ember$inflector$lib$lib$system$string$$pluralize(underscored);
},
/**
The ActiveModelAdapter overrides the `ajaxError` method
to return a DS.InvalidError for all 422 Unprocessable Entity
responses.
A 422 HTTP response from the server generally implies that the request
was well formed but the API was unable to process it because the
content was not semantically correct or meaningful per the API.
For more information on 422 HTTP Error code see 11.2 WebDAV RFC 4918
https://tools.ietf.org/html/rfc4918#section-11.2
@method ajaxError
@param {Object} jqXHR
@return error
*/
ajaxError: function (jqXHR) {
var error = this._super.apply(this, arguments);
if (jqXHR && jqXHR.status === 422) {
var response = Ember.$.parseJSON(jqXHR.responseText);
return new ember$data$lib$system$model$errors$invalid$$default(response);
} else {
return error;
}
}
});
var activemodel$adapter$lib$system$active$model$adapter$$default = activemodel$adapter$lib$system$active$model$adapter$$ActiveModelAdapter;
var ember$data$lib$system$serializer$$Serializer = Ember.Object.extend({
/**
The `store` property is the application's `store` that contains all records.
It's injected as a service.
It can be used to push records from a non flat data structure server
response.
@property store
@type {DS.Store}
@public
*/
/**
The `extract` method is used to deserialize the payload received from your
data source into the form that Ember Data expects.
@method extract
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Object}
*/
extract: null,
/**
The `serialize` method is used when a record is saved in order to convert
the record into the form that your external data source expects.
`serialize` takes an optional `options` hash with a single option:
- `includeId`: If this is `true`, `serialize` should include the ID
in the serialized object it builds.
@method serialize
@param {DS.Model} record
@param {Object} [options]
@return {Object}
*/
serialize: null,
/**
The `normalize` method is used to convert a payload received from your
external data source into the normalized form `store.push()` expects. You
should override this method, munge the hash and return the normalized
payload.
@method normalize
@param {DS.Model} typeClass
@param {Object} hash
@return {Object}
*/
normalize: function (typeClass, hash) {
return hash;
}
});
var ember$data$lib$system$serializer$$default = ember$data$lib$system$serializer$$Serializer;
var ember$data$lib$serializers$json$serializer$$get = Ember.get;
var ember$data$lib$serializers$json$serializer$$isNone = Ember.isNone;
var ember$data$lib$serializers$json$serializer$$map = Ember.ArrayPolyfills.map;
var ember$data$lib$serializers$json$serializer$$merge = Ember.merge;
var ember$data$lib$serializers$json$serializer$$default = ember$data$lib$system$serializer$$default.extend({
/**
The primaryKey is used when serializing and deserializing
data. Ember Data always uses the `id` property to store the id of
the record. The external source may not always follow this
convention. In these cases it is useful to override the
primaryKey property to match the primaryKey of your external
store.
Example
```app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
primaryKey: '_id'
});
```
@property primaryKey
@type {String}
@default 'id'
*/
primaryKey: 'id',
/**
The `attrs` object can be used to declare a simple mapping between
property names on `DS.Model` records and payload keys in the
serialized JSON object representing the record. An object with the
property `key` can also be used to designate the attribute's key on
the response payload.
Example
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string'),
admin: DS.attr('boolean')
});
```
```app/serializers/person.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
attrs: {
admin: 'is_admin',
occupation: {key: 'career'}
}
});
```
You can also remove attributes by setting the `serialize` key to
false in your mapping object.
Example
```app/serializers/person.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
attrs: {
admin: {serialize: false},
occupation: {key: 'career'}
}
});
```
When serialized:
```javascript
{
"firstName": "Harry",
"lastName": "Houdini",
"career": "magician"
}
```
Note that the `admin` is now not included in the payload.
@property attrs
@type {Object}
*/
mergedProperties: ['attrs'],
/**
Given a subclass of `DS.Model` and a JSON object this method will
iterate through each attribute of the `DS.Model` and invoke the
`DS.Transform#deserialize` method on the matching property of the
JSON object. This method is typically called after the
serializer's `normalize` method.
@method applyTransforms
@private
@param {DS.Model} typeClass
@param {Object} data The data to transform
@return {Object} data The transformed data object
*/
applyTransforms: function (typeClass, data) {
typeClass.eachTransformedAttribute(function applyTransform(key, typeClass) {
if (!data.hasOwnProperty(key)) {
return;
}
var transform = this.transformFor(typeClass);
data[key] = transform.deserialize(data[key]);
}, this);
return data;
},
/**
Normalizes a part of the JSON payload returned by
the server. You should override this method, munge the hash
and call super if you have generic normalization to do.
It takes the type of the record that is being normalized
(as a DS.Model class), the property where the hash was
originally found, and the hash to normalize.
You can use this method, for example, to normalize underscored keys to camelized
or other general-purpose normalizations.
Example
```app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
normalize: function(typeClass, hash) {
var fields = Ember.get(typeClass, 'fields');
fields.forEach(function(field) {
var payloadField = Ember.String.underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return this._super.apply(this, arguments);
}
});
```
@method normalize
@param {DS.Model} typeClass
@param {Object} hash
@return {Object}
*/
normalize: function (typeClass, hash) {
if (!hash) {
return hash;
}
this.normalizeId(hash);
this.normalizeAttributes(typeClass, hash);
this.normalizeRelationships(typeClass, hash);
this.normalizeUsingDeclaredMapping(typeClass, hash);
this.applyTransforms(typeClass, hash);
return hash;
},
/**
You can use this method to normalize all payloads, regardless of whether they
represent single records or an array.
For example, you might want to remove some extraneous data from the payload:
```app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
normalizePayload: function(payload) {
delete payload.version;
delete payload.status;
return payload;
}
});
```
@method normalizePayload
@param {Object} payload
@return {Object} the normalized payload
*/
normalizePayload: function (payload) {
return payload;
},
/**
@method normalizeAttributes
@private
*/
normalizeAttributes: function (typeClass, hash) {
var payloadKey;
if (this.keyForAttribute) {
typeClass.eachAttribute(function (key) {
payloadKey = this.keyForAttribute(key, 'deserialize');
if (key === payloadKey) {
return;
}
if (!hash.hasOwnProperty(payloadKey)) {
return;
}
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}, this);
}
},
/**
@method normalizeRelationships
@private
*/
normalizeRelationships: function (typeClass, hash) {
var payloadKey;
if (this.keyForRelationship) {
typeClass.eachRelationship(function (key, relationship) {
payloadKey = this.keyForRelationship(key, relationship.kind, 'deserialize');
if (key === payloadKey) {
return;
}
if (!hash.hasOwnProperty(payloadKey)) {
return;
}
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}, this);
}
},
/**
@method normalizeUsingDeclaredMapping
@private
*/
normalizeUsingDeclaredMapping: function (typeClass, hash) {
var attrs = ember$data$lib$serializers$json$serializer$$get(this, 'attrs');
var payloadKey, key;
if (attrs) {
for (key in attrs) {
payloadKey = this._getMappedKey(key);
if (!hash.hasOwnProperty(payloadKey)) {
continue;
}
if (payloadKey !== key) {
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}
}
}
},
/**
@method normalizeId
@private
*/
normalizeId: function (hash) {
var primaryKey = ember$data$lib$serializers$json$serializer$$get(this, 'primaryKey');
if (primaryKey === 'id') {
return;
}
hash.id = hash[primaryKey];
delete hash[primaryKey];
},
/**
@method normalizeErrors
@private
*/
normalizeErrors: function (typeClass, hash) {
this.normalizeId(hash);
this.normalizeAttributes(typeClass, hash);
this.normalizeRelationships(typeClass, hash);
this.normalizeUsingDeclaredMapping(typeClass, hash);
},
/**
Looks up the property key that was set by the custom `attr` mapping
passed to the serializer.
@method _getMappedKey
@private
@param {String} key
@return {String} key
*/
_getMappedKey: function (key) {
var attrs = ember$data$lib$serializers$json$serializer$$get(this, 'attrs');
var mappedKey;
if (attrs && attrs[key]) {
mappedKey = attrs[key];
//We need to account for both the {title: 'post_title'} and
//{title: {key: 'post_title'}} forms
if (mappedKey.key) {
mappedKey = mappedKey.key;
}
if (typeof mappedKey === 'string') {
key = mappedKey;
}
}
return key;
},
/**
Check attrs.key.serialize property to inform if the `key`
can be serialized
@method _canSerialize
@private
@param {String} key
@return {boolean} true if the key can be serialized
*/
_canSerialize: function (key) {
var attrs = ember$data$lib$serializers$json$serializer$$get(this, 'attrs');
return !attrs || !attrs[key] || attrs[key].serialize !== false;
},
// SERIALIZE
/**
Called when a record is saved in order to convert the
record into JSON.
By default, it creates a JSON object with a key for
each attribute and belongsTo relationship.
For example, consider this model:
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr(),
body: DS.attr(),
author: DS.belongsTo('user')
});
```
The default serialization would create a JSON object like:
```javascript
{
"title": "Rails is unagi",
"body": "Rails? Omakase? O_O",
"author": 12
}
```
By default, attributes are passed through as-is, unless
you specified an attribute type (`DS.attr('date')`). If
you specify a transform, the JavaScript value will be
serialized when inserted into the JSON hash.
By default, belongs-to relationships are converted into
IDs when inserted into the JSON hash.
## IDs
`serialize` takes an options hash with a single option:
`includeId`. If this option is `true`, `serialize` will,
by default include the ID in the JSON object it builds.
The adapter passes in `includeId: true` when serializing
a record for `createRecord`, but not for `updateRecord`.
## Customization
Your server may expect a different JSON format than the
built-in serialization format.
In that case, you can implement `serialize` yourself and
return a JSON hash of your choosing.
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serialize: function(snapshot, options) {
var json = {
POST_TTL: snapshot.attr('title'),
POST_BDY: snapshot.attr('body'),
POST_CMS: snapshot.hasMany('comments', { ids: true })
}
if (options.includeId) {
json.POST_ID_ = snapshot.id;
}
return json;
}
});
```
## Customizing an App-Wide Serializer
If you want to define a serializer for your entire
application, you'll probably want to use `eachAttribute`
and `eachRelationship` on the record.
```app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serialize: function(snapshot, options) {
var json = {};
snapshot.eachAttribute(function(name) {
json[serverAttributeName(name)] = snapshot.attr(name);
})
snapshot.eachRelationship(function(name, relationship) {
if (relationship.kind === 'hasMany') {
json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true });
}
});
if (options.includeId) {
json.ID_ = snapshot.id;
}
return json;
}
});
function serverAttributeName(attribute) {
return attribute.underscore().toUpperCase();
}
function serverHasManyName(name) {
return serverAttributeName(name.singularize()) + "_IDS";
}
```
This serializer will generate JSON that looks like this:
```javascript
{
"TITLE": "Rails is omakase",
"BODY": "Yep. Omakase.",
"COMMENT_IDS": [ 1, 2, 3 ]
}
```
## Tweaking the Default JSON
If you just want to do some small tweaks on the default JSON,
you can call super first and make the tweaks on the returned
JSON.
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serialize: function(snapshot, options) {
var json = this._super.apply(this, arguments);
json.subject = json.title;
delete json.title;
return json;
}
});
```
@method serialize
@param {DS.Snapshot} snapshot
@param {Object} options
@return {Object} json
*/
serialize: function (snapshot, options) {
var json = {};
if (options && options.includeId) {
var id = snapshot.id;
if (id) {
json[ember$data$lib$serializers$json$serializer$$get(this, 'primaryKey')] = id;
}
}
snapshot.eachAttribute(function (key, attribute) {
this.serializeAttribute(snapshot, json, key, attribute);
}, this);
snapshot.eachRelationship(function (key, relationship) {
if (relationship.kind === 'belongsTo') {
this.serializeBelongsTo(snapshot, json, relationship);
} else if (relationship.kind === 'hasMany') {
this.serializeHasMany(snapshot, json, relationship);
}
}, this);
return json;
},
/**
You can use this method to customize how a serialized record is added to the complete
JSON hash to be sent to the server. By default the JSON Serializer does not namespace
the payload and just sends the raw serialized JSON object.
If your server expects namespaced keys, you should consider using the RESTSerializer.
Otherwise you can override this method to customize how the record is added to the hash.
For example, your server may expect underscored root objects.
```app/serializers/application.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
serializeIntoHash: function(data, type, snapshot, options) {
var root = Ember.String.decamelize(type.modelName);
data[root] = this.serialize(snapshot, options);
}
});
```
@method serializeIntoHash
@param {Object} hash
@param {DS.Model} typeClass
@param {DS.Snapshot} snapshot
@param {Object} options
*/
serializeIntoHash: function (hash, typeClass, snapshot, options) {
ember$data$lib$serializers$json$serializer$$merge(hash, this.serialize(snapshot, options));
},
/**
`serializeAttribute` can be used to customize how `DS.attr`
properties are serialized
For example if you wanted to ensure all your attributes were always
serialized as properties on an `attributes` object you could
write:
```app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serializeAttribute: function(snapshot, json, key, attributes) {
json.attributes = json.attributes || {};
this._super(snapshot, json.attributes, key, attributes);
}
});
```
@method serializeAttribute
@param {DS.Snapshot} snapshot
@param {Object} json
@param {String} key
@param {Object} attribute
*/
serializeAttribute: function (snapshot, json, key, attribute) {
var type = attribute.type;
if (this._canSerialize(key)) {
var value = snapshot.attr(key);
if (type) {
var transform = this.transformFor(type);
value = transform.serialize(value);
}
// if provided, use the mapping provided by `attrs` in
// the serializer
var payloadKey = this._getMappedKey(key);
if (payloadKey === key && this.keyForAttribute) {
payloadKey = this.keyForAttribute(key, 'serialize');
}
json[payloadKey] = value;
}
},
/**
`serializeBelongsTo` can be used to customize how `DS.belongsTo`
properties are serialized.
Example
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serializeBelongsTo: function(snapshot, json, relationship) {
var key = relationship.key;
var belongsTo = snapshot.belongsTo(key);
key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo", "serialize") : key;
json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.record.toJSON();
}
});
```
@method serializeBelongsTo
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializeBelongsTo: function (snapshot, json, relationship) {
var key = relationship.key;
if (this._canSerialize(key)) {
var belongsToId = snapshot.belongsTo(key, { id: true });
// if provided, use the mapping provided by `attrs` in
// the serializer
var payloadKey = this._getMappedKey(key);
if (payloadKey === key && this.keyForRelationship) {
payloadKey = this.keyForRelationship(key, 'belongsTo', 'serialize');
}
//Need to check whether the id is there for new&async records
if (ember$data$lib$serializers$json$serializer$$isNone(belongsToId)) {
json[payloadKey] = null;
} else {
json[payloadKey] = belongsToId;
}
if (relationship.options.polymorphic) {
this.serializePolymorphicType(snapshot, json, relationship);
}
}
},
/**
`serializeHasMany` can be used to customize how `DS.hasMany`
properties are serialized.
Example
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serializeHasMany: function(snapshot, json, relationship) {
var key = relationship.key;
if (key === 'comments') {
return;
} else {
this._super.apply(this, arguments);
}
}
});
```
@method serializeHasMany
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializeHasMany: function (snapshot, json, relationship) {
var key = relationship.key;
if (this._canSerialize(key)) {
var payloadKey;
// if provided, use the mapping provided by `attrs` in
// the serializer
payloadKey = this._getMappedKey(key);
if (payloadKey === key && this.keyForRelationship) {
payloadKey = this.keyForRelationship(key, 'hasMany', 'serialize');
}
var relationshipType = snapshot.type.determineRelationshipType(relationship, this.store);
if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany') {
json[payloadKey] = snapshot.hasMany(key, { ids: true });
// TODO support for polymorphic manyToNone and manyToMany relationships
}
}
},
/**
You can use this method to customize how polymorphic objects are
serialized. Objects are considered to be polymorphic if
`{polymorphic: true}` is pass as the second argument to the
`DS.belongsTo` function.
Example
```app/serializers/comment.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serializePolymorphicType: function(snapshot, json, relationship) {
var key = relationship.key,
belongsTo = snapshot.belongsTo(key);
key = this.keyForAttribute ? this.keyForAttribute(key, "serialize") : key;
if (Ember.isNone(belongsTo)) {
json[key + "_type"] = null;
} else {
json[key + "_type"] = belongsTo.modelName;
}
}
});
```
@method serializePolymorphicType
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: Ember.K,
// EXTRACT
/**
The `extract` method is used to deserialize payload data from the
server. By default the `JSONSerializer` does not push the records
into the store. However records that subclass `JSONSerializer`
such as the `RESTSerializer` may push records into the store as
part of the extract call.
This method delegates to a more specific extract method based on
the `requestType`.
To override this method with a custom one, make sure to call
`return this._super(store, type, payload, id, requestType)` with your
pre-processed data.
Here's an example of using `extract` manually:
```javascript
socket.on('message', function(message) {
var data = message.data;
var typeClass = store.modelFor(message.modelName);
var serializer = store.serializerFor(typeClass.modelName);
var record = serializer.extract(store, typeClass, data, data.id, 'single');
store.push(message.modelName, record);
});
```
@method extract
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extract: function (store, typeClass, payload, id, requestType) {
this.extractMeta(store, typeClass.modelName, payload);
var specificExtract = 'extract' + requestType.charAt(0).toUpperCase() + requestType.substr(1);
return this[specificExtract](store, typeClass, payload, id, requestType);
},
/**
`extractFindAll` is a hook into the extract method used when a
call is made to `DS.Store#findAll`. By default this method is an
alias for [extractArray](#method_extractArray).
@method extractFindAll
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindAll: function (store, typeClass, payload, id, requestType) {
return this.extractArray(store, typeClass, payload, id, requestType);
},
/**
`extractFindQuery` is a hook into the extract method used when a
call is made to `DS.Store#findQuery`. By default this method is an
alias for [extractArray](#method_extractArray).
@method extractFindQuery
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindQuery: function (store, typeClass, payload, id, requestType) {
return this.extractArray(store, typeClass, payload, id, requestType);
},
/**
`extractFindMany` is a hook into the extract method used when a
call is made to `DS.Store#findMany`. By default this method is
alias for [extractArray](#method_extractArray).
@method extractFindMany
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindMany: function (store, typeClass, payload, id, requestType) {
return this.extractArray(store, typeClass, payload, id, requestType);
},
/**
`extractFindHasMany` is a hook into the extract method used when a
call is made to `DS.Store#findHasMany`. By default this method is
alias for [extractArray](#method_extractArray).
@method extractFindHasMany
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindHasMany: function (store, typeClass, payload, id, requestType) {
return this.extractArray(store, typeClass, payload, id, requestType);
},
/**
`extractCreateRecord` is a hook into the extract method used when a
call is made to `DS.Model#save` and the record is new. By default
this method is alias for [extractSave](#method_extractSave).
@method extractCreateRecord
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractCreateRecord: function (store, typeClass, payload, id, requestType) {
return this.extractSave(store, typeClass, payload, id, requestType);
},
/**
`extractUpdateRecord` is a hook into the extract method used when
a call is made to `DS.Model#save` and the record has been updated.
By default this method is alias for [extractSave](#method_extractSave).
@method extractUpdateRecord
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractUpdateRecord: function (store, typeClass, payload, id, requestType) {
return this.extractSave(store, typeClass, payload, id, requestType);
},
/**
`extractDeleteRecord` is a hook into the extract method used when
a call is made to `DS.Model#save` and the record has been deleted.
By default this method is alias for [extractSave](#method_extractSave).
@method extractDeleteRecord
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractDeleteRecord: function (store, typeClass, payload, id, requestType) {
return this.extractSave(store, typeClass, payload, id, requestType);
},
/**
`extractFind` is a hook into the extract method used when
a call is made to `DS.Store#find`. By default this method is
alias for [extractSingle](#method_extractSingle).
@method extractFind
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractFind: function (store, typeClass, payload, id, requestType) {
return this.extractSingle(store, typeClass, payload, id, requestType);
},
/**
`extractFindBelongsTo` is a hook into the extract method used when
a call is made to `DS.Store#findBelongsTo`. By default this method is
alias for [extractSingle](#method_extractSingle).
@method extractFindBelongsTo
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractFindBelongsTo: function (store, typeClass, payload, id, requestType) {
return this.extractSingle(store, typeClass, payload, id, requestType);
},
/**
`extractSave` is a hook into the extract method used when a call
is made to `DS.Model#save`. By default this method is alias
for [extractSingle](#method_extractSingle).
@method extractSave
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractSave: function (store, typeClass, payload, id, requestType) {
return this.extractSingle(store, typeClass, payload, id, requestType);
},
/**
`extractSingle` is used to deserialize a single record returned
from the adapter.
Example
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
extractSingle: function(store, typeClass, payload) {
payload.comments = payload._embedded.comment;
delete payload._embedded;
return this._super(store, typeClass, payload);
},
});
```
@method extractSingle
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractSingle: function (store, typeClass, payload, id, requestType) {
var normalizedPayload = this.normalizePayload(payload);
return this.normalize(typeClass, normalizedPayload);
},
/**
`extractArray` is used to deserialize an array of records
returned from the adapter.
Example
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
extractArray: function(store, typeClass, payload) {
return payload.map(function(json) {
return this.extractSingle(store, typeClass, json);
}, this);
}
});
```
@method extractArray
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} arrayPayload
@param {(String|Number)} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractArray: function (store, typeClass, arrayPayload, id, requestType) {
var normalizedPayload = this.normalizePayload(arrayPayload);
var serializer = this;
return ember$data$lib$serializers$json$serializer$$map.call(normalizedPayload, function (singlePayload) {
return serializer.normalize(typeClass, singlePayload);
});
},
/**
`extractMeta` is used to deserialize any meta information in the
adapter payload. By default Ember Data expects meta information to
be located on the `meta` property of the payload object.
Example
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
extractMeta: function(store, typeClass, payload) {
if (payload && payload._pagination) {
store.setMetadataFor(typeClass, payload._pagination);
delete payload._pagination;
}
}
});
```
@method extractMeta
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
*/
extractMeta: function (store, typeClass, payload) {
if (payload && payload.meta) {
store.setMetadataFor(typeClass, payload.meta);
delete payload.meta;
}
},
/**
`extractErrors` is used to extract model errors when a call is made
to `DS.Model#save` which fails with an `InvalidError`. By default
Ember Data expects error information to be located on the `errors`
property of the payload object.
Example
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
extractErrors: function(store, typeClass, payload, id) {
if (payload && typeof payload === 'object' && payload._problems) {
payload = payload._problems;
this.normalizeErrors(typeClass, payload);
}
return payload;
}
});
```
@method extractErrors
@param {DS.Store} store
@param {DS.Model} typeClass
@param {Object} payload
@param {(String|Number)} id
@return {Object} json The deserialized errors
*/
extractErrors: function (store, typeClass, payload, id) {
if (payload && typeof payload === 'object' && payload.errors) {
payload = payload.errors;
this.normalizeErrors(typeClass, payload);
}
return payload;
},
/**
`keyForAttribute` can be used to define rules for how to convert an
attribute name in your model to a key in your JSON.
Example
```app/serializers/application.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
keyForAttribute: function(attr, method) {
return Ember.String.underscore(attr).toUpperCase();
}
});
```
@method keyForAttribute
@param {String} key
@param {String} method
@return {String} normalized key
*/
keyForAttribute: function (key, method) {
return key;
},
/**
`keyForRelationship` can be used to define a custom key when
serializing and deserializing relationship properties. By default
`JSONSerializer` does not provide an implementation of this method.
Example
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
keyForRelationship: function(key, relationship, method) {
return 'rel_' + Ember.String.underscore(key);
}
});
```
@method keyForRelationship
@param {String} key
@param {String} typeClass
@param {String} method
@return {String} normalized key
*/
keyForRelationship: function (key, typeClass, method) {
return key;
},
// HELPERS
/**
@method transformFor
@private
@param {String} attributeType
@param {Boolean} skipAssertion
@return {DS.Transform} transform
*/
transformFor: function (attributeType, skipAssertion) {
var transform = this.container.lookup('transform:' + attributeType);
return transform;
}
});
var ember$data$lib$system$normalize$model$name$$default = ember$data$lib$system$normalize$model$name$$normalizeModelName;
/**
All modelNames are dasherized internally. Changing this function may
require changes to other normalization hooks (such as typeForRoot).
@method normalizeModelName
@public
@param {String} modelName
@return {String} if the adapter can generate one, an ID
@for DS
*/
function ember$data$lib$system$normalize$model$name$$normalizeModelName(modelName) {
return Ember.String.dasherize(modelName);
}
var ember$data$lib$system$coerce$id$$default = ember$data$lib$system$coerce$id$$coerceId;
// Used by the store to normalize IDs entering the store. Despite the fact
// that developers may provide IDs as numbers (e.g., `store.find(Person, 1)`),
// it is important that internally we use strings, since IDs may be serialized
// and lose type information. For example, Ember's router may put a record's
// ID into the URL, and if we later try to deserialize that URL and find the
// corresponding record, we will not know if it is a string or a number.
function ember$data$lib$system$coerce$id$$coerceId(id) {
return id == null ? null : id + '';
}
var ember$data$lib$serializers$rest$serializer$$forEach = Ember.ArrayPolyfills.forEach;
var ember$data$lib$serializers$rest$serializer$$map = Ember.ArrayPolyfills.map;
var ember$data$lib$serializers$rest$serializer$$camelize = Ember.String.camelize;
/**
Normally, applications will use the `RESTSerializer` by implementing
the `normalize` method and individual normalizations under
`normalizeHash`.
This allows you to do whatever kind of munging you need, and is
especially useful if your server is inconsistent and you need to
do munging differently for many different kinds of responses.
See the `normalize` documentation for more information.
## Across the Board Normalization
There are also a number of hooks that you might find useful to define
across-the-board rules for your payload. These rules will be useful
if your server is consistent, or if you're building an adapter for
an infrastructure service, like Parse, and want to encode service
conventions.
For example, if all of your keys are underscored and all-caps, but
otherwise consistent with the names you use in your models, you
can implement across-the-board rules for how to convert an attribute
name in your model to a key in your JSON.
```app/serializers/application.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
keyForAttribute: function(attr, method) {
return Ember.String.underscore(attr).toUpperCase();
}
});
```
You can also implement `keyForRelationship`, which takes the name
of the relationship as the first parameter, the kind of
relationship (`hasMany` or `belongsTo`) as the second parameter, and
the method (`serialize` or `deserialize`) as the third parameter.
@class RESTSerializer
@namespace DS
@extends DS.JSONSerializer
*/
var ember$data$lib$serializers$rest$serializer$$RESTSerializer = ember$data$lib$serializers$json$serializer$$default.extend({
/**
If you want to do normalizations specific to some part of the payload, you
can specify those under `normalizeHash`.
For example, given the following json where the the `IDs` under
`"comments"` are provided as `_id` instead of `id`.
```javascript
{
"post": {
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2 ]
},
"comments": [{
"_id": 1,
"body": "FIRST"
}, {
"_id": 2,
"body": "Rails is unagi"
}]
}
```
You use `normalizeHash` to normalize just the comments:
```app/serializers/post.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
normalizeHash: {
comments: function(hash) {
hash.id = hash._id;
delete hash._id;
return hash;
}
}
});
```
The key under `normalizeHash` is usually just the original key
that was in the original payload. However, key names will be
impacted by any modifications done in the `normalizePayload`
method. The `DS.RESTSerializer`'s default implementation makes no
changes to the payload keys.
@property normalizeHash
@type {Object}
@default undefined
*/
/**
Normalizes a part of the JSON payload returned by
the server. You should override this method, munge the hash
and call super if you have generic normalization to do.
It takes the type of the record that is being normalized
(as a DS.Model class), the property where the hash was
originally found, and the hash to normalize.
For example, if you have a payload that looks like this:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2 ]
},
"comments": [{
"id": 1,
"body": "FIRST"
}, {
"id": 2,
"body": "Rails is unagi"
}]
}
```
The `normalize` method will be called three times:
* With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }`
* With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }`
* With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }`
You can use this method, for example, to normalize underscored keys to camelized
or other general-purpose normalizations.
If you want to do normalizations specific to some part of the payload, you
can specify those under `normalizeHash`.
For example, if the `IDs` under `"comments"` are provided as `_id` instead of
`id`, you can specify how to normalize just the comments:
```app/serializers/post.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
normalizeHash: {
comments: function(hash) {
hash.id = hash._id;
delete hash._id;
return hash;
}
}
});
```
The key under `normalizeHash` is just the original key that was in the original
payload.
@method normalize
@param {DS.Model} typeClass
@param {Object} hash
@param {String} prop
@return {Object}
*/
normalize: function (typeClass, hash, prop) {
this.normalizeId(hash);
this.normalizeAttributes(typeClass, hash);
this.normalizeRelationships(typeClass, hash);
this.normalizeUsingDeclaredMapping(typeClass, hash);
if (this.normalizeHash && this.normalizeHash[prop]) {
this.normalizeHash[prop](hash);
}
this.applyTransforms(typeClass, hash);
return hash;
},
/**
Called when the server has returned a payload representing
a single record, such as in response to a `find` or `save`.
It is your opportunity to clean up the server's response into the normalized
form expected by Ember Data.
If you want, you can just restructure the top-level of your payload, and
do more fine-grained normalization in the `normalize` method.
For example, if you have a payload like this in response to a request for
post 1:
```js
{
"id": 1,
"title": "Rails is omakase",
"_embedded": {
"comment": [{
"_id": 1,
"comment_title": "FIRST"
}, {
"_id": 2,
"comment_title": "Rails is unagi"
}]
}
}
```
You could implement a serializer that looks like this to get your payload
into shape:
```app/serializers/post.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
// First, restructure the top-level so it's organized by type
extractSingle: function(store, typeClass, payload, id) {
var comments = payload._embedded.comment;
delete payload._embedded;
payload = { comments: comments, post: payload };
return this._super(store, typeClass, payload, id);
},
normalizeHash: {
// Next, normalize individual comments, which (after `extract`)
// are now located under `comments`
comments: function(hash) {
hash.id = hash._id;
hash.title = hash.comment_title;
delete hash._id;
delete hash.comment_title;
return hash;
}
}
})
```
When you call super from your own implementation of `extractSingle`, the
built-in implementation will find the primary record in your normalized
payload and push the remaining records into the store.
The primary record is the single hash found under `post` or the first
element of the `posts` array.
The primary record has special meaning when the record is being created
for the first time or updated (`createRecord` or `updateRecord`). In
particular, it will update the properties of the record that was saved.
@method extractSingle
@param {DS.Store} store
@param {DS.Model} primaryTypeClass
@param {Object} rawPayload
@param {String} recordId
@return {Object} the primary response to the original request
*/
extractSingle: function (store, primaryTypeClass, rawPayload, recordId) {
var payload = this.normalizePayload(rawPayload);
var primaryRecord;
for (var prop in payload) {
var modelName = this.modelNameFromPayloadKey(prop);
if (!store.modelFactoryFor(modelName)) {
continue;
}
var isPrimary = this.isPrimaryType(store, modelName, primaryTypeClass);
var value = payload[prop];
if (value === null) {
continue;
}
// legacy support for singular resources
if (isPrimary && Ember.typeOf(value) !== "array") {
primaryRecord = this.normalize(primaryTypeClass, value, prop);
continue;
}
var normalizedArray = this.normalizeArray(store, modelName, value, prop);
/*jshint loopfunc:true*/
ember$data$lib$serializers$rest$serializer$$forEach.call(normalizedArray, function (hash) {
var isFirstCreatedRecord = isPrimary && !recordId && !primaryRecord;
var isUpdatedRecord = isPrimary && ember$data$lib$system$coerce$id$$default(hash.id) === recordId;
// find the primary record.
//
// It's either:
// * the record with the same ID as the original request
// * in the case of a newly created record that didn't have an ID, the first
// record in the Array
if (isFirstCreatedRecord || isUpdatedRecord) {
primaryRecord = hash;
} else {
store.push(modelName, hash);
}
}, this);
}
return primaryRecord;
},
/**
Called when the server has returned a payload representing
multiple records, such as in response to a `findAll` or `findQuery`.
It is your opportunity to clean up the server's response into the normalized
form expected by Ember Data.
If you want, you can just restructure the top-level of your payload, and
do more fine-grained normalization in the `normalize` method.
For example, if you have a payload like this in response to a request for
all posts:
```js
{
"_embedded": {
"post": [{
"id": 1,
"title": "Rails is omakase"
}, {
"id": 2,
"title": "The Parley Letter"
}],
"comment": [{
"_id": 1,
"comment_title": "Rails is unagi",
"post_id": 1
}, {
"_id": 2,
"comment_title": "Don't tread on me",
"post_id": 2
}]
}
}
```
You could implement a serializer that looks like this to get your payload
into shape:
```app/serializers/post.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
// First, restructure the top-level so it's organized by type
// and the comments are listed under a post's `comments` key.
extractArray: function(store, type, payload) {
var posts = payload._embedded.post;
var comments = [];
var postCache = {};
posts.forEach(function(post) {
post.comments = [];
postCache[post.id] = post;
});
payload._embedded.comment.forEach(function(comment) {
comments.push(comment);
postCache[comment.post_id].comments.push(comment);
delete comment.post_id;
});
payload = { comments: comments, posts: posts };
return this._super(store, type, payload);
},
normalizeHash: {
// Next, normalize individual comments, which (after `extract`)
// are now located under `comments`
comments: function(hash) {
hash.id = hash._id;
hash.title = hash.comment_title;
delete hash._id;
delete hash.comment_title;
return hash;
}
}
})
```
When you call super from your own implementation of `extractArray`, the
built-in implementation will find the primary array in your normalized
payload and push the remaining records into the store.
The primary array is the array found under `posts`.
The primary record has special meaning when responding to `findQuery`
or `findHasMany`. In particular, the primary array will become the
list of records in the record array that kicked off the request.
If your primary array contains secondary (embedded) records of the same type,
you cannot place these into the primary array `posts`. Instead, place the
secondary items into an underscore prefixed property `_posts`, which will
push these items into the store and will not affect the resulting query.
@method extractArray
@param {DS.Store} store
@param {DS.Model} primaryTypeClass
@param {Object} rawPayload
@return {Array} The primary array that was returned in response
to the original query.
*/
extractArray: function (store, primaryTypeClass, rawPayload) {
var payload = this.normalizePayload(rawPayload);
var primaryArray;
for (var prop in payload) {
var modelName = prop;
var forcedSecondary = false;
if (prop.charAt(0) === "_") {
forcedSecondary = true;
modelName = prop.substr(1);
}
var typeName = this.modelNameFromPayloadKey(modelName);
if (!store.modelFactoryFor(typeName)) {
continue;
}
var normalizedArray = this.normalizeArray(store, typeName, payload[prop], prop);
var isPrimary = !forcedSecondary && this.isPrimaryType(store, typeName, primaryTypeClass);
if (isPrimary) {
primaryArray = normalizedArray;
} else {
store.pushMany(typeName, normalizedArray);
}
}
return primaryArray;
},
normalizeArray: function (store, typeName, arrayHash, prop) {
var typeClass = store.modelFor(typeName);
var typeSerializer = store.serializerFor(typeName);
/*jshint loopfunc:true*/
return ember$data$lib$serializers$rest$serializer$$map.call(arrayHash, function (hash) {
return typeSerializer.normalize(typeClass, hash, prop);
}, this);
},
isPrimaryType: function (store, typeName, primaryTypeClass) {
var typeClass = store.modelFor(typeName);
return typeClass.modelName === primaryTypeClass.modelName;
},
/**
This method allows you to push a payload containing top-level
collections of records organized per type.
```js
{
"posts": [{
"id": "1",
"title": "Rails is omakase",
"author", "1",
"comments": [ "1" ]
}],
"comments": [{
"id": "1",
"body": "FIRST"
}],
"users": [{
"id": "1",
"name": "@d2h"
}]
}
```
It will first normalize the payload, so you can use this to push
in data streaming in from your server structured the same way
that fetches and saves are structured.
@method pushPayload
@param {DS.Store} store
@param {Object} rawPayload
*/
pushPayload: function (store, rawPayload) {
var payload = this.normalizePayload(rawPayload);
for (var prop in payload) {
var modelName = this.modelNameFromPayloadKey(prop);
if (!store.modelFactoryFor(modelName)) {
continue;
}
var typeClass = store.modelFor(modelName);
var typeSerializer = store.serializerFor(modelName);
/*jshint loopfunc:true*/
var normalizedArray = ember$data$lib$serializers$rest$serializer$$map.call(Ember.makeArray(payload[prop]), function (hash) {
return typeSerializer.normalize(typeClass, hash, prop);
}, this);
store.pushMany(modelName, normalizedArray);
}
},
/**
This method is used to convert each JSON root key in the payload
into a modelName that it can use to look up the appropriate model for
that part of the payload.
For example, your server may send a model name that does not correspond with
the name of the model in your app. Let's take a look at an example model,
and an example payload:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
});
```
```javascript
{
"blog/post": {
"id": "1
}
}
```
Ember Data is going to normalize the payload's root key for the modelName. As a result,
it will try to look up the "blog/post" model. Since we don't have a model called "blog/post"
(or a file called app/models/blog/post.js in ember-cli), Ember Data will throw an error
because it cannot find the "blog/post" model.
Since we want to remove this namespace, we can define a serializer for the application that will
remove "blog/" from the payload key whenver it's encountered by Ember Data:
```app/serializers/application.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
modelNameFromPayloadKey: function(payloadKey) {
if (payloadKey === 'blog/post') {
return this._super(payloadKey.replace('blog/', ''));
} else {
return this._super(payloadKey);
}
}
});
```
After refreshing, Ember Data will appropriately look up the "post" model.
By default the modelName for a model is its
name in dasherized form. This means that a payload key like "blogPost" would be
normalized to "blog-post" when Ember Data looks up the model. Usually, Ember Data
can use the correct inflection to do this for you. Most of the time, you won't
need to override `modelNameFromPayloadKey` for this purpose.
@method modelNameFromPayloadKey
@param {String} key
@return {String} the model's modelName
*/
modelNameFromPayloadKey: function (key) {
return ember$inflector$lib$lib$system$string$$singularize(ember$data$lib$system$normalize$model$name$$default(key));
},
// SERIALIZE
/**
Called when a record is saved in order to convert the
record into JSON.
By default, it creates a JSON object with a key for
each attribute and belongsTo relationship.
For example, consider this model:
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr(),
body: DS.attr(),
author: DS.belongsTo('user')
});
```
The default serialization would create a JSON object like:
```js
{
"title": "Rails is unagi",
"body": "Rails? Omakase? O_O",
"author": 12
}
```
By default, attributes are passed through as-is, unless
you specified an attribute type (`DS.attr('date')`). If
you specify a transform, the JavaScript value will be
serialized when inserted into the JSON hash.
By default, belongs-to relationships are converted into
IDs when inserted into the JSON hash.
## IDs
`serialize` takes an options hash with a single option:
`includeId`. If this option is `true`, `serialize` will,
by default include the ID in the JSON object it builds.
The adapter passes in `includeId: true` when serializing
a record for `createRecord`, but not for `updateRecord`.
## Customization
Your server may expect a different JSON format than the
built-in serialization format.
In that case, you can implement `serialize` yourself and
return a JSON hash of your choosing.
```app/serializers/post.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
serialize: function(snapshot, options) {
var json = {
POST_TTL: snapshot.attr('title'),
POST_BDY: snapshot.attr('body'),
POST_CMS: snapshot.hasMany('comments', { ids: true })
}
if (options.includeId) {
json.POST_ID_ = snapshot.id;
}
return json;
}
});
```
## Customizing an App-Wide Serializer
If you want to define a serializer for your entire
application, you'll probably want to use `eachAttribute`
and `eachRelationship` on the record.
```app/serializers/application.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
serialize: function(snapshot, options) {
var json = {};
snapshot.eachAttribute(function(name) {
json[serverAttributeName(name)] = snapshot.attr(name);
})
snapshot.eachRelationship(function(name, relationship) {
if (relationship.kind === 'hasMany') {
json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true });
}
});
if (options.includeId) {
json.ID_ = snapshot.id;
}
return json;
}
});
function serverAttributeName(attribute) {
return attribute.underscore().toUpperCase();
}
function serverHasManyName(name) {
return serverAttributeName(name.singularize()) + "_IDS";
}
```
This serializer will generate JSON that looks like this:
```js
{
"TITLE": "Rails is omakase",
"BODY": "Yep. Omakase.",
"COMMENT_IDS": [ 1, 2, 3 ]
}
```
## Tweaking the Default JSON
If you just want to do some small tweaks on the default JSON,
you can call super first and make the tweaks on the returned
JSON.
```app/serializers/post.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
serialize: function(snapshot, options) {
var json = this._super(snapshot, options);
json.subject = json.title;
delete json.title;
return json;
}
});
```
@method serialize
@param {DS.Snapshot} snapshot
@param {Object} options
@return {Object} json
*/
serialize: function (snapshot, options) {
return this._super.apply(this, arguments);
},
/**
You can use this method to customize the root keys serialized into the JSON.
By default the REST Serializer sends the modelName of a model, which is a camelized
version of the name.
For example, your server may expect underscored root objects.
```app/serializers/application.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
serializeIntoHash: function(data, type, record, options) {
var root = Ember.String.decamelize(type.modelName);
data[root] = this.serialize(record, options);
}
});
```
@method serializeIntoHash
@param {Object} hash
@param {DS.Model} typeClass
@param {DS.Snapshot} snapshot
@param {Object} options
*/
serializeIntoHash: function (hash, typeClass, snapshot, options) {
var normalizedRootKey = this.payloadKeyFromModelName(typeClass.modelName);
hash[normalizedRootKey] = this.serialize(snapshot, options);
},
/**
You can use `payloadKeyFromModelName` to override the root key for an outgoing
request. By default, the RESTSerializer returns a camelized version of the
model's name.
For a model called TacoParty, its `modelName` would be the string `taco-party`. The RESTSerializer
will send it to the server with `tacoParty` as the root key in the JSON payload:
```js
{
"tacoParty": {
"id": "1",
"location": "Matthew Beale's House"
}
}
```
For example, your server may expect dasherized root objects:
```app/serializers/application.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
payloadKeyFromModelName: function(modelName) {
return Ember.String.dasherize(modelName);
}
});
```
Given a `TacoParty' model, calling `save` on a tacoModel would produce an outgoing
request like:
```js
{
"taco-party": {
"id": "1",
"location": "Matthew Beale's House"
}
}
```
@method payloadKeyFromModelName
@param {String} modelName
@return {String}
*/
payloadKeyFromModelName: function (modelName) {
return ember$data$lib$serializers$rest$serializer$$camelize(modelName);
},
/**
Deprecated. Use modelNameFromPayloadKey instead
@method typeForRoot
@param {String} modelName
@return {String}
@deprecated
*/
typeForRoot: function (modelName) {
return this.modelNameFromPayloadKey(modelName);
},
/**
You can use this method to customize how polymorphic objects are serialized.
By default the JSON Serializer creates the key by appending `Type` to
the attribute and value from the model's camelcased model name.
@method serializePolymorphicType
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: function (snapshot, json, relationship) {
var key = relationship.key;
var belongsTo = snapshot.belongsTo(key);
key = this.keyForAttribute ? this.keyForAttribute(key, "serialize") : key;
if (Ember.isNone(belongsTo)) {
json[key + "Type"] = null;
} else {
json[key + "Type"] = Ember.String.camelize(belongsTo.modelName);
}
}
});
var ember$data$lib$serializers$rest$serializer$$default = ember$data$lib$serializers$rest$serializer$$RESTSerializer;
/**
@module ember-data
*/
var activemodel$adapter$lib$system$active$model$serializer$$forEach = Ember.EnumerableUtils.forEach;
var activemodel$adapter$lib$system$active$model$serializer$$camelize = Ember.String.camelize;
var activemodel$adapter$lib$system$active$model$serializer$$classify = Ember.String.classify;
var activemodel$adapter$lib$system$active$model$serializer$$decamelize = Ember.String.decamelize;
var activemodel$adapter$lib$system$active$model$serializer$$underscore = Ember.String.underscore;
/**
The ActiveModelSerializer is a subclass of the RESTSerializer designed to integrate
with a JSON API that uses an underscored naming convention instead of camelCasing.
It has been designed to work out of the box with the
[active\_model\_serializers](http://github.com/rails-api/active_model_serializers)
Ruby gem. This Serializer expects specific settings using ActiveModel::Serializers,
`embed :ids, embed_in_root: true` which sideloads the records.
This serializer extends the DS.RESTSerializer by making consistent
use of the camelization, decamelization and pluralization methods to
normalize the serialized JSON into a format that is compatible with
a conventional Rails backend and Ember Data.
## JSON Structure
The ActiveModelSerializer expects the JSON returned from your server
to follow the REST adapter conventions substituting underscored keys
for camelcased ones.
### Conventional Names
Attribute names in your JSON payload should be the underscored versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```js
App.FamousPerson = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"famous_person": {
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation": "President"
}
}
```
Let's imagine that `Occupation` is just another model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.belongsTo('occupation')
});
App.Occupation = DS.Model.extend({
name: DS.attr('string'),
salary: DS.attr('number'),
people: DS.hasMany('person')
});
```
The JSON needed to avoid extra server calls, should look like this:
```js
{
"people": [{
"id": 1,
"first_name": "Barack",
"last_name": "Obama",
"occupation_id": 1
}],
"occupations": [{
"id": 1,
"name": "President",
"salary": 100000,
"person_ids": [1]
}]
}
```
@class ActiveModelSerializer
@namespace DS
@extends DS.RESTSerializer
*/
var activemodel$adapter$lib$system$active$model$serializer$$ActiveModelSerializer = ember$data$lib$serializers$rest$serializer$$default.extend({
// SERIALIZE
/**
Converts camelCased attributes to underscored when serializing.
@method keyForAttribute
@param {String} attribute
@return String
*/
keyForAttribute: function (attr) {
return activemodel$adapter$lib$system$active$model$serializer$$decamelize(attr);
},
/**
Underscores relationship names and appends "_id" or "_ids" when serializing
relationship keys.
@method keyForRelationship
@param {String} relationshipModelName
@param {String} kind
@return String
*/
keyForRelationship: function (relationshipModelName, kind) {
var key = activemodel$adapter$lib$system$active$model$serializer$$decamelize(relationshipModelName);
if (kind === "belongsTo") {
return key + "_id";
} else if (kind === "hasMany") {
return ember$inflector$lib$lib$system$string$$singularize(key) + "_ids";
} else {
return key;
}
},
/*
Does not serialize hasMany relationships by default.
*/
serializeHasMany: Ember.K,
/**
Underscores the JSON root keys when serializing.
@method payloadKeyFromModelName
@param {String} modelName
@return {String}
*/
payloadKeyFromModelName: function (modelName) {
return activemodel$adapter$lib$system$active$model$serializer$$underscore(activemodel$adapter$lib$system$active$model$serializer$$decamelize(modelName));
},
/**
Serializes a polymorphic type as a fully capitalized model name.
@method serializePolymorphicType
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: function (snapshot, json, relationship) {
var key = relationship.key;
var belongsTo = snapshot.belongsTo(key);
var jsonKey = activemodel$adapter$lib$system$active$model$serializer$$underscore(key + "_type");
if (Ember.isNone(belongsTo)) {
json[jsonKey] = null;
} else {
json[jsonKey] = activemodel$adapter$lib$system$active$model$serializer$$classify(belongsTo.modelName).replace(/(\/)([a-z])/g, function (match, separator, chr) {
return match.toUpperCase();
}).replace("/", "::");
}
},
// EXTRACT
/**
Add extra step to `DS.RESTSerializer.normalize` so links are normalized.
If your payload looks like:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "flagged_comments": "api/comments/flagged" }
}
}
```
The normalized version would look like this
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "flaggedComments": "api/comments/flagged" }
}
}
```
@method normalize
@param {subclass of DS.Model} typeClass
@param {Object} hash
@param {String} prop
@return Object
*/
normalize: function (typeClass, hash, prop) {
this.normalizeLinks(hash);
return this._super(typeClass, hash, prop);
},
/**
Convert `snake_cased` links to `camelCase`
@method normalizeLinks
@param {Object} data
*/
normalizeLinks: function (data) {
if (data.links) {
var links = data.links;
for (var link in links) {
var camelizedLink = activemodel$adapter$lib$system$active$model$serializer$$camelize(link);
if (camelizedLink !== link) {
links[camelizedLink] = links[link];
delete links[link];
}
}
}
},
/**
Normalize the polymorphic type from the JSON.
Normalize:
```js
{
id: "1"
minion: { type: "evil_minion", id: "12"}
}
```
To:
```js
{
id: "1"
minion: { type: "evilMinion", id: "12"}
}
```
@param {Subclass of DS.Model} typeClass
@method normalizeRelationships
@private
*/
normalizeRelationships: function (typeClass, hash) {
if (this.keyForRelationship) {
typeClass.eachRelationship(function (key, relationship) {
var payloadKey, payload;
if (relationship.options.polymorphic) {
payloadKey = this.keyForAttribute(key, "deserialize");
payload = hash[payloadKey];
if (payload && payload.type) {
payload.type = this.modelNameFromPayloadKey(payload.type);
} else if (payload && relationship.kind === "hasMany") {
var self = this;
activemodel$adapter$lib$system$active$model$serializer$$forEach(payload, function (single) {
single.type = self.modelNameFromPayloadKey(single.type);
});
}
} else {
payloadKey = this.keyForRelationship(key, relationship.kind, "deserialize");
if (!hash.hasOwnProperty(payloadKey)) {
return;
}
payload = hash[payloadKey];
}
hash[key] = payload;
if (key !== payloadKey) {
delete hash[payloadKey];
}
}, this);
}
},
modelNameFromPayloadKey: function (key) {
var convertedFromRubyModule = activemodel$adapter$lib$system$active$model$serializer$$camelize(ember$inflector$lib$lib$system$string$$singularize(key)).replace(/(^|\:)([A-Z])/g, function (match, separator, chr) {
return match.toLowerCase();
}).replace("::", "/");
return ember$data$lib$system$normalize$model$name$$default(convertedFromRubyModule);
}
});
var activemodel$adapter$lib$system$active$model$serializer$$default = activemodel$adapter$lib$system$active$model$serializer$$ActiveModelSerializer;
function ember$data$lib$system$container$proxy$$ContainerProxy(container) {
this.container = container;
}
ember$data$lib$system$container$proxy$$ContainerProxy.prototype.aliasedFactory = function (path, preLookup) {
var _this = this;
return {
create: function () {
if (preLookup) {
preLookup();
}
return _this.container.lookup(path);
}
};
};
ember$data$lib$system$container$proxy$$ContainerProxy.prototype.registerAlias = function (source, dest, preLookup) {
var factory = this.aliasedFactory(dest, preLookup);
return this.container.register(source, factory);
};
ember$data$lib$system$container$proxy$$ContainerProxy.prototype.registerDeprecation = function (deprecated, valid) {
var preLookupCallback = function () {
};
return this.registerAlias(deprecated, valid, preLookupCallback);
};
ember$data$lib$system$container$proxy$$ContainerProxy.prototype.registerDeprecations = function (proxyPairs) {
var i, proxyPair, deprecated, valid;
for (i = proxyPairs.length; i > 0; i--) {
proxyPair = proxyPairs[i - 1];
deprecated = proxyPair["deprecated"];
valid = proxyPair["valid"];
this.registerDeprecation(deprecated, valid);
}
};
var ember$data$lib$system$container$proxy$$default = ember$data$lib$system$container$proxy$$ContainerProxy;
var activemodel$adapter$lib$setup$container$$default = activemodel$adapter$lib$setup$container$$setupActiveModelAdapter;
function activemodel$adapter$lib$setup$container$$setupActiveModelAdapter(registry, application) {
var proxy = new ember$data$lib$system$container$proxy$$default(registry);
proxy.registerDeprecations([{ deprecated: "serializer:_ams", valid: "serializer:-active-model" }, { deprecated: "adapter:_ams", valid: "adapter:-active-model" }]);
registry.register("serializer:-active-model", activemodel$adapter$lib$system$active$model$serializer$$default);
registry.register("adapter:-active-model", activemodel$adapter$lib$system$active$model$adapter$$default);
}
var ember$data$lib$core$$DS = Ember.Namespace.create({
VERSION: '1.0.0-beta.19.1'
});
if (Ember.libraries) {
Ember.libraries.registerCoreLibrary('Ember Data', ember$data$lib$core$$DS.VERSION);
}
//jshint ignore: line
var ember$data$lib$core$$EMBER_DATA_FEATURES = {};
Ember.merge(Ember.FEATURES, ember$data$lib$core$$EMBER_DATA_FEATURES);
var ember$data$lib$core$$default = ember$data$lib$core$$DS;
var ember$data$lib$system$promise$proxies$$Promise = Ember.RSVP.Promise;
var ember$data$lib$system$promise$proxies$$get = Ember.get;
/**
A `PromiseArray` is an object that acts like both an `Ember.Array`
and a promise. When the promise is resolved the resulting value
will be set to the `PromiseArray`'s `content` property. This makes
it easy to create data bindings with the `PromiseArray` that will be
updated when the promise resolves.
For more information see the [Ember.PromiseProxyMixin
documentation](/api/classes/Ember.PromiseProxyMixin.html).
Example
```javascript
var promiseArray = DS.PromiseArray.create({
promise: $.getJSON('/some/remote/data.json')
});
promiseArray.get('length'); // 0
promiseArray.then(function() {
promiseArray.get('length'); // 100
});
```
@class PromiseArray
@namespace DS
@extends Ember.ArrayProxy
@uses Ember.PromiseProxyMixin
*/
var ember$data$lib$system$promise$proxies$$PromiseArray = Ember.ArrayProxy.extend(Ember.PromiseProxyMixin);
/**
A `PromiseObject` is an object that acts like both an `Ember.Object`
and a promise. When the promise is resolved, then the resulting value
will be set to the `PromiseObject`'s `content` property. This makes
it easy to create data bindings with the `PromiseObject` that will
be updated when the promise resolves.
For more information see the [Ember.PromiseProxyMixin
documentation](/api/classes/Ember.PromiseProxyMixin.html).
Example
```javascript
var promiseObject = DS.PromiseObject.create({
promise: $.getJSON('/some/remote/data.json')
});
promiseObject.get('name'); // null
promiseObject.then(function() {
promiseObject.get('name'); // 'Tomster'
});
```
@class PromiseObject
@namespace DS
@extends Ember.ObjectProxy
@uses Ember.PromiseProxyMixin
*/
var ember$data$lib$system$promise$proxies$$PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin);
var ember$data$lib$system$promise$proxies$$promiseObject = function (promise, label) {
return ember$data$lib$system$promise$proxies$$PromiseObject.create({
promise: ember$data$lib$system$promise$proxies$$Promise.resolve(promise, label)
});
};
var ember$data$lib$system$promise$proxies$$promiseArray = function (promise, label) {
return ember$data$lib$system$promise$proxies$$PromiseArray.create({
promise: ember$data$lib$system$promise$proxies$$Promise.resolve(promise, label)
});
};
/**
A PromiseManyArray is a PromiseArray that also proxies certain method calls
to the underlying manyArray.
Right now we proxy:
* `reload()`
* `createRecord()`
* `on()`
* `one()`
* `trigger()`
* `off()`
* `has()`
@class PromiseManyArray
@namespace DS
@extends Ember.ArrayProxy
*/
function ember$data$lib$system$promise$proxies$$proxyToContent(method) {
return function () {
var content = ember$data$lib$system$promise$proxies$$get(this, 'content');
return content[method].apply(content, arguments);
};
}
var ember$data$lib$system$promise$proxies$$PromiseManyArray = ember$data$lib$system$promise$proxies$$PromiseArray.extend({
reload: function () {
//I don't think this should ever happen right now, but worth guarding if we refactor the async relationships
return ember$data$lib$system$promise$proxies$$PromiseManyArray.create({
promise: ember$data$lib$system$promise$proxies$$get(this, 'content').reload()
});
},
createRecord: ember$data$lib$system$promise$proxies$$proxyToContent('createRecord'),
on: ember$data$lib$system$promise$proxies$$proxyToContent('on'),
one: ember$data$lib$system$promise$proxies$$proxyToContent('one'),
trigger: ember$data$lib$system$promise$proxies$$proxyToContent('trigger'),
off: ember$data$lib$system$promise$proxies$$proxyToContent('off'),
has: ember$data$lib$system$promise$proxies$$proxyToContent('has')
});
var ember$data$lib$system$promise$proxies$$promiseManyArray = function (promise, label) {
return ember$data$lib$system$promise$proxies$$PromiseManyArray.create({
promise: ember$data$lib$system$promise$proxies$$Promise.resolve(promise, label)
});
};
var ember$data$lib$system$store$common$$get = Ember.get;
function ember$data$lib$system$store$common$$_bind(fn) {
var args = Array.prototype.slice.call(arguments, 1);
return function () {
return fn.apply(undefined, args);
};
}
function ember$data$lib$system$store$common$$_guard(promise, test) {
var guarded = promise["finally"](function () {
if (!test()) {
guarded._subscribers.length = 0;
}
});
return guarded;
}
function ember$data$lib$system$store$common$$_objectIsAlive(object) {
return !(ember$data$lib$system$store$common$$get(object, "isDestroyed") || ember$data$lib$system$store$common$$get(object, "isDestroying"));
}
function ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, type) {
var serializer = adapter.serializer;
if (serializer === undefined) {
serializer = store.serializerFor(type);
}
if (serializer === null || serializer === undefined) {
serializer = {
extract: function (store, type, payload) {
return payload;
}
};
}
return serializer;
}
var ember$data$lib$system$store$finders$$Promise = Ember.RSVP.Promise;
var ember$data$lib$system$store$finders$$map = Ember.EnumerableUtils.map;
function ember$data$lib$system$store$finders$$_find(adapter, store, typeClass, id, internalModel) {
var snapshot = internalModel.createSnapshot();
var promise = adapter.find(store, typeClass, id, snapshot);
var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, internalModel.type.modelName);
var label = "DS: Handle Adapter#find of " + typeClass + " with id: " + id;
promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store));
return promise.then(function (adapterPayload) {
return store._adapterRun(function () {
var payload = serializer.extract(store, typeClass, adapterPayload, id, "find");
//TODO Optimize
var record = store.push(typeClass.modelName, payload);
return record._internalModel;
});
}, function (error) {
internalModel.notFound();
if (internalModel.isEmpty()) {
internalModel.unloadRecord();
}
throw error;
}, "DS: Extract payload of '" + typeClass + "'");
}
function ember$data$lib$system$store$finders$$_findMany(adapter, store, typeClass, ids, internalModels) {
var snapshots = Ember.A(internalModels).invoke("createSnapshot");
var promise = adapter.findMany(store, typeClass, ids, snapshots);
var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, typeClass.modelName);
var label = "DS: Handle Adapter#findMany of " + typeClass;
if (promise === undefined) {
throw new Error("adapter.findMany returned undefined, this was very likely a mistake");
}
promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store));
return promise.then(function (adapterPayload) {
return store._adapterRun(function () {
var payload = serializer.extract(store, typeClass, adapterPayload, null, "findMany");
//TODO Optimize, no need to materialize here
var records = store.pushMany(typeClass.modelName, payload);
return ember$data$lib$system$store$finders$$map(records, function (record) {
return record._internalModel;
});
});
}, null, "DS: Extract payload of " + typeClass);
}
function ember$data$lib$system$store$finders$$_findHasMany(adapter, store, internalModel, link, relationship) {
var snapshot = internalModel.createSnapshot();
var typeClass = store.modelFor(relationship.type);
var promise = adapter.findHasMany(store, snapshot, link, relationship);
var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, relationship.type);
var label = "DS: Handle Adapter#findHasMany of " + internalModel + " : " + relationship.type;
promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store));
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, internalModel));
return promise.then(function (adapterPayload) {
return store._adapterRun(function () {
var payload = serializer.extract(store, typeClass, adapterPayload, null, "findHasMany");
//TODO Use a non record creating push
var records = store.pushMany(relationship.type, payload);
return ember$data$lib$system$store$finders$$map(records, function (record) {
return record._internalModel;
});
});
}, null, "DS: Extract payload of " + internalModel + " : hasMany " + relationship.type);
}
function ember$data$lib$system$store$finders$$_findBelongsTo(adapter, store, internalModel, link, relationship) {
var snapshot = internalModel.createSnapshot();
var typeClass = store.modelFor(relationship.type);
var promise = adapter.findBelongsTo(store, snapshot, link, relationship);
var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, relationship.type);
var label = "DS: Handle Adapter#findBelongsTo of " + internalModel + " : " + relationship.type;
promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store));
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, internalModel));
return promise.then(function (adapterPayload) {
return store._adapterRun(function () {
var payload = serializer.extract(store, typeClass, adapterPayload, null, "findBelongsTo");
if (!payload) {
return null;
}
var record = store.push(relationship.type, payload);
//TODO Optimize
return record._internalModel;
});
}, null, "DS: Extract payload of " + internalModel + " : " + relationship.type);
}
function ember$data$lib$system$store$finders$$_findAll(adapter, store, typeClass, sinceToken) {
var promise = adapter.findAll(store, typeClass, sinceToken);
var modelName = typeClass.modelName;
var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, modelName);
var label = "DS: Handle Adapter#findAll of " + typeClass;
promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store));
return promise.then(function (adapterPayload) {
store._adapterRun(function () {
var payload = serializer.extract(store, typeClass, adapterPayload, null, "findAll");
store.pushMany(modelName, payload);
});
store.didUpdateAll(typeClass);
return store.all(modelName);
}, null, "DS: Extract payload of findAll " + typeClass);
}
function ember$data$lib$system$store$finders$$_findQuery(adapter, store, typeClass, query, recordArray) {
var modelName = typeClass.modelName;
var promise = adapter.findQuery(store, typeClass, query, recordArray);
var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, modelName);
var label = "DS: Handle Adapter#findQuery of " + typeClass;
promise = ember$data$lib$system$store$finders$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store));
return promise.then(function (adapterPayload) {
var payload;
store._adapterRun(function () {
payload = serializer.extract(store, typeClass, adapterPayload, null, "findQuery");
});
recordArray.load(payload);
return recordArray;
}, null, "DS: Extract payload of findQuery " + typeClass);
}
var ember$data$lib$system$record$arrays$record$array$$get = Ember.get;
var ember$data$lib$system$record$arrays$record$array$$set = Ember.set;
var ember$data$lib$system$record$arrays$record$array$$default = Ember.ArrayProxy.extend(Ember.Evented, {
/**
The model type contained by this record array.
@property type
@type DS.Model
*/
type: null,
/**
The array of client ids backing the record array. When a
record is requested from the record array, the record
for the client id at the same index is materialized, if
necessary, by the store.
@property content
@private
@type Ember.Array
*/
content: null,
/**
The flag to signal a `RecordArray` is finished loading data.
Example
```javascript
var people = store.all('person');
people.get('isLoaded'); // true
```
@property isLoaded
@type Boolean
*/
isLoaded: false,
/**
The flag to signal a `RecordArray` is currently loading data.
Example
```javascript
var people = store.all('person');
people.get('isUpdating'); // false
people.update();
people.get('isUpdating'); // true
```
@property isUpdating
@type Boolean
*/
isUpdating: false,
/**
The store that created this record array.
@property store
@private
@type DS.Store
*/
store: null,
/**
Retrieves an object from the content by index.
@method objectAtContent
@private
@param {Number} index
@return {DS.Model} record
*/
objectAtContent: function (index) {
var content = ember$data$lib$system$record$arrays$record$array$$get(this, 'content');
var internalModel = content.objectAt(index);
return internalModel && internalModel.getRecord();
},
/**
Used to get the latest version of all of the records in this array
from the adapter.
Example
```javascript
var people = store.all('person');
people.get('isUpdating'); // false
people.update();
people.get('isUpdating'); // true
```
@method update
*/
update: function () {
if (ember$data$lib$system$record$arrays$record$array$$get(this, 'isUpdating')) {
return;
}
var store = ember$data$lib$system$record$arrays$record$array$$get(this, 'store');
var modelName = ember$data$lib$system$record$arrays$record$array$$get(this, 'type.modelName');
return store.fetchAll(modelName, this);
},
/**
Adds an internal model to the `RecordArray` without duplicates
@method addInternalModel
@private
@param {InternalModel} internalModel
@param {number} an optional index to insert at
*/
addInternalModel: function (internalModel, idx) {
var content = ember$data$lib$system$record$arrays$record$array$$get(this, 'content');
if (idx === undefined) {
content.addObject(internalModel);
} else if (!content.contains(internalModel)) {
content.insertAt(idx, internalModel);
}
},
/**
Removes an internalModel to the `RecordArray`.
@method removeInternalModel
@private
@param {InternalModel} internalModel
*/
removeInternalModel: function (internalModel) {
ember$data$lib$system$record$arrays$record$array$$get(this, 'content').removeObject(internalModel);
},
/**
Saves all of the records in the `RecordArray`.
Example
```javascript
var messages = store.all('message');
messages.forEach(function(message) {
message.set('hasBeenSeen', true);
});
messages.save();
```
@method save
@return {DS.PromiseArray} promise
*/
save: function () {
var recordArray = this;
var promiseLabel = 'DS: RecordArray#save ' + ember$data$lib$system$record$arrays$record$array$$get(this, 'type');
var promise = Ember.RSVP.all(this.invoke('save'), promiseLabel).then(function (array) {
return recordArray;
}, null, 'DS: RecordArray#save return RecordArray');
return ember$data$lib$system$promise$proxies$$PromiseArray.create({ promise: promise });
},
_dissociateFromOwnRecords: function () {
var array = this;
this.get('content').forEach(function (record) {
var recordArrays = record._recordArrays;
if (recordArrays) {
recordArrays["delete"](array);
}
});
},
/**
@method _unregisterFromManager
@private
*/
_unregisterFromManager: function () {
var manager = ember$data$lib$system$record$arrays$record$array$$get(this, 'manager');
manager.unregisterFilteredRecordArray(this);
},
willDestroy: function () {
this._unregisterFromManager();
this._dissociateFromOwnRecords();
ember$data$lib$system$record$arrays$record$array$$set(this, 'content', undefined);
this._super.apply(this, arguments);
}
});
/**
@module ember-data
*/
var ember$data$lib$system$record$arrays$filtered$record$array$$get = Ember.get;
var ember$data$lib$system$record$arrays$filtered$record$array$$default = ember$data$lib$system$record$arrays$record$array$$default.extend({
/**
The filterFunction is a function used to test records from the store to
determine if they should be part of the record array.
Example
```javascript
var allPeople = store.all('person');
allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"]
var people = store.filter('person', function(person) {
if (person.get('name').match(/Katz$/)) { return true; }
});
people.mapBy('name'); // ["Yehuda Katz"]
var notKatzFilter = function(person) {
return !person.get('name').match(/Katz$/);
};
people.set('filterFunction', notKatzFilter);
people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"]
```
@method filterFunction
@param {DS.Model} record
@return {Boolean} `true` if the record should be in the array
*/
filterFunction: null,
isLoaded: true,
replace: function () {
var type = ember$data$lib$system$record$arrays$filtered$record$array$$get(this, "type").toString();
throw new Error("The result of a client-side filter (on " + type + ") is immutable.");
},
/**
@method updateFilter
@private
*/
_updateFilter: function () {
var manager = ember$data$lib$system$record$arrays$filtered$record$array$$get(this, "manager");
manager.updateFilter(this, ember$data$lib$system$record$arrays$filtered$record$array$$get(this, "type"), ember$data$lib$system$record$arrays$filtered$record$array$$get(this, "filterFunction"));
},
updateFilter: Ember.observer(function () {
Ember.run.once(this, this._updateFilter);
}, "filterFunction")
});
/**
@module ember-data
*/
var ember$data$lib$system$record$arrays$adapter$populated$record$array$$get = Ember.get;
function ember$data$lib$system$record$arrays$adapter$populated$record$array$$cloneNull(source) {
var clone = Ember.create(null);
for (var key in source) {
clone[key] = source[key];
}
return clone;
}
var ember$data$lib$system$record$arrays$adapter$populated$record$array$$default = ember$data$lib$system$record$arrays$record$array$$default.extend({
query: null,
replace: function () {
var type = ember$data$lib$system$record$arrays$adapter$populated$record$array$$get(this, "type").toString();
throw new Error("The result of a server query (on " + type + ") is immutable.");
},
/**
@method load
@private
@param {Array} data
*/
load: function (data) {
var store = ember$data$lib$system$record$arrays$adapter$populated$record$array$$get(this, "store");
var type = ember$data$lib$system$record$arrays$adapter$populated$record$array$$get(this, "type");
var modelName = type.modelName;
var records = store.pushMany(modelName, data);
var meta = store.metadataFor(modelName);
//TODO Optimize
var internalModels = Ember.A(records).mapBy("_internalModel");
this.setProperties({
content: Ember.A(internalModels),
isLoaded: true,
meta: ember$data$lib$system$record$arrays$adapter$populated$record$array$$cloneNull(meta)
});
internalModels.forEach(function (record) {
this.manager.recordArraysForRecord(record).add(this);
}, this);
// TODO: should triggering didLoad event be the last action of the runLoop?
Ember.run.once(this, "trigger", "didLoad");
}
});
var ember$data$lib$system$ordered$set$$EmberOrderedSet = Ember.OrderedSet;
var ember$data$lib$system$ordered$set$$guidFor = Ember.guidFor;
var ember$data$lib$system$ordered$set$$OrderedSet = function () {
this._super$constructor();
};
ember$data$lib$system$ordered$set$$OrderedSet.create = function () {
var Constructor = this;
return new Constructor();
};
ember$data$lib$system$ordered$set$$OrderedSet.prototype = Ember.create(ember$data$lib$system$ordered$set$$EmberOrderedSet.prototype);
ember$data$lib$system$ordered$set$$OrderedSet.prototype.constructor = ember$data$lib$system$ordered$set$$OrderedSet;
ember$data$lib$system$ordered$set$$OrderedSet.prototype._super$constructor = ember$data$lib$system$ordered$set$$EmberOrderedSet;
ember$data$lib$system$ordered$set$$OrderedSet.prototype.addWithIndex = function (obj, idx) {
var guid = ember$data$lib$system$ordered$set$$guidFor(obj);
var presenceSet = this.presenceSet;
var list = this.list;
if (presenceSet[guid] === true) {
return;
}
presenceSet[guid] = true;
if (idx === undefined || idx == null) {
list.push(obj);
} else {
list.splice(idx, 0, obj);
}
this.size += 1;
return this;
};
var ember$data$lib$system$ordered$set$$default = ember$data$lib$system$ordered$set$$OrderedSet;
var ember$data$lib$system$record$array$manager$$get = Ember.get;
var ember$data$lib$system$record$array$manager$$forEach = Ember.EnumerableUtils.forEach;
var ember$data$lib$system$record$array$manager$$indexOf = Ember.EnumerableUtils.indexOf;
var ember$data$lib$system$record$array$manager$$default = Ember.Object.extend({
init: function () {
this.filteredRecordArrays = ember$data$lib$system$map$$MapWithDefault.create({
defaultValue: function () {
return [];
}
});
this.changedRecords = [];
this._adapterPopulatedRecordArrays = [];
},
recordDidChange: function (record) {
if (this.changedRecords.push(record) !== 1) {
return;
}
Ember.run.schedule("actions", this, this.updateRecordArrays);
},
recordArraysForRecord: function (record) {
record._recordArrays = record._recordArrays || ember$data$lib$system$ordered$set$$default.create();
return record._recordArrays;
},
/**
This method is invoked whenever data is loaded into the store by the
adapter or updated by the adapter, or when a record has changed.
It updates all record arrays that a record belongs to.
To avoid thrashing, it only runs at most once per run loop.
@method updateRecordArrays
*/
updateRecordArrays: function () {
ember$data$lib$system$record$array$manager$$forEach(this.changedRecords, function (record) {
if (record.isDeleted()) {
this._recordWasDeleted(record);
} else {
this._recordWasChanged(record);
}
}, this);
this.changedRecords.length = 0;
},
_recordWasDeleted: function (record) {
var recordArrays = record._recordArrays;
if (!recordArrays) {
return;
}
recordArrays.forEach(function (array) {
array.removeInternalModel(record);
});
record._recordArrays = null;
},
//Don't need to update non filtered arrays on simple changes
_recordWasChanged: function (record) {
var typeClass = record.type;
var recordArrays = this.filteredRecordArrays.get(typeClass);
var filter;
ember$data$lib$system$record$array$manager$$forEach(recordArrays, function (array) {
filter = ember$data$lib$system$record$array$manager$$get(array, "filterFunction");
if (filter) {
this.updateRecordArray(array, filter, typeClass, record);
}
}, this);
},
//Need to update live arrays on loading
recordWasLoaded: function (record) {
var typeClass = record.type;
var recordArrays = this.filteredRecordArrays.get(typeClass);
var filter;
ember$data$lib$system$record$array$manager$$forEach(recordArrays, function (array) {
filter = ember$data$lib$system$record$array$manager$$get(array, "filterFunction");
this.updateRecordArray(array, filter, typeClass, record);
}, this);
},
/**
Update an individual filter.
@method updateRecordArray
@param {DS.FilteredRecordArray} array
@param {Function} filter
@param {DS.Model} typeClass
@param {InternalModel} record
*/
updateRecordArray: function (array, filter, typeClass, record) {
var shouldBeInArray;
if (!filter) {
shouldBeInArray = true;
} else {
shouldBeInArray = filter(record.getRecord());
}
var recordArrays = this.recordArraysForRecord(record);
if (shouldBeInArray) {
if (!recordArrays.has(array)) {
array.addInternalModel(record);
recordArrays.add(array);
}
} else if (!shouldBeInArray) {
recordArrays["delete"](array);
array.removeInternalModel(record);
}
},
/**
This method is invoked if the `filterFunction` property is
changed on a `DS.FilteredRecordArray`.
It essentially re-runs the filter from scratch. This same
method is invoked when the filter is created in th first place.
@method updateFilter
@param {Array} array
@param {String} modelName
@param {Function} filter
*/
updateFilter: function (array, modelName, filter) {
var typeMap = this.store.typeMapFor(modelName);
var records = typeMap.records;
var record;
for (var i = 0, l = records.length; i < l; i++) {
record = records[i];
if (!record.isDeleted() && !record.isEmpty()) {
this.updateRecordArray(array, filter, modelName, record);
}
}
},
/**
Create a `DS.RecordArray` for a type and register it for updates.
@method createRecordArray
@param {Class} typeClass
@return {DS.RecordArray}
*/
createRecordArray: function (typeClass) {
var array = ember$data$lib$system$record$arrays$record$array$$default.create({
type: typeClass,
content: Ember.A(),
store: this.store,
isLoaded: true,
manager: this
});
this.registerFilteredRecordArray(array, typeClass);
return array;
},
/**
Create a `DS.FilteredRecordArray` for a type and register it for updates.
@method createFilteredRecordArray
@param {DS.Model} typeClass
@param {Function} filter
@param {Object} query (optional
@return {DS.FilteredRecordArray}
*/
createFilteredRecordArray: function (typeClass, filter, query) {
var array = ember$data$lib$system$record$arrays$filtered$record$array$$default.create({
query: query,
type: typeClass,
content: Ember.A(),
store: this.store,
manager: this,
filterFunction: filter
});
this.registerFilteredRecordArray(array, typeClass, filter);
return array;
},
/**
Create a `DS.AdapterPopulatedRecordArray` for a type with given query.
@method createAdapterPopulatedRecordArray
@param {DS.Model} typeClass
@param {Object} query
@return {DS.AdapterPopulatedRecordArray}
*/
createAdapterPopulatedRecordArray: function (typeClass, query) {
var array = ember$data$lib$system$record$arrays$adapter$populated$record$array$$default.create({
type: typeClass,
query: query,
content: Ember.A(),
store: this.store,
manager: this
});
this._adapterPopulatedRecordArrays.push(array);
return array;
},
/**
Register a RecordArray for a given type to be backed by
a filter function. This will cause the array to update
automatically when records of that type change attribute
values or states.
@method registerFilteredRecordArray
@param {DS.RecordArray} array
@param {DS.Model} typeClass
@param {Function} filter
*/
registerFilteredRecordArray: function (array, typeClass, filter) {
var recordArrays = this.filteredRecordArrays.get(typeClass);
recordArrays.push(array);
this.updateFilter(array, typeClass, filter);
},
/**
Unregister a FilteredRecordArray.
So manager will not update this array.
@method unregisterFilteredRecordArray
@param {DS.RecordArray} array
*/
unregisterFilteredRecordArray: function (array) {
var recordArrays = this.filteredRecordArrays.get(array.type);
var index = ember$data$lib$system$record$array$manager$$indexOf(recordArrays, array);
recordArrays.splice(index, 1);
},
willDestroy: function () {
this._super.apply(this, arguments);
this.filteredRecordArrays.forEach(function (value) {
ember$data$lib$system$record$array$manager$$forEach(ember$data$lib$system$record$array$manager$$flatten(value), ember$data$lib$system$record$array$manager$$destroy);
});
ember$data$lib$system$record$array$manager$$forEach(this._adapterPopulatedRecordArrays, ember$data$lib$system$record$array$manager$$destroy);
}
});
function ember$data$lib$system$record$array$manager$$destroy(entry) {
entry.destroy();
}
function ember$data$lib$system$record$array$manager$$flatten(list) {
var length = list.length;
var result = Ember.A();
for (var i = 0; i < length; i++) {
result = result.concat(list[i]);
}
return result;
}
/**
* The `ContainerInstanceCache` serves as a lazy cache for looking up
* instances of serializers and adapters. It has some additional logic for
* finding the 'fallback' adapter or serializer.
*
* The 'fallback' adapter or serializer is an adapter or serializer that is looked up
* when the preferred lookup fails. For example, say you try to look up `adapter:post`,
* but there is no entry (app/adapters/post.js in EmberCLI) for `adapter:post` in the registry.
*
* The `fallbacks` array passed will then be used; the first entry in the fallbacks array
* that exists in the container will then be cached for `adapter:post`. So, the next time you
* look up `adapter:post`, you'll get the `adapter:application` instance (or whatever the fallback
* was if `adapter:application` doesn't exist).
*
* @private
* @class ContainerInstanceCache
*
*/
function ember$data$lib$system$store$container$instance$cache$$ContainerInstanceCache(container) {
this._container = container;
this._cache = ember$lib$main$$default.create(null);
}
ember$data$lib$system$store$container$instance$cache$$ContainerInstanceCache.prototype = ember$lib$main$$default.create(null);
ember$lib$main$$default.merge(ember$data$lib$system$store$container$instance$cache$$ContainerInstanceCache.prototype, {
get: function (type, preferredKey, fallbacks) {
var cache = this._cache;
var preferredLookupKey = '' + type + ':' + preferredKey;
if (!(preferredLookupKey in cache)) {
var instance = this.instanceFor(preferredLookupKey) || this._findInstance(type, fallbacks);
if (instance) {
cache[preferredLookupKey] = instance;
}
}
return cache[preferredLookupKey];
},
_findInstance: function (type, fallbacks) {
for (var i = 0, _length = fallbacks.length; i < _length; i++) {
var fallback = fallbacks[i];
var lookupKey = '' + type + ':' + fallback;
var instance = this.instanceFor(lookupKey);
if (instance) {
return instance;
}
}
},
instanceFor: function (key) {
var cache = this._cache;
if (!cache[key]) {
var instance = this._container.lookup(key);
if (instance) {
cache[key] = instance;
}
}
return cache[key];
},
destroy: function () {
var cache = this._cache;
var cacheEntries = ember$lib$main$$default.keys(cache);
for (var i = 0, _length2 = cacheEntries.length; i < _length2; i++) {
var cacheKey = cacheEntries[i];
var cacheEntry = cache[cacheKey];
if (cacheEntry) {
cacheEntry.destroy();
}
}
this._container = null;
},
constructor: ember$data$lib$system$store$container$instance$cache$$ContainerInstanceCache,
toString: function () {
return 'ContainerInstanceCache';
}
});
var ember$data$lib$system$store$container$instance$cache$$default = ember$data$lib$system$store$container$instance$cache$$ContainerInstanceCache;
function ember$data$lib$system$merge$$merge(original, updates) {
if (!updates || typeof updates !== 'object') {
return original;
}
var props = Ember.keys(updates);
var prop;
var length = props.length;
for (var i = 0; i < length; i++) {
prop = props[i];
original[prop] = updates[prop];
}
return original;
}
var ember$data$lib$system$merge$$default = ember$data$lib$system$merge$$merge;
var ember$data$lib$system$model$states$$get = Ember.get;
/*
This file encapsulates the various states that a record can transition
through during its lifecycle.
*/
/**
### State
Each record has a `currentState` property that explicitly tracks what
state a record is in at any given time. For instance, if a record is
newly created and has not yet been sent to the adapter to be saved,
it would be in the `root.loaded.created.uncommitted` state. If a
record has had local modifications made to it that are in the
process of being saved, the record would be in the
`root.loaded.updated.inFlight` state. (This state paths will be
explained in more detail below.)
Events are sent by the record or its store to the record's
`currentState` property. How the state reacts to these events is
dependent on which state it is in. In some states, certain events
will be invalid and will cause an exception to be raised.
States are hierarchical and every state is a substate of the
`RootState`. For example, a record can be in the
`root.deleted.uncommitted` state, then transition into the
`root.deleted.inFlight` state. If a child state does not implement
an event handler, the state manager will attempt to invoke the event
on all parent states until the root state is reached. The state
hierarchy of a record is described in terms of a path string. You
can determine a record's current state by getting the state's
`stateName` property:
```javascript
record.get('currentState.stateName');
//=> "root.created.uncommitted"
```
The hierarchy of valid states that ship with ember data looks like
this:
```text
* root
* deleted
* saved
* uncommitted
* inFlight
* empty
* loaded
* created
* uncommitted
* inFlight
* saved
* updated
* uncommitted
* inFlight
* loading
```
The `DS.Model` states are themselves stateless. What that means is
that, the hierarchical states that each of *those* points to is a
shared data structure. For performance reasons, instead of each
record getting its own copy of the hierarchy of states, each record
points to this global, immutable shared instance. How does a state
know which record it should be acting on? We pass the record
instance into the state's event handlers as the first argument.
The record passed as the first parameter is where you should stash
state about the record if needed; you should never store data on the state
object itself.
### Events and Flags
A state may implement zero or more events and flags.
#### Events
Events are named functions that are invoked when sent to a record. The
record will first look for a method with the given name on the
current state. If no method is found, it will search the current
state's parent, and then its grandparent, and so on until reaching
the top of the hierarchy. If the root is reached without an event
handler being found, an exception will be raised. This can be very
helpful when debugging new features.
Here's an example implementation of a state with a `myEvent` event handler:
```javascript
aState: DS.State.create({
myEvent: function(manager, param) {
console.log("Received myEvent with", param);
}
})
```
To trigger this event:
```javascript
record.send('myEvent', 'foo');
//=> "Received myEvent with foo"
```
Note that an optional parameter can be sent to a record's `send()` method,
which will be passed as the second parameter to the event handler.
Events should transition to a different state if appropriate. This can be
done by calling the record's `transitionTo()` method with a path to the
desired state. The state manager will attempt to resolve the state path
relative to the current state. If no state is found at that path, it will
attempt to resolve it relative to the current state's parent, and then its
parent, and so on until the root is reached. For example, imagine a hierarchy
like this:
* created
* uncommitted <-- currentState
* inFlight
* updated
* inFlight
If we are currently in the `uncommitted` state, calling
`transitionTo('inFlight')` would transition to the `created.inFlight` state,
while calling `transitionTo('updated.inFlight')` would transition to
the `updated.inFlight` state.
Remember that *only events* should ever cause a state transition. You should
never call `transitionTo()` from outside a state's event handler. If you are
tempted to do so, create a new event and send that to the state manager.
#### Flags
Flags are Boolean values that can be used to introspect a record's current
state in a more user-friendly way than examining its state path. For example,
instead of doing this:
```javascript
var statePath = record.get('stateManager.currentPath');
if (statePath === 'created.inFlight') {
doSomething();
}
```
You can say:
```javascript
if (record.get('isNew') && record.get('isSaving')) {
doSomething();
}
```
If your state does not set a value for a given flag, the value will
be inherited from its parent (or the first place in the state hierarchy
where it is defined).
The current set of flags are defined below. If you want to add a new flag,
in addition to the area below, you will also need to declare it in the
`DS.Model` class.
* [isEmpty](DS.Model.html#property_isEmpty)
* [isLoading](DS.Model.html#property_isLoading)
* [isLoaded](DS.Model.html#property_isLoaded)
* [isDirty](DS.Model.html#property_isDirty)
* [isSaving](DS.Model.html#property_isSaving)
* [isDeleted](DS.Model.html#property_isDeleted)
* [isNew](DS.Model.html#property_isNew)
* [isValid](DS.Model.html#property_isValid)
@namespace DS
@class RootState
*/
function ember$data$lib$system$model$states$$didSetProperty(internalModel, context) {
if (context.value === context.originalValue) {
delete internalModel._attributes[context.name];
internalModel.send('propertyWasReset', context.name);
} else if (context.value !== context.oldValue) {
internalModel.send('becomeDirty');
}
internalModel.updateRecordArraysLater();
}
// Implementation notes:
//
// Each state has a boolean value for all of the following flags:
//
// * isLoaded: The record has a populated `data` property. When a
// record is loaded via `store.find`, `isLoaded` is false
// until the adapter sets it. When a record is created locally,
// its `isLoaded` property is always true.
// * isDirty: The record has local changes that have not yet been
// saved by the adapter. This includes records that have been
// created (but not yet saved) or deleted.
// * isSaving: The record has been committed, but
// the adapter has not yet acknowledged that the changes have
// been persisted to the backend.
// * isDeleted: The record was marked for deletion. When `isDeleted`
// is true and `isDirty` is true, the record is deleted locally
// but the deletion was not yet persisted. When `isSaving` is
// true, the change is in-flight. When both `isDirty` and
// `isSaving` are false, the change has persisted.
// * isError: The adapter reported that it was unable to save
// local changes to the backend. This may also result in the
// record having its `isValid` property become false if the
// adapter reported that server-side validations failed.
// * isNew: The record was created on the client and the adapter
// did not yet report that it was successfully saved.
// * isValid: The adapter did not report any server-side validation
// failures.
// The dirty state is a abstract state whose functionality is
// shared between the `created` and `updated` states.
//
// The deleted state shares the `isDirty` flag with the
// subclasses of `DirtyState`, but with a very different
// implementation.
//
// Dirty states have three child states:
//
// `uncommitted`: the store has not yet handed off the record
// to be saved.
// `inFlight`: the store has handed off the record to be saved,
// but the adapter has not yet acknowledged success.
// `invalid`: the record has invalid information and cannot be
// send to the adapter yet.
var ember$data$lib$system$model$states$$DirtyState = {
initialState: 'uncommitted',
// FLAGS
isDirty: true,
// SUBSTATES
// When a record first becomes dirty, it is `uncommitted`.
// This means that there are local pending changes, but they
// have not yet begun to be saved, and are not invalid.
uncommitted: {
// EVENTS
didSetProperty: ember$data$lib$system$model$states$$didSetProperty,
//TODO(Igor) reloading now triggers a
//loadingData event, though it seems fine?
loadingData: Ember.K,
propertyWasReset: function (internalModel, name) {
var length = Ember.keys(internalModel._attributes).length;
var stillDirty = length > 0;
if (!stillDirty) {
internalModel.send('rolledBack');
}
},
pushedData: Ember.K,
becomeDirty: Ember.K,
willCommit: function (internalModel) {
internalModel.transitionTo('inFlight');
},
reloadRecord: function (internalModel, resolve) {
resolve(internalModel.store.reloadRecord(internalModel));
},
rolledBack: function (internalModel) {
internalModel.transitionTo('loaded.saved');
},
becameInvalid: function (internalModel) {
internalModel.transitionTo('invalid');
},
rollback: function (internalModel) {
internalModel.rollback();
internalModel.triggerLater('ready');
}
},
// Once a record has been handed off to the adapter to be
// saved, it is in the 'in flight' state. Changes to the
// record cannot be made during this window.
inFlight: {
// FLAGS
isSaving: true,
// EVENTS
didSetProperty: ember$data$lib$system$model$states$$didSetProperty,
becomeDirty: Ember.K,
pushedData: Ember.K,
unloadRecord: ember$data$lib$system$model$states$$assertAgainstUnloadRecord,
// TODO: More robust semantics around save-while-in-flight
willCommit: Ember.K,
didCommit: function (internalModel) {
var dirtyType = ember$data$lib$system$model$states$$get(this, 'dirtyType');
internalModel.transitionTo('saved');
internalModel.send('invokeLifecycleCallbacks', dirtyType);
},
becameInvalid: function (internalModel) {
internalModel.transitionTo('invalid');
internalModel.send('invokeLifecycleCallbacks');
},
becameError: function (internalModel) {
internalModel.transitionTo('uncommitted');
internalModel.triggerLater('becameError', internalModel);
}
},
// A record is in the `invalid` if the adapter has indicated
// the the record failed server-side invalidations.
invalid: {
// FLAGS
isValid: false,
// EVENTS
deleteRecord: function (internalModel) {
internalModel.transitionTo('deleted.uncommitted');
internalModel.disconnectRelationships();
},
didSetProperty: function (internalModel, context) {
internalModel.getErrors().remove(context.name);
ember$data$lib$system$model$states$$didSetProperty(internalModel, context);
},
becomeDirty: Ember.K,
pushedData: Ember.K,
willCommit: function (internalModel) {
internalModel.getErrors().clear();
internalModel.transitionTo('inFlight');
},
rolledBack: function (internalModel) {
internalModel.getErrors().clear();
internalModel.triggerLater('ready');
},
becameValid: function (internalModel) {
internalModel.transitionTo('uncommitted');
},
invokeLifecycleCallbacks: function (internalModel) {
internalModel.triggerLater('becameInvalid', internalModel);
},
exit: function (internalModel) {
internalModel._inFlightAttributes = Ember.create(null);
}
}
};
// The created and updated states are created outside the state
// chart so we can reopen their substates and add mixins as
// necessary.
function ember$data$lib$system$model$states$$deepClone(object) {
var clone = {};
var value;
for (var prop in object) {
value = object[prop];
if (value && typeof value === 'object') {
clone[prop] = ember$data$lib$system$model$states$$deepClone(value);
} else {
clone[prop] = value;
}
}
return clone;
}
function ember$data$lib$system$model$states$$mixin(original, hash) {
for (var prop in hash) {
original[prop] = hash[prop];
}
return original;
}
function ember$data$lib$system$model$states$$dirtyState(options) {
var newState = ember$data$lib$system$model$states$$deepClone(ember$data$lib$system$model$states$$DirtyState);
return ember$data$lib$system$model$states$$mixin(newState, options);
}
var ember$data$lib$system$model$states$$createdState = ember$data$lib$system$model$states$$dirtyState({
dirtyType: 'created',
// FLAGS
isNew: true
});
ember$data$lib$system$model$states$$createdState.invalid.rolledBack = function (internalModel) {
internalModel.transitionTo('deleted.saved');
};
ember$data$lib$system$model$states$$createdState.uncommitted.rolledBack = function (internalModel) {
internalModel.transitionTo('deleted.saved');
};
var ember$data$lib$system$model$states$$updatedState = ember$data$lib$system$model$states$$dirtyState({
dirtyType: 'updated'
});
ember$data$lib$system$model$states$$createdState.uncommitted.deleteRecord = function (internalModel) {
internalModel.disconnectRelationships();
internalModel.transitionTo('deleted.saved');
internalModel.send('invokeLifecycleCallbacks');
};
ember$data$lib$system$model$states$$createdState.uncommitted.rollback = function (internalModel) {
ember$data$lib$system$model$states$$DirtyState.uncommitted.rollback.apply(this, arguments);
internalModel.transitionTo('deleted.saved');
};
ember$data$lib$system$model$states$$createdState.uncommitted.pushedData = function (internalModel) {
internalModel.transitionTo('loaded.updated.uncommitted');
internalModel.triggerLater('didLoad');
};
ember$data$lib$system$model$states$$createdState.uncommitted.propertyWasReset = Ember.K;
function ember$data$lib$system$model$states$$assertAgainstUnloadRecord(internalModel) {
}
ember$data$lib$system$model$states$$updatedState.inFlight.unloadRecord = ember$data$lib$system$model$states$$assertAgainstUnloadRecord;
ember$data$lib$system$model$states$$updatedState.uncommitted.deleteRecord = function (internalModel) {
internalModel.transitionTo('deleted.uncommitted');
internalModel.disconnectRelationships();
};
var ember$data$lib$system$model$states$$RootState = {
// FLAGS
isEmpty: false,
isLoading: false,
isLoaded: false,
isDirty: false,
isSaving: false,
isDeleted: false,
isNew: false,
isValid: true,
// DEFAULT EVENTS
// Trying to roll back if you're not in the dirty state
// doesn't change your state. For example, if you're in the
// in-flight state, rolling back the record doesn't move
// you out of the in-flight state.
rolledBack: Ember.K,
unloadRecord: function (internalModel) {
// clear relationships before moving to deleted state
// otherwise it fails
internalModel.clearRelationships();
internalModel.transitionTo('deleted.saved');
},
propertyWasReset: Ember.K,
// SUBSTATES
// A record begins its lifecycle in the `empty` state.
// If its data will come from the adapter, it will
// transition into the `loading` state. Otherwise, if
// the record is being created on the client, it will
// transition into the `created` state.
empty: {
isEmpty: true,
// EVENTS
loadingData: function (internalModel, promise) {
internalModel._loadingPromise = promise;
internalModel.transitionTo('loading');
},
loadedData: function (internalModel) {
internalModel.transitionTo('loaded.created.uncommitted');
internalModel.triggerLater('ready');
},
pushedData: function (internalModel) {
internalModel.transitionTo('loaded.saved');
internalModel.triggerLater('didLoad');
internalModel.triggerLater('ready');
}
},
// A record enters this state when the store asks
// the adapter for its data. It remains in this state
// until the adapter provides the requested data.
//
// Usually, this process is asynchronous, using an
// XHR to retrieve the data.
loading: {
// FLAGS
isLoading: true,
exit: function (internalModel) {
internalModel._loadingPromise = null;
},
// EVENTS
pushedData: function (internalModel) {
internalModel.transitionTo('loaded.saved');
internalModel.triggerLater('didLoad');
internalModel.triggerLater('ready');
//TODO this seems out of place here
internalModel.didCleanError();
},
becameError: function (internalModel) {
internalModel.triggerLater('becameError', internalModel);
},
notFound: function (internalModel) {
internalModel.transitionTo('empty');
}
},
// A record enters this state when its data is populated.
// Most of a record's lifecycle is spent inside substates
// of the `loaded` state.
loaded: {
initialState: 'saved',
// FLAGS
isLoaded: true,
//TODO(Igor) Reloading now triggers a loadingData event,
//but it should be ok?
loadingData: Ember.K,
// SUBSTATES
// If there are no local changes to a record, it remains
// in the `saved` state.
saved: {
setup: function (internalModel) {
var attrs = internalModel._attributes;
var isDirty = Ember.keys(attrs).length > 0;
if (isDirty) {
internalModel.adapterDidDirty();
}
},
// EVENTS
didSetProperty: ember$data$lib$system$model$states$$didSetProperty,
pushedData: Ember.K,
becomeDirty: function (internalModel) {
internalModel.transitionTo('updated.uncommitted');
},
willCommit: function (internalModel) {
internalModel.transitionTo('updated.inFlight');
},
reloadRecord: function (internalModel, resolve) {
resolve(internalModel.store.reloadRecord(internalModel));
},
deleteRecord: function (internalModel) {
internalModel.transitionTo('deleted.uncommitted');
internalModel.disconnectRelationships();
},
unloadRecord: function (internalModel) {
// clear relationships before moving to deleted state
// otherwise it fails
internalModel.clearRelationships();
internalModel.transitionTo('deleted.saved');
},
didCommit: function (internalModel) {
internalModel.send('invokeLifecycleCallbacks', ember$data$lib$system$model$states$$get(internalModel, 'lastDirtyType'));
},
// loaded.saved.notFound would be triggered by a failed
// `reload()` on an unchanged record
notFound: Ember.K
},
// A record is in this state after it has been locally
// created but before the adapter has indicated that
// it has been saved.
created: ember$data$lib$system$model$states$$createdState,
// A record is in this state if it has already been
// saved to the server, but there are new local changes
// that have not yet been saved.
updated: ember$data$lib$system$model$states$$updatedState
},
// A record is in this state if it was deleted from the store.
deleted: {
initialState: 'uncommitted',
dirtyType: 'deleted',
// FLAGS
isDeleted: true,
isLoaded: true,
isDirty: true,
// TRANSITIONS
setup: function (internalModel) {
internalModel.updateRecordArrays();
},
// SUBSTATES
// When a record is deleted, it enters the `start`
// state. It will exit this state when the record
// starts to commit.
uncommitted: {
// EVENTS
willCommit: function (internalModel) {
internalModel.transitionTo('inFlight');
},
rollback: function (internalModel) {
internalModel.rollback();
internalModel.triggerLater('ready');
},
pushedData: Ember.K,
becomeDirty: Ember.K,
deleteRecord: Ember.K,
rolledBack: function (internalModel) {
internalModel.transitionTo('loaded.saved');
internalModel.triggerLater('ready');
}
},
// After a record starts committing, but
// before the adapter indicates that the deletion
// has saved to the server, a record is in the
// `inFlight` substate of `deleted`.
inFlight: {
// FLAGS
isSaving: true,
// EVENTS
unloadRecord: ember$data$lib$system$model$states$$assertAgainstUnloadRecord,
// TODO: More robust semantics around save-while-in-flight
willCommit: Ember.K,
didCommit: function (internalModel) {
internalModel.transitionTo('saved');
internalModel.send('invokeLifecycleCallbacks');
},
becameError: function (internalModel) {
internalModel.transitionTo('uncommitted');
internalModel.triggerLater('becameError', internalModel);
},
becameInvalid: function (internalModel) {
internalModel.transitionTo('invalid');
internalModel.triggerLater('becameInvalid', internalModel);
}
},
// Once the adapter indicates that the deletion has
// been saved, the record enters the `saved` substate
// of `deleted`.
saved: {
// FLAGS
isDirty: false,
setup: function (internalModel) {
var store = internalModel.store;
store._dematerializeRecord(internalModel);
},
invokeLifecycleCallbacks: function (internalModel) {
internalModel.triggerLater('didDelete', internalModel);
internalModel.triggerLater('didCommit', internalModel);
},
willCommit: Ember.K,
didCommit: Ember.K
},
invalid: {
isValid: false,
didSetProperty: function (internalModel, context) {
internalModel.getErrors().remove(context.name);
ember$data$lib$system$model$states$$didSetProperty(internalModel, context);
},
deleteRecord: Ember.K,
becomeDirty: Ember.K,
willCommit: Ember.K,
rolledBack: function (internalModel) {
internalModel.getErrors().clear();
internalModel.transitionTo('loaded.saved');
internalModel.triggerLater('ready');
},
becameValid: function (internalModel) {
internalModel.transitionTo('uncommitted');
}
}
},
invokeLifecycleCallbacks: function (internalModel, dirtyType) {
if (dirtyType === 'created') {
internalModel.triggerLater('didCreate', internalModel);
} else {
internalModel.triggerLater('didUpdate', internalModel);
}
internalModel.triggerLater('didCommit', internalModel);
}
};
function ember$data$lib$system$model$states$$wireState(object, parent, name) {
/*jshint proto:true*/
// TODO: Use Object.create and copy instead
object = ember$data$lib$system$model$states$$mixin(parent ? Ember.create(parent) : {}, object);
object.parentState = parent;
object.stateName = name;
for (var prop in object) {
if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') {
continue;
}
if (typeof object[prop] === 'object') {
object[prop] = ember$data$lib$system$model$states$$wireState(object[prop], object, name + '.' + prop);
}
}
return object;
}
ember$data$lib$system$model$states$$RootState = ember$data$lib$system$model$states$$wireState(ember$data$lib$system$model$states$$RootState, null, 'root');
var ember$data$lib$system$model$states$$default = ember$data$lib$system$model$states$$RootState;
var ember$data$lib$system$relationships$state$relationship$$forEach = Ember.EnumerableUtils.forEach;
function ember$data$lib$system$relationships$state$relationship$$Relationship(store, record, inverseKey, relationshipMeta) {
this.members = new ember$data$lib$system$ordered$set$$default();
this.canonicalMembers = new ember$data$lib$system$ordered$set$$default();
this.store = store;
this.key = relationshipMeta.key;
this.inverseKey = inverseKey;
this.record = record;
this.isAsync = relationshipMeta.options.async;
this.relationshipMeta = relationshipMeta;
//This probably breaks for polymorphic relationship in complex scenarios, due to
//multiple possible modelNames
this.inverseKeyForImplicit = this.record.constructor.modelName + this.key;
this.linkPromise = null;
this.hasData = false;
}
ember$data$lib$system$relationships$state$relationship$$Relationship.prototype = {
constructor: ember$data$lib$system$relationships$state$relationship$$Relationship,
destroy: Ember.K,
clear: function () {
var members = this.members.list;
var member;
while (members.length > 0) {
member = members[0];
this.removeRecord(member);
}
},
disconnect: function () {
this.members.forEach(function (member) {
this.removeRecordFromInverse(member);
}, this);
},
reconnect: function () {
this.members.forEach(function (member) {
this.addRecordToInverse(member);
}, this);
},
removeRecords: function (records) {
var self = this;
ember$data$lib$system$relationships$state$relationship$$forEach(records, function (record) {
self.removeRecord(record);
});
},
addRecords: function (records, idx) {
var self = this;
ember$data$lib$system$relationships$state$relationship$$forEach(records, function (record) {
self.addRecord(record, idx);
if (idx !== undefined) {
idx++;
}
});
},
addCanonicalRecords: function (records, idx) {
for (var i = 0; i < records.length; i++) {
if (idx !== undefined) {
this.addCanonicalRecord(records[i], i + idx);
} else {
this.addCanonicalRecord(records[i]);
}
}
},
addCanonicalRecord: function (record, idx) {
if (!this.canonicalMembers.has(record)) {
this.canonicalMembers.add(record);
if (this.inverseKey) {
record._relationships.get(this.inverseKey).addCanonicalRecord(this.record);
} else {
if (!record._implicitRelationships[this.inverseKeyForImplicit]) {
record._implicitRelationships[this.inverseKeyForImplicit] = new ember$data$lib$system$relationships$state$relationship$$Relationship(this.store, record, this.key, { options: {} });
}
record._implicitRelationships[this.inverseKeyForImplicit].addCanonicalRecord(this.record);
}
}
this.flushCanonicalLater();
this.setHasData(true);
},
removeCanonicalRecords: function (records, idx) {
for (var i = 0; i < records.length; i++) {
if (idx !== undefined) {
this.removeCanonicalRecord(records[i], i + idx);
} else {
this.removeCanonicalRecord(records[i]);
}
}
},
removeCanonicalRecord: function (record, idx) {
if (this.canonicalMembers.has(record)) {
this.removeCanonicalRecordFromOwn(record);
if (this.inverseKey) {
this.removeCanonicalRecordFromInverse(record);
} else {
if (record._implicitRelationships[this.inverseKeyForImplicit]) {
record._implicitRelationships[this.inverseKeyForImplicit].removeCanonicalRecord(this.record);
}
}
}
this.flushCanonicalLater();
},
addRecord: function (record, idx) {
if (!this.members.has(record)) {
this.members.addWithIndex(record, idx);
this.notifyRecordRelationshipAdded(record, idx);
if (this.inverseKey) {
record._relationships.get(this.inverseKey).addRecord(this.record);
} else {
if (!record._implicitRelationships[this.inverseKeyForImplicit]) {
record._implicitRelationships[this.inverseKeyForImplicit] = new ember$data$lib$system$relationships$state$relationship$$Relationship(this.store, record, this.key, { options: {} });
}
record._implicitRelationships[this.inverseKeyForImplicit].addRecord(this.record);
}
this.record.updateRecordArraysLater();
}
this.setHasData(true);
},
removeRecord: function (record) {
if (this.members.has(record)) {
this.removeRecordFromOwn(record);
if (this.inverseKey) {
this.removeRecordFromInverse(record);
} else {
if (record._implicitRelationships[this.inverseKeyForImplicit]) {
record._implicitRelationships[this.inverseKeyForImplicit].removeRecord(this.record);
}
}
}
},
addRecordToInverse: function (record) {
if (this.inverseKey) {
record._relationships.get(this.inverseKey).addRecord(this.record);
}
},
removeRecordFromInverse: function (record) {
var inverseRelationship = record._relationships.get(this.inverseKey);
//Need to check for existence, as the record might unloading at the moment
if (inverseRelationship) {
inverseRelationship.removeRecordFromOwn(this.record);
}
},
removeRecordFromOwn: function (record) {
this.members["delete"](record);
this.notifyRecordRelationshipRemoved(record);
this.record.updateRecordArrays();
},
removeCanonicalRecordFromInverse: function (record) {
var inverseRelationship = record._relationships.get(this.inverseKey);
//Need to check for existence, as the record might unloading at the moment
if (inverseRelationship) {
inverseRelationship.removeCanonicalRecordFromOwn(this.record);
}
},
removeCanonicalRecordFromOwn: function (record) {
this.canonicalMembers["delete"](record);
this.flushCanonicalLater();
},
flushCanonical: function () {
this.willSync = false;
//a hack for not removing new records
//TODO remove once we have proper diffing
var newRecords = [];
for (var i = 0; i < this.members.list.length; i++) {
if (this.members.list[i].isNew()) {
newRecords.push(this.members.list[i]);
}
}
//TODO(Igor) make this less abysmally slow
this.members = this.canonicalMembers.copy();
for (i = 0; i < newRecords.length; i++) {
this.members.add(newRecords[i]);
}
},
flushCanonicalLater: function () {
if (this.willSync) {
return;
}
this.willSync = true;
var self = this;
this.store._backburner.join(function () {
self.store._backburner.schedule("syncRelationships", self, self.flushCanonical);
});
},
updateLink: function (link) {
if (link !== this.link) {
this.link = link;
this.linkPromise = null;
this.record.notifyPropertyChange(this.key);
}
},
findLink: function () {
if (this.linkPromise) {
return this.linkPromise;
} else {
var promise = this.fetchLink();
this.linkPromise = promise;
return promise.then(function (result) {
return result;
});
}
},
updateRecordsFromAdapter: function (records) {
//TODO(Igor) move this to a proper place
var self = this;
//TODO Once we have adapter support, we need to handle updated and canonical changes
self.computeChanges(records);
self.setHasData(true);
},
notifyRecordRelationshipAdded: Ember.K,
notifyRecordRelationshipRemoved: Ember.K,
setHasData: function (value) {
this.hasData = value;
}
};
var ember$data$lib$system$relationships$state$relationship$$default = ember$data$lib$system$relationships$state$relationship$$Relationship;
var ember$data$lib$system$many$array$$get = Ember.get;
var ember$data$lib$system$many$array$$set = Ember.set;
var ember$data$lib$system$many$array$$filter = Ember.ArrayPolyfills.filter;
var ember$data$lib$system$many$array$$map = Ember.EnumerableUtils.map;
var ember$data$lib$system$many$array$$default = Ember.Object.extend(Ember.MutableArray, Ember.Evented, {
init: function () {
this.currentState = Ember.A([]);
},
record: null,
canonicalState: null,
currentState: null,
length: 0,
objectAt: function (index) {
//Ember observers such as 'firstObject', 'lastObject' might do out of bounds accesses
if (!this.currentState[index]) {
return undefined;
}
return this.currentState[index].getRecord();
},
flushCanonical: function () {
//TODO make this smarter, currently its plenty stupid
var toSet = ember$data$lib$system$many$array$$filter.call(this.canonicalState, function (internalModel) {
return !internalModel.isDeleted();
});
//a hack for not removing new records
//TODO remove once we have proper diffing
var newRecords = this.currentState.filter(function (internalModel) {
return internalModel.isNew();
});
toSet = toSet.concat(newRecords);
var oldLength = this.length;
this.arrayContentWillChange(0, this.length, toSet.length);
this.set('length', toSet.length);
this.currentState = toSet;
this.arrayContentDidChange(0, oldLength, this.length);
//TODO Figure out to notify only on additions and maybe only if unloaded
this.relationship.notifyHasManyChanged();
this.record.updateRecordArrays();
},
/**
`true` if the relationship is polymorphic, `false` otherwise.
@property {Boolean} isPolymorphic
@private
*/
isPolymorphic: false,
/**
The loading state of this array
@property {Boolean} isLoaded
*/
isLoaded: false,
/**
The relationship which manages this array.
@property {ManyRelationship} relationship
@private
*/
relationship: null,
internalReplace: function (idx, amt, objects) {
if (!objects) {
objects = [];
}
this.arrayContentWillChange(idx, amt, objects.length);
this.currentState.splice.apply(this.currentState, [idx, amt].concat(objects));
this.set('length', this.currentState.length);
this.arrayContentDidChange(idx, amt, objects.length);
if (objects) {
//TODO(Igor) probably needed only for unloaded records
this.relationship.notifyHasManyChanged();
}
this.record.updateRecordArrays();
},
//TODO(Igor) optimize
internalRemoveRecords: function (records) {
var index;
for (var i = 0; i < records.length; i++) {
index = this.currentState.indexOf(records[i]);
this.internalReplace(index, 1);
}
},
//TODO(Igor) optimize
internalAddRecords: function (records, idx) {
if (idx === undefined) {
idx = this.currentState.length;
}
this.internalReplace(idx, 0, records);
},
replace: function (idx, amt, objects) {
var records;
if (amt > 0) {
records = this.currentState.slice(idx, idx + amt);
this.get('relationship').removeRecords(records);
}
if (objects) {
this.get('relationship').addRecords(ember$data$lib$system$many$array$$map(objects, function (obj) {
return obj._internalModel;
}), idx);
}
},
/**
Used for async `hasMany` arrays
to keep track of when they will resolve.
@property {Ember.RSVP.Promise} promise
@private
*/
promise: null,
/**
@method loadingRecordsCount
@param {Number} count
@private
*/
loadingRecordsCount: function (count) {
this.loadingRecordsCount = count;
},
/**
@method loadedRecord
@private
*/
loadedRecord: function () {
this.loadingRecordsCount--;
if (this.loadingRecordsCount === 0) {
ember$data$lib$system$many$array$$set(this, 'isLoaded', true);
this.trigger('didLoad');
}
},
/**
@method reload
@public
*/
reload: function () {
return this.relationship.reload();
},
/**
Saves all of the records in the `ManyArray`.
Example
```javascript
store.find('inbox', 1).then(function(inbox) {
inbox.get('messages').then(function(messages) {
messages.forEach(function(message) {
message.set('isRead', true);
});
messages.save()
});
});
```
@method save
@return {DS.PromiseArray} promise
*/
save: function () {
var manyArray = this;
var promiseLabel = 'DS: ManyArray#save ' + ember$data$lib$system$many$array$$get(this, 'type');
var promise = Ember.RSVP.all(this.invoke('save'), promiseLabel).then(function (array) {
return manyArray;
}, null, 'DS: ManyArray#save return ManyArray');
return ember$data$lib$system$promise$proxies$$PromiseArray.create({ promise: promise });
},
/**
Create a child record within the owner
@method createRecord
@private
@param {Object} hash
@return {DS.Model} record
*/
createRecord: function (hash) {
var store = ember$data$lib$system$many$array$$get(this, 'store');
var type = ember$data$lib$system$many$array$$get(this, 'type');
var record;
record = store.createRecord(type.modelName, hash);
this.pushObject(record);
return record;
},
/**
@method addRecord
@param {DS.Model} record
@deprecated Use `addObject()` instead
*/
addRecord: function (record) {
this.addObject(record);
},
/**
@method removeRecord
@param {DS.Model} record
@deprecated Use `removeObject()` instead
*/
removeRecord: function (record) {
this.removeObject(record);
}
});
var ember$data$lib$system$relationships$state$has$many$$map = Ember.EnumerableUtils.map;
var ember$data$lib$system$relationships$state$has$many$$ManyRelationship = function (store, record, inverseKey, relationshipMeta) {
this._super$constructor(store, record, inverseKey, relationshipMeta);
this.belongsToType = relationshipMeta.type;
this.canonicalState = [];
this.manyArray = ember$data$lib$system$many$array$$default.create({
canonicalState: this.canonicalState,
store: this.store,
relationship: this,
type: this.store.modelFor(this.belongsToType),
record: record
});
this.isPolymorphic = relationshipMeta.options.polymorphic;
this.manyArray.isPolymorphic = this.isPolymorphic;
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype = Ember.create(ember$data$lib$system$relationships$state$relationship$$default.prototype);
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.constructor = ember$data$lib$system$relationships$state$has$many$$ManyRelationship;
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$constructor = ember$data$lib$system$relationships$state$relationship$$default;
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.destroy = function () {
this.manyArray.destroy();
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$addCanonicalRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addCanonicalRecord;
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.addCanonicalRecord = function (record, idx) {
if (this.canonicalMembers.has(record)) {
return;
}
if (idx !== undefined) {
this.canonicalState.splice(idx, 0, record);
} else {
this.canonicalState.push(record);
}
this._super$addCanonicalRecord(record, idx);
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$addRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addRecord;
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.addRecord = function (record, idx) {
if (this.members.has(record)) {
return;
}
this._super$addRecord(record, idx);
this.manyArray.internalAddRecords([record], idx);
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$removeCanonicalRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeCanonicalRecordFromOwn;
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.removeCanonicalRecordFromOwn = function (record, idx) {
var i = idx;
if (!this.canonicalMembers.has(record)) {
return;
}
if (i === undefined) {
i = this.canonicalState.indexOf(record);
}
if (i > -1) {
this.canonicalState.splice(i, 1);
}
this._super$removeCanonicalRecordFromOwn(record, idx);
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$flushCanonical = ember$data$lib$system$relationships$state$relationship$$default.prototype.flushCanonical;
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.flushCanonical = function () {
this.manyArray.flushCanonical();
this._super$flushCanonical();
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype._super$removeRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeRecordFromOwn;
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.removeRecordFromOwn = function (record, idx) {
if (!this.members.has(record)) {
return;
}
this._super$removeRecordFromOwn(record, idx);
if (idx !== undefined) {
//TODO(Igor) not used currently, fix
this.manyArray.currentState.removeAt(idx);
} else {
this.manyArray.internalRemoveRecords([record]);
}
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.notifyRecordRelationshipAdded = function (record, idx) {
var typeClass = this.store.modelFor(this.relationshipMeta.type);
this.record.notifyHasManyAdded(this.key, record, idx);
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.reload = function () {
var self = this;
if (this.link) {
return this.fetchLink();
} else {
return this.store.scheduleFetchMany(this.manyArray.toArray()).then(function () {
//Goes away after the manyArray refactor
self.manyArray.set("isLoaded", true);
return self.manyArray;
});
}
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.computeChanges = function (records) {
var members = this.canonicalMembers;
var recordsToRemove = [];
var length;
var record;
var i;
records = ember$data$lib$system$relationships$state$has$many$$setForArray(records);
members.forEach(function (member) {
if (records.has(member)) {
return;
}
recordsToRemove.push(member);
});
this.removeCanonicalRecords(recordsToRemove);
// Using records.toArray() since currently using
// removeRecord can modify length, messing stuff up
// forEach since it directly looks at "length" each
// iteration
records = records.toArray();
length = records.length;
for (i = 0; i < length; i++) {
record = records[i];
this.removeCanonicalRecord(record);
this.addCanonicalRecord(record, i);
}
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.fetchLink = function () {
var self = this;
return this.store.findHasMany(this.record, this.link, this.relationshipMeta).then(function (records) {
self.store._backburner.join(function () {
self.updateRecordsFromAdapter(records);
});
return self.manyArray;
});
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.findRecords = function () {
var manyArray = this.manyArray;
//TODO CLEANUP
return this.store.findMany(ember$data$lib$system$relationships$state$has$many$$map(manyArray.toArray(), function (rec) {
return rec._internalModel;
})).then(function () {
//Goes away after the manyArray refactor
manyArray.set("isLoaded", true);
return manyArray;
});
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.notifyHasManyChanged = function () {
this.record.notifyHasManyAdded(this.key);
};
ember$data$lib$system$relationships$state$has$many$$ManyRelationship.prototype.getRecords = function () {
//TODO(Igor) sync server here, once our syncing is not stupid
if (this.isAsync) {
var self = this;
var promise;
if (this.link) {
promise = this.findLink().then(function () {
return self.findRecords();
});
} else {
promise = this.findRecords();
}
return ember$data$lib$system$promise$proxies$$PromiseManyArray.create({
content: this.manyArray,
promise: promise
});
} else {
//TODO(Igor) WTF DO I DO HERE?
if (!this.manyArray.get("isDestroyed")) {
this.manyArray.set("isLoaded", true);
}
return this.manyArray;
}
};
function ember$data$lib$system$relationships$state$has$many$$setForArray(array) {
var set = new ember$data$lib$system$ordered$set$$default();
if (array) {
for (var i = 0, l = array.length; i < l; i++) {
set.add(array[i]);
}
}
return set;
}
var ember$data$lib$system$relationships$state$has$many$$default = ember$data$lib$system$relationships$state$has$many$$ManyRelationship;
var ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship = function (store, record, inverseKey, relationshipMeta) {
this._super$constructor(store, record, inverseKey, relationshipMeta);
this.record = record;
this.key = relationshipMeta.key;
this.inverseRecord = null;
this.canonicalState = null;
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype = Ember.create(ember$data$lib$system$relationships$state$relationship$$default.prototype);
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.constructor = ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship;
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$constructor = ember$data$lib$system$relationships$state$relationship$$default;
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.setRecord = function (newRecord) {
if (newRecord) {
this.addRecord(newRecord);
} else if (this.inverseRecord) {
this.removeRecord(this.inverseRecord);
}
this.setHasData(true);
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.setCanonicalRecord = function (newRecord) {
if (newRecord) {
this.addCanonicalRecord(newRecord);
} else if (this.inverseRecord) {
this.removeCanonicalRecord(this.inverseRecord);
}
this.setHasData(true);
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$addCanonicalRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addCanonicalRecord;
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.addCanonicalRecord = function (newRecord) {
if (this.canonicalMembers.has(newRecord)) {
return;
}
if (this.canonicalState) {
this.removeCanonicalRecord(this.canonicalState);
}
this.canonicalState = newRecord;
this._super$addCanonicalRecord(newRecord);
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$flushCanonical = ember$data$lib$system$relationships$state$relationship$$default.prototype.flushCanonical;
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.flushCanonical = function () {
//temporary fix to not remove newly created records if server returned null.
//TODO remove once we have proper diffing
if (this.inverseRecord && this.inverseRecord.isNew() && !this.canonicalState) {
return;
}
this.inverseRecord = this.canonicalState;
this.record.notifyBelongsToChanged(this.key);
this._super$flushCanonical();
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$addRecord = ember$data$lib$system$relationships$state$relationship$$default.prototype.addRecord;
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.addRecord = function (newRecord) {
if (this.members.has(newRecord)) {
return;
}
var typeClass = this.store.modelFor(this.relationshipMeta.type);
if (this.inverseRecord) {
this.removeRecord(this.inverseRecord);
}
this.inverseRecord = newRecord;
this._super$addRecord(newRecord);
this.record.notifyBelongsToChanged(this.key);
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.setRecordPromise = function (newPromise) {
var content = newPromise.get && newPromise.get("content");
this.setRecord(content ? content._internalModel : content);
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$removeRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeRecordFromOwn;
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.removeRecordFromOwn = function (record) {
if (!this.members.has(record)) {
return;
}
this.inverseRecord = null;
this._super$removeRecordFromOwn(record);
this.record.notifyBelongsToChanged(this.key);
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype._super$removeCanonicalRecordFromOwn = ember$data$lib$system$relationships$state$relationship$$default.prototype.removeCanonicalRecordFromOwn;
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.removeCanonicalRecordFromOwn = function (record) {
if (!this.canonicalMembers.has(record)) {
return;
}
this.canonicalState = null;
this._super$removeCanonicalRecordFromOwn(record);
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.findRecord = function () {
if (this.inverseRecord) {
return this.store._findByInternalModel(this.inverseRecord);
} else {
return Ember.RSVP.Promise.resolve(null);
}
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.fetchLink = function () {
var self = this;
return this.store.findBelongsTo(this.record, this.link, this.relationshipMeta).then(function (record) {
if (record) {
self.addRecord(record);
}
return record;
});
};
ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship.prototype.getRecord = function () {
//TODO(Igor) flushCanonical here once our syncing is not stupid
if (this.isAsync) {
var promise;
if (this.link) {
var self = this;
promise = this.findLink().then(function () {
return self.findRecord();
});
} else {
promise = this.findRecord();
}
return ember$data$lib$system$promise$proxies$$PromiseObject.create({
promise: promise,
content: this.inverseRecord ? this.inverseRecord.getRecord() : null
});
} else {
if (this.inverseRecord === null) {
return null;
}
var toReturn = this.inverseRecord.getRecord();
return toReturn;
}
};
var ember$data$lib$system$relationships$state$belongs$to$$default = ember$data$lib$system$relationships$state$belongs$to$$BelongsToRelationship;
var ember$data$lib$system$relationships$state$create$$get = Ember.get;
var ember$data$lib$system$relationships$state$create$$createRelationshipFor = function (record, relationshipMeta, store) {
var inverseKey;
var inverse = record.type.inverseFor(relationshipMeta.key, store);
if (inverse) {
inverseKey = inverse.name;
}
if (relationshipMeta.kind === "hasMany") {
return new ember$data$lib$system$relationships$state$has$many$$default(store, record, inverseKey, relationshipMeta);
} else {
return new ember$data$lib$system$relationships$state$belongs$to$$default(store, record, inverseKey, relationshipMeta);
}
};
var ember$data$lib$system$relationships$state$create$$Relationships = function (record) {
this.record = record;
this.initializedRelationships = Ember.create(null);
};
ember$data$lib$system$relationships$state$create$$Relationships.prototype.has = function (key) {
return !!this.initializedRelationships[key];
};
ember$data$lib$system$relationships$state$create$$Relationships.prototype.get = function (key) {
var relationships = this.initializedRelationships;
var relationshipsByName = ember$data$lib$system$relationships$state$create$$get(this.record.type, "relationshipsByName");
if (!relationships[key] && relationshipsByName.get(key)) {
relationships[key] = ember$data$lib$system$relationships$state$create$$createRelationshipFor(this.record, relationshipsByName.get(key), this.record.store);
}
return relationships[key];
};
var ember$data$lib$system$relationships$state$create$$default = ember$data$lib$system$relationships$state$create$$Relationships;
var ember$data$lib$system$snapshot$$get = Ember.get;
/**
@class Snapshot
@namespace DS
@private
@constructor
@param {DS.Model} internalModel The model to create a snapshot from
*/
function ember$data$lib$system$snapshot$$Snapshot(internalModel) {
this._attributes = Ember.create(null);
this._belongsToRelationships = Ember.create(null);
this._belongsToIds = Ember.create(null);
this._hasManyRelationships = Ember.create(null);
this._hasManyIds = Ember.create(null);
var record = internalModel.getRecord();
this.record = record;
record.eachAttribute(function (keyName) {
this._attributes[keyName] = ember$data$lib$system$snapshot$$get(record, keyName);
}, this);
this.id = internalModel.id;
this._internalModel = internalModel;
this.type = internalModel.type;
this.modelName = internalModel.type.modelName;
this._changedAttributes = record.changedAttributes();
// The following code is here to keep backwards compatibility when accessing
// `constructor` directly.
//
// With snapshots you should use `type` instead of `constructor`.
//
// Remove for Ember Data 1.0.
if (Ember.platform.hasPropertyAccessors) {
var callDeprecate = true;
Ember.defineProperty(this, 'constructor', {
get: function () {
// Ugly hack since accessing error.stack (done in `Ember.deprecate()`)
// causes the internals of Chrome to access the constructor, which then
// causes an infinite loop if accessed and calls `Ember.deprecate()`
// again.
if (callDeprecate) {
callDeprecate = false;
callDeprecate = true;
}
return this.type;
}
});
} else {
this.constructor = this.type;
}
}
ember$data$lib$system$snapshot$$Snapshot.prototype = {
constructor: ember$data$lib$system$snapshot$$Snapshot,
/**
The id of the snapshot's underlying record
Example
```javascript
// store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' });
postSnapshot.id; // => '1'
```
@property id
@type {String}
*/
id: null,
/**
The underlying record for this snapshot. Can be used to access methods and
properties defined on the record.
Example
```javascript
var json = snapshot.record.toJSON();
```
@property record
@type {DS.Model}
*/
record: null,
/**
The type of the underlying record for this snapshot, as a DS.Model.
@property type
@type {DS.Model}
*/
type: null,
/**
The name of the type of the underlying record for this snapshot, as a string.
@property modelName
@type {String}
*/
modelName: null,
/**
Returns the value of an attribute.
Example
```javascript
// store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' });
postSnapshot.attr('author'); // => 'Tomster'
postSnapshot.attr('title'); // => 'Ember.js rocks'
```
Note: Values are loaded eagerly and cached when the snapshot is created.
@method attr
@param {String} keyName
@return {Object} The attribute value or undefined
*/
attr: function (keyName) {
if (keyName in this._attributes) {
return this._attributes[keyName];
}
throw new Ember.Error('Model \'' + Ember.inspect(this.record) + '\' has no attribute named \'' + keyName + '\' defined.');
},
/**
Returns all attributes and their corresponding values.
Example
```javascript
// store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' });
postSnapshot.attributes(); // => { author: 'Tomster', title: 'Ember.js rocks' }
```
@method attributes
@return {Object} All attributes of the current snapshot
*/
attributes: function () {
return Ember.copy(this._attributes);
},
/**
Returns all changed attributes and their old and new values.
Example
```javascript
// store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' });
postModel.set('title', 'Ember.js rocks!');
postSnapshot.changedAttributes(); // => { title: ['Ember.js rocks', 'Ember.js rocks!'] }
```
@method changedAttributes
@return {Object} All changed attributes of the current snapshot
*/
changedAttributes: function () {
var prop;
var changedAttributes = Ember.create(null);
for (prop in this._changedAttributes) {
changedAttributes[prop] = Ember.copy(this._changedAttributes[prop]);
}
return changedAttributes;
},
/**
Returns the current value of a belongsTo relationship.
`belongsTo` takes an optional hash of options as a second parameter,
currently supported options are:
- `id`: set to `true` if you only want the ID of the related record to be
returned.
Example
```javascript
// store.push('post', { id: 1, title: 'Hello World' });
// store.createRecord('comment', { body: 'Lorem ipsum', post: post });
commentSnapshot.belongsTo('post'); // => DS.Snapshot
commentSnapshot.belongsTo('post', { id: true }); // => '1'
// store.push('comment', { id: 1, body: 'Lorem ipsum' });
commentSnapshot.belongsTo('post'); // => undefined
```
Calling `belongsTo` will return a new Snapshot as long as there's any known
data for the relationship available, such as an ID. If the relationship is
known but unset, `belongsTo` will return `null`. If the contents of the
relationship is unknown `belongsTo` will return `undefined`.
Note: Relationships are loaded lazily and cached upon first access.
@method belongsTo
@param {String} keyName
@param {Object} [options]
@return {(DS.Snapshot|String|null|undefined)} A snapshot or ID of a known
relationship or null if the relationship is known but unset. undefined
will be returned if the contents of the relationship is unknown.
*/
belongsTo: function (keyName, options) {
var id = options && options.id;
var relationship, inverseRecord, hasData;
var result;
if (id && keyName in this._belongsToIds) {
return this._belongsToIds[keyName];
}
if (!id && keyName in this._belongsToRelationships) {
return this._belongsToRelationships[keyName];
}
relationship = this._internalModel._relationships.get(keyName);
if (!(relationship && relationship.relationshipMeta.kind === 'belongsTo')) {
throw new Ember.Error('Model \'' + Ember.inspect(this.record) + '\' has no belongsTo relationship named \'' + keyName + '\' defined.');
}
hasData = ember$data$lib$system$snapshot$$get(relationship, 'hasData');
inverseRecord = ember$data$lib$system$snapshot$$get(relationship, 'inverseRecord');
if (hasData) {
if (inverseRecord && !inverseRecord.isDeleted()) {
if (id) {
result = ember$data$lib$system$snapshot$$get(inverseRecord, 'id');
} else {
result = inverseRecord.createSnapshot();
}
} else {
result = null;
}
}
if (id) {
this._belongsToIds[keyName] = result;
} else {
this._belongsToRelationships[keyName] = result;
}
return result;
},
/**
Returns the current value of a hasMany relationship.
`hasMany` takes an optional hash of options as a second parameter,
currently supported options are:
- `ids`: set to `true` if you only want the IDs of the related records to be
returned.
Example
```javascript
// store.push('post', { id: 1, title: 'Hello World', comments: [2, 3] });
postSnapshot.hasMany('comments'); // => [DS.Snapshot, DS.Snapshot]
postSnapshot.hasMany('comments', { ids: true }); // => ['2', '3']
// store.push('post', { id: 1, title: 'Hello World' });
postSnapshot.hasMany('comments'); // => undefined
```
Note: Relationships are loaded lazily and cached upon first access.
@method hasMany
@param {String} keyName
@param {Object} [options]
@return {(Array|undefined)} An array of snapshots or IDs of a known
relationship or an empty array if the relationship is known but unset.
undefined will be returned if the contents of the relationship is unknown.
*/
hasMany: function (keyName, options) {
var ids = options && options.ids;
var relationship, members, hasData;
var results;
if (ids && keyName in this._hasManyIds) {
return this._hasManyIds[keyName];
}
if (!ids && keyName in this._hasManyRelationships) {
return this._hasManyRelationships[keyName];
}
relationship = this._internalModel._relationships.get(keyName);
if (!(relationship && relationship.relationshipMeta.kind === 'hasMany')) {
throw new Ember.Error('Model \'' + Ember.inspect(this.record) + '\' has no hasMany relationship named \'' + keyName + '\' defined.');
}
hasData = ember$data$lib$system$snapshot$$get(relationship, 'hasData');
members = ember$data$lib$system$snapshot$$get(relationship, 'members');
if (hasData) {
results = [];
members.forEach(function (member) {
if (!member.isDeleted()) {
if (ids) {
results.push(member.id);
} else {
results.push(member.createSnapshot());
}
}
});
}
if (ids) {
this._hasManyIds[keyName] = results;
} else {
this._hasManyRelationships[keyName] = results;
}
return results;
},
/**
Iterates through all the attributes of the model, calling the passed
function on each attribute.
Example
```javascript
snapshot.eachAttribute(function(name, meta) {
// ...
});
```
@method eachAttribute
@param {Function} callback the callback to execute
@param {Object} [binding] the value to which the callback's `this` should be bound
*/
eachAttribute: function (callback, binding) {
this.record.eachAttribute(callback, binding);
},
/**
Iterates through all the relationships of the model, calling the passed
function on each relationship.
Example
```javascript
snapshot.eachRelationship(function(name, relationship) {
// ...
});
```
@method eachRelationship
@param {Function} callback the callback to execute
@param {Object} [binding] the value to which the callback's `this` should be bound
*/
eachRelationship: function (callback, binding) {
this.record.eachRelationship(callback, binding);
},
/**
@method get
@param {String} keyName
@return {Object} The property value
@deprecated Use [attr](#method_attr), [belongsTo](#method_belongsTo) or [hasMany](#method_hasMany) instead
*/
get: function (keyName) {
if (keyName === 'id') {
return this.id;
}
if (keyName in this._attributes) {
return this.attr(keyName);
}
var relationship = this._internalModel._relationships.get(keyName);
if (relationship && relationship.relationshipMeta.kind === 'belongsTo') {
return this.belongsTo(keyName);
}
if (relationship && relationship.relationshipMeta.kind === 'hasMany') {
return this.hasMany(keyName);
}
return ember$data$lib$system$snapshot$$get(this.record, keyName);
},
/**
@method serialize
@param {Object} options
@return {Object} an object whose values are primitive JSON values only
*/
serialize: function (options) {
return this.record.store.serializerFor(this.modelName).serialize(this, options);
},
/**
@method unknownProperty
@param {String} keyName
@return {Object} The property value
@deprecated Use [attr](#method_attr), [belongsTo](#method_belongsTo) or [hasMany](#method_hasMany) instead
*/
unknownProperty: function (keyName) {
return this.get(keyName);
},
/**
@method _createSnapshot
@private
*/
_createSnapshot: function () {
return this;
}
};
Ember.defineProperty(ember$data$lib$system$snapshot$$Snapshot.prototype, 'typeKey', {
enumerable: false,
get: function () {
return this.modelName;
},
set: function () {
}
});
var ember$data$lib$system$snapshot$$default = ember$data$lib$system$snapshot$$Snapshot;
var ember$data$lib$system$model$errors$$get = Ember.get;
var ember$data$lib$system$model$errors$$isEmpty = Ember.isEmpty;
var ember$data$lib$system$model$errors$$map = Ember.EnumerableUtils.map;
var ember$data$lib$system$model$errors$$default = Ember.Object.extend(Ember.Enumerable, Ember.Evented, {
/**
Register with target handler
@method registerHandlers
@param {Object} target
@param {Function} becameInvalid
@param {Function} becameValid
*/
registerHandlers: function (target, becameInvalid, becameValid) {
this.on('becameInvalid', target, becameInvalid);
this.on('becameValid', target, becameValid);
},
/**
@property errorsByAttributeName
@type {Ember.MapWithDefault}
@private
*/
errorsByAttributeName: Ember.reduceComputed('content', {
initialValue: function () {
return ember$data$lib$system$map$$MapWithDefault.create({
defaultValue: function () {
return Ember.A();
}
});
},
addedItem: function (errors, error) {
errors.get(error.attribute).pushObject(error);
return errors;
},
removedItem: function (errors, error) {
errors.get(error.attribute).removeObject(error);
return errors;
}
}),
/**
Returns errors for a given attribute
```javascript
var user = store.createRecord('user', {
username: 'tomster',
email: 'invalidEmail'
});
user.save().catch(function(){
user.get('errors').errorsFor('email'); // returns:
// [{attribute: "email", message: "Doesn't look like a valid email."}]
});
```
@method errorsFor
@param {String} attribute
@return {Array}
*/
errorsFor: function (attribute) {
return ember$data$lib$system$model$errors$$get(this, 'errorsByAttributeName').get(attribute);
},
/**
An array containing all of the error messages for this
record. This is useful for displaying all errors to the user.
```handlebars
{{#each model.errors.messages as |message|}}
<div class="error">
{{message}}
</div>
{{/each}}
```
@property messages
@type {Array}
*/
messages: Ember.computed.mapBy('content', 'message'),
/**
@property content
@type {Array}
@private
*/
content: Ember.computed(function () {
return Ember.A();
}),
/**
@method unknownProperty
@private
*/
unknownProperty: function (attribute) {
var errors = this.errorsFor(attribute);
if (ember$data$lib$system$model$errors$$isEmpty(errors)) {
return null;
}
return errors;
},
/**
@method nextObject
@private
*/
nextObject: function (index, previousObject, context) {
return ember$data$lib$system$model$errors$$get(this, 'content').objectAt(index);
},
/**
Total number of errors.
@property length
@type {Number}
@readOnly
*/
length: Ember.computed.oneWay('content.length').readOnly(),
/**
@property isEmpty
@type {Boolean}
@readOnly
*/
isEmpty: Ember.computed.not('length').readOnly(),
/**
Adds error messages to a given attribute and sends
`becameInvalid` event to the record.
Example:
```javascript
if (!user.get('username') {
user.get('errors').add('username', 'This field is required');
}
```
@method add
@param {String} attribute
@param {(Array|String)} messages
*/
add: function (attribute, messages) {
var wasEmpty = ember$data$lib$system$model$errors$$get(this, 'isEmpty');
messages = this._findOrCreateMessages(attribute, messages);
ember$data$lib$system$model$errors$$get(this, 'content').addObjects(messages);
this.notifyPropertyChange(attribute);
this.enumerableContentDidChange();
if (wasEmpty && !ember$data$lib$system$model$errors$$get(this, 'isEmpty')) {
this.trigger('becameInvalid');
}
},
/**
@method _findOrCreateMessages
@private
*/
_findOrCreateMessages: function (attribute, messages) {
var errors = this.errorsFor(attribute);
return ember$data$lib$system$model$errors$$map(Ember.makeArray(messages), function (message) {
return errors.findBy('message', message) || {
attribute: attribute,
message: message
};
});
},
/**
Removes all error messages from the given attribute and sends
`becameValid` event to the record if there no more errors left.
Example:
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
email: DS.attr('string'),
twoFactorAuth: DS.attr('boolean'),
phone: DS.attr('string')
});
```
```app/routes/user/edit.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
save: function(user) {
if (!user.get('twoFactorAuth')) {
user.get('errors').remove('phone');
}
user.save();
}
}
});
```
@method remove
@param {String} attribute
*/
remove: function (attribute) {
if (ember$data$lib$system$model$errors$$get(this, 'isEmpty')) {
return;
}
var content = ember$data$lib$system$model$errors$$get(this, 'content').rejectBy('attribute', attribute);
ember$data$lib$system$model$errors$$get(this, 'content').setObjects(content);
this.notifyPropertyChange(attribute);
this.enumerableContentDidChange();
if (ember$data$lib$system$model$errors$$get(this, 'isEmpty')) {
this.trigger('becameValid');
}
},
/**
Removes all error messages and sends `becameValid` event
to the record.
Example:
```app/routes/user/edit.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
retrySave: function(user) {
user.get('errors').clear();
user.save();
}
}
});
```
@method clear
*/
clear: function () {
if (ember$data$lib$system$model$errors$$get(this, 'isEmpty')) {
return;
}
ember$data$lib$system$model$errors$$get(this, 'content').clear();
this.enumerableContentDidChange();
this.trigger('becameValid');
},
/**
Checks if there is error messages for the given attribute.
```app/routes/user/edit.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
save: function(user) {
if (user.get('errors').has('email')) {
return alert('Please update your email before attempting to save.');
}
user.save();
}
}
});
```
@method has
@param {String} attribute
@return {Boolean} true if there some errors on given attribute
*/
has: function (attribute) {
return !ember$data$lib$system$model$errors$$isEmpty(this.errorsFor(attribute));
}
});
var ember$data$lib$system$model$internal$model$$Promise = Ember.RSVP.Promise;
var ember$data$lib$system$model$internal$model$$get = Ember.get;
var ember$data$lib$system$model$internal$model$$set = Ember.set;
var ember$data$lib$system$model$internal$model$$forEach = Ember.ArrayPolyfills.forEach;
var ember$data$lib$system$model$internal$model$$map = Ember.ArrayPolyfills.map;
var ember$data$lib$system$model$internal$model$$_extractPivotNameCache = Ember.create(null);
var ember$data$lib$system$model$internal$model$$_splitOnDotCache = Ember.create(null);
function ember$data$lib$system$model$internal$model$$splitOnDot(name) {
return ember$data$lib$system$model$internal$model$$_splitOnDotCache[name] || (ember$data$lib$system$model$internal$model$$_splitOnDotCache[name] = name.split("."));
}
function ember$data$lib$system$model$internal$model$$extractPivotName(name) {
return ember$data$lib$system$model$internal$model$$_extractPivotNameCache[name] || (ember$data$lib$system$model$internal$model$$_extractPivotNameCache[name] = ember$data$lib$system$model$internal$model$$splitOnDot(name)[0]);
}
function ember$data$lib$system$model$internal$model$$retrieveFromCurrentState(key) {
return function () {
return ember$data$lib$system$model$internal$model$$get(this.currentState, key);
};
}
/**
`InternalModel` is the Model class that we use internally inside Ember Data to represent models.
Internal ED methods should only deal with `InternalModel` objects. It is a fast, plain Javascript class.
We expose `DS.Model` to application code, by materializing a `DS.Model` from `InternalModel` lazily, as
a performance optimization.
`InternalModel` should never be exposed to application code. At the boundaries of the system, in places
like `find`, `push`, etc. we convert between Models and InternalModels.
We need to make sure that the properties from `InternalModel` are correctly exposed/proxied on `Model`
if they are needed.
@class InternalModel
*/
var ember$data$lib$system$model$internal$model$$InternalModel = function InternalModel(type, id, store, container, data) {
this.type = type;
this.id = id;
this.store = store;
this.container = container;
this._data = data || Ember.create(null);
this.modelName = type.modelName;
this.errors = null;
this.dataHasInitialized = false;
//Look into making this lazy
this._deferredTriggers = [];
this._attributes = Ember.create(null);
this._inFlightAttributes = Ember.create(null);
this._relationships = new ember$data$lib$system$relationships$state$create$$default(this);
this.currentState = ember$data$lib$system$model$states$$default.empty;
this.isReloading = false;
/*
implicit relationships are relationship which have not been declared but the inverse side exists on
another record somewhere
For example if there was
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr()
})
```
but there is also
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr(),
comments: DS.hasMany('comment')
})
```
would have a implicit post relationship in order to be do things like remove ourselves from the post
when we are deleted
*/
this._implicitRelationships = Ember.create(null);
};
ember$data$lib$system$model$internal$model$$InternalModel.prototype = {
isEmpty: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isEmpty"),
isLoading: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isLoading"),
isLoaded: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isLoaded"),
isDirty: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isDirty"),
isSaving: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isSaving"),
isDeleted: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isDeleted"),
isNew: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isNew"),
isValid: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("isValid"),
dirtyType: ember$data$lib$system$model$internal$model$$retrieveFromCurrentState("dirtyType"),
constructor: ember$data$lib$system$model$internal$model$$InternalModel,
materializeRecord: function () {
// lookupFactory should really return an object that creates
// instances with the injections applied
this.record = this.type._create({
id: this.id,
store: this.store,
container: this.container,
_internalModel: this
});
this._triggerDeferredTriggers();
},
recordObjectWillDestroy: function () {
this.record = null;
},
deleteRecord: function () {
this.send("deleteRecord");
},
save: function () {
var promiseLabel = "DS: Model#save " + this;
var resolver = Ember.RSVP.defer(promiseLabel);
this.store.scheduleSave(this, resolver);
return resolver.promise;
},
startedReloading: function () {
this.isReloading = true;
if (this.record) {
ember$data$lib$system$model$internal$model$$set(this.record, "isReloading", true);
}
},
finishedReloading: function () {
this.isReloading = false;
if (this.record) {
ember$data$lib$system$model$internal$model$$set(this.record, "isReloading", false);
}
},
reload: function () {
this.startedReloading();
var record = this;
var promiseLabel = "DS: Model#reload of " + this;
return new ember$data$lib$system$model$internal$model$$Promise(function (resolve) {
record.send("reloadRecord", resolve);
}, promiseLabel).then(function () {
record.didCleanError();
return record;
}, function (reason) {
record.didError();
throw reason;
}, "DS: Model#reload complete, update flags")["finally"](function () {
record.finishedReloading();
record.updateRecordArrays();
});
},
getRecord: function () {
if (!this.record) {
this.materializeRecord();
}
return this.record;
},
unloadRecord: function () {
this.send("unloadRecord");
},
eachRelationship: function (callback, binding) {
return this.type.eachRelationship(callback, binding);
},
eachAttribute: function (callback, binding) {
return this.type.eachAttribute(callback, binding);
},
inverseFor: function (key) {
return this.type.inverseFor(key);
},
setupData: function (data) {
var changedKeys = ember$data$lib$system$model$internal$model$$mergeAndReturnChangedKeys(this._data, data);
this.pushedData();
if (this.record) {
this.record._notifyProperties(changedKeys);
}
this.didInitalizeData();
},
becameReady: function () {
Ember.run.schedule("actions", this.store.recordArrayManager, this.store.recordArrayManager.recordWasLoaded, this);
},
didInitalizeData: function () {
if (!this.dataHasInitialized) {
this.becameReady();
this.dataHasInitialized = true;
}
},
destroy: function () {
if (this.record) {
return this.record.destroy();
}
},
/**
@method createSnapshot
@private
*/
createSnapshot: function () {
return new ember$data$lib$system$snapshot$$default(this);
},
/**
@method loadingData
@private
@param {Promise} promise
*/
loadingData: function (promise) {
this.send("loadingData", promise);
},
/**
@method loadedData
@private
*/
loadedData: function () {
this.send("loadedData");
this.didInitalizeData();
},
/**
@method notFound
@private
*/
notFound: function () {
this.send("notFound");
},
/**
@method pushedData
@private
*/
pushedData: function () {
this.send("pushedData");
},
flushChangedAttributes: function () {
this._inFlightAttributes = this._attributes;
this._attributes = Ember.create(null);
},
/**
@method adapterWillCommit
@private
*/
adapterWillCommit: function () {
this.send("willCommit");
},
/**
@method adapterDidDirty
@private
*/
adapterDidDirty: function () {
this.send("becomeDirty");
this.updateRecordArraysLater();
},
/**
@method send
@private
@param {String} name
@param {Object} context
*/
send: function (name, context) {
var currentState = ember$data$lib$system$model$internal$model$$get(this, "currentState");
if (!currentState[name]) {
this._unhandledEvent(currentState, name, context);
}
return currentState[name](this, context);
},
notifyHasManyAdded: function (key, record, idx) {
if (this.record) {
this.record.notifyHasManyAdded(key, record, idx);
}
},
notifyHasManyRemoved: function (key, record, idx) {
if (this.record) {
this.record.notifyHasManyRemoved(key, record, idx);
}
},
notifyBelongsToChanged: function (key, record) {
if (this.record) {
this.record.notifyBelongsToChanged(key, record);
}
},
notifyPropertyChange: function (key) {
if (this.record) {
this.record.notifyPropertyChange(key);
}
},
rollback: function () {
var dirtyKeys = Ember.keys(this._attributes);
this._attributes = Ember.create(null);
if (ember$data$lib$system$model$internal$model$$get(this, "isError")) {
this._inFlightAttributes = Ember.create(null);
this.didCleanError();
}
//Eventually rollback will always work for relationships
//For now we support it only out of deleted state, because we
//have an explicit way of knowing when the server acked the relationship change
if (this.isDeleted()) {
//TODO: Should probably move this to the state machine somehow
this.becameReady();
this.reconnectRelationships();
}
if (this.isNew()) {
this.clearRelationships();
}
if (this.isValid()) {
this._inFlightAttributes = Ember.create(null);
}
this.send("rolledBack");
this.record._notifyProperties(dirtyKeys);
},
/**
@method transitionTo
@private
@param {String} name
*/
transitionTo: function (name) {
// POSSIBLE TODO: Remove this code and replace with
// always having direct reference to state objects
var pivotName = ember$data$lib$system$model$internal$model$$extractPivotName(name);
var currentState = ember$data$lib$system$model$internal$model$$get(this, "currentState");
var state = currentState;
do {
if (state.exit) {
state.exit(this);
}
state = state.parentState;
} while (!state.hasOwnProperty(pivotName));
var path = ember$data$lib$system$model$internal$model$$splitOnDot(name);
var setups = [];
var enters = [];
var i, l;
for (i = 0, l = path.length; i < l; i++) {
state = state[path[i]];
if (state.enter) {
enters.push(state);
}
if (state.setup) {
setups.push(state);
}
}
for (i = 0, l = enters.length; i < l; i++) {
enters[i].enter(this);
}
ember$data$lib$system$model$internal$model$$set(this, "currentState", state);
//TODO Consider whether this is the best approach for keeping these two in sync
if (this.record) {
ember$data$lib$system$model$internal$model$$set(this.record, "currentState", state);
}
for (i = 0, l = setups.length; i < l; i++) {
setups[i].setup(this);
}
this.updateRecordArraysLater();
},
_unhandledEvent: function (state, name, context) {
var errorMessage = "Attempted to handle event `" + name + "` ";
errorMessage += "on " + String(this) + " while in state ";
errorMessage += state.stateName + ". ";
if (context !== undefined) {
errorMessage += "Called with " + Ember.inspect(context) + ".";
}
throw new Ember.Error(errorMessage);
},
triggerLater: function () {
var length = arguments.length;
var args = new Array(length);
for (var i = 0; i < length; i++) {
args[i] = arguments[i];
}
if (this._deferredTriggers.push(args) !== 1) {
return;
}
Ember.run.scheduleOnce("actions", this, "_triggerDeferredTriggers");
},
_triggerDeferredTriggers: function () {
//TODO: Before 1.0 we want to remove all the events that happen on the pre materialized record,
//but for now, we queue up all the events triggered before the record was materialized, and flush
//them once we have the record
if (!this.record) {
return;
}
for (var i = 0, l = this._deferredTriggers.length; i < l; i++) {
this.record.trigger.apply(this.record, this._deferredTriggers[i]);
}
this._deferredTriggers.length = 0;
},
/**
@method clearRelationships
@private
*/
clearRelationships: function () {
this.eachRelationship(function (name, relationship) {
if (this._relationships.has(name)) {
var rel = this._relationships.get(name);
//TODO(Igor) figure out whether we want to clear or disconnect
rel.clear();
rel.destroy();
}
}, this);
var model = this;
ember$data$lib$system$model$internal$model$$forEach.call(Ember.keys(this._implicitRelationships), function (key) {
model._implicitRelationships[key].clear();
model._implicitRelationships[key].destroy();
});
},
disconnectRelationships: function () {
this.eachRelationship(function (name, relationship) {
this._relationships.get(name).disconnect();
}, this);
var model = this;
ember$data$lib$system$model$internal$model$$forEach.call(Ember.keys(this._implicitRelationships), function (key) {
model._implicitRelationships[key].disconnect();
});
},
reconnectRelationships: function () {
this.eachRelationship(function (name, relationship) {
this._relationships.get(name).reconnect();
}, this);
var model = this;
ember$data$lib$system$model$internal$model$$forEach.call(Ember.keys(this._implicitRelationships), function (key) {
model._implicitRelationships[key].reconnect();
});
},
/**
When a find request is triggered on the store, the user can optionally pass in
attributes and relationships to be preloaded. These are meant to behave as if they
came back from the server, except the user obtained them out of band and is informing
the store of their existence. The most common use case is for supporting client side
nested URLs, such as `/posts/1/comments/2` so the user can do
`store.find('comment', 2, {post:1})` without having to fetch the post.
Preloaded data can be attributes and relationships passed in either as IDs or as actual
models.
@method _preloadData
@private
@param {Object} preload
*/
_preloadData: function (preload) {
var record = this;
//TODO(Igor) consider the polymorphic case
ember$data$lib$system$model$internal$model$$forEach.call(Ember.keys(preload), function (key) {
var preloadValue = ember$data$lib$system$model$internal$model$$get(preload, key);
var relationshipMeta = record.type.metaForProperty(key);
if (relationshipMeta.isRelationship) {
record._preloadRelationship(key, preloadValue);
} else {
record._data[key] = preloadValue;
}
});
},
_preloadRelationship: function (key, preloadValue) {
var relationshipMeta = this.type.metaForProperty(key);
var type = relationshipMeta.type;
if (relationshipMeta.kind === "hasMany") {
this._preloadHasMany(key, preloadValue, type);
} else {
this._preloadBelongsTo(key, preloadValue, type);
}
},
_preloadHasMany: function (key, preloadValue, type) {
var internalModel = this;
var recordsToSet = ember$data$lib$system$model$internal$model$$map.call(preloadValue, function (recordToPush) {
return internalModel._convertStringOrNumberIntoInternalModel(recordToPush, type);
});
//We use the pathway of setting the hasMany as if it came from the adapter
//because the user told us that they know this relationships exists already
this._relationships.get(key).updateRecordsFromAdapter(recordsToSet);
},
_preloadBelongsTo: function (key, preloadValue, type) {
var recordToSet = this._convertStringOrNumberIntoInternalModel(preloadValue, type);
//We use the pathway of setting the hasMany as if it came from the adapter
//because the user told us that they know this relationships exists already
this._relationships.get(key).setRecord(recordToSet);
},
_convertStringOrNumberIntoInternalModel: function (value, type) {
if (typeof value === "string" || typeof value === "number") {
return this.store._internalModelForId(type, value);
}
if (value._internalModel) {
return value._internalModel;
}
return value;
},
/**
@method updateRecordArrays
@private
*/
updateRecordArrays: function () {
this._updatingRecordArraysLater = false;
this.store.dataWasUpdated(this.type, this);
},
setId: function (id) {
this.id = id;
//TODO figure out whether maybe we should proxy
ember$data$lib$system$model$internal$model$$set(this.record, "id", id);
},
didError: function () {
this.isError = true;
if (this.record) {
this.record.set("isError", true);
}
},
didCleanError: function () {
this.isError = false;
if (this.record) {
this.record.set("isError", false);
}
},
/**
If the adapter did not return a hash in response to a commit,
merge the changed attributes and relationships into the existing
saved data.
@method adapterDidCommit
*/
adapterDidCommit: function (data) {
var changedKeys;
this.didCleanError();
if (data) {
changedKeys = ember$data$lib$system$model$internal$model$$mergeAndReturnChangedKeys(this._data, data);
} else {
ember$data$lib$system$merge$$default(this._data, this._inFlightAttributes);
}
this._inFlightAttributes = Ember.create(null);
this.send("didCommit");
this.updateRecordArraysLater();
if (!data) {
return;
}
this.record._notifyProperties(changedKeys);
},
/**
@method updateRecordArraysLater
@private
*/
updateRecordArraysLater: function () {
// quick hack (something like this could be pushed into run.once
if (this._updatingRecordArraysLater) {
return;
}
this._updatingRecordArraysLater = true;
Ember.run.schedule("actions", this, this.updateRecordArrays);
},
getErrors: function () {
if (this.errors) {
return this.errors;
}
var errors = ember$data$lib$system$model$errors$$default.create();
errors.registerHandlers(this, function () {
this.send("becameInvalid");
}, function () {
this.send("becameValid");
});
this.errors = errors;
return errors;
},
// FOR USE DURING COMMIT PROCESS
/**
@method adapterDidInvalidate
@private
*/
adapterDidInvalidate: function (errors) {
var recordErrors = this.getErrors();
ember$data$lib$system$model$internal$model$$forEach.call(Ember.keys(errors), function (key) {
recordErrors.add(key, errors[key]);
});
this._saveWasRejected();
},
/**
@method adapterDidError
@private
*/
adapterDidError: function () {
this.send("becameError");
this.didError();
this._saveWasRejected();
},
_saveWasRejected: function () {
var keys = Ember.keys(this._inFlightAttributes);
for (var i = 0; i < keys.length; i++) {
if (this._attributes[keys[i]] === undefined) {
this._attributes[keys[i]] = this._inFlightAttributes[keys[i]];
}
}
this._inFlightAttributes = Ember.create(null);
},
toString: function () {
if (this.record) {
return this.record.toString();
} else {
return "<" + this.modelName + ":" + this.id + ">";
}
}
};
// Like Ember.merge, but instead returns a list of keys
// for values that fail a strict equality check
// instead of the original object.
function ember$data$lib$system$model$internal$model$$mergeAndReturnChangedKeys(original, updates) {
var changedKeys = [];
if (!updates || typeof updates !== "object") {
return changedKeys;
}
var keys = Ember.keys(updates);
var length = keys.length;
var i, val, key;
for (i = 0; i < length; i++) {
key = keys[i];
val = updates[key];
if (original[key] !== val) {
changedKeys.push(key);
}
original[key] = val;
}
return changedKeys;
}
var ember$data$lib$system$model$internal$model$$default = ember$data$lib$system$model$internal$model$$InternalModel;
/**
@module ember-data
*/
var ember$data$lib$system$model$model$$get = Ember.get;
var ember$data$lib$system$model$model$$intersection = Ember.EnumerableUtils.intersection;
var ember$data$lib$system$model$model$$RESERVED_MODEL_PROPS = ['currentState', 'data', 'store'];
var ember$data$lib$system$model$model$$retrieveFromCurrentState = Ember.computed('currentState', function (key) {
return ember$data$lib$system$model$model$$get(this._internalModel.currentState, key);
}).readOnly();
/**
The model class that all Ember Data records descend from.
This is the public API of Ember Data models. If you are using Ember Data
in your application, this is the class you should use.
If you are working on Ember Data internals, you most likely want to be dealing
with `InternalModel`
@class Model
@namespace DS
@extends Ember.Object
@uses Ember.Evented
*/
var ember$data$lib$system$model$model$$Model = Ember.Object.extend(Ember.Evented, {
_recordArrays: undefined,
_relationships: undefined,
_internalModel: null,
store: null,
/**
If this property is `true` the record is in the `empty`
state. Empty is the first state all records enter after they have
been created. Most records created by the store will quickly
transition to the `loading` state if data needs to be fetched from
the server or the `created` state if the record is created on the
client. A record can also enter the empty state if the adapter is
unable to locate the record.
@property isEmpty
@type {Boolean}
@readOnly
*/
isEmpty: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loading` state. A
record enters this state when the store asks the adapter for its
data. It remains in this state until the adapter provides the
requested data.
@property isLoading
@type {Boolean}
@readOnly
*/
isLoading: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loaded` state. A
record enters this state when its data is populated. Most of a
record's lifecycle is spent inside substates of the `loaded`
state.
Example
```javascript
var record = store.createRecord('model');
record.get('isLoaded'); // true
store.find('model', 1).then(function(model) {
model.get('isLoaded'); // true
});
```
@property isLoaded
@type {Boolean}
@readOnly
*/
isLoaded: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `dirty` state. The
record has local changes that have not yet been saved by the
adapter. This includes records that have been created (but not yet
saved) or deleted.
Example
```javascript
var record = store.createRecord('model');
record.get('isDirty'); // true
store.find('model', 1).then(function(model) {
model.get('isDirty'); // false
model.set('foo', 'some value');
model.get('isDirty'); // true
});
```
@property isDirty
@type {Boolean}
@readOnly
*/
isDirty: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `saving` state. A
record enters the saving state when `save` is called, but the
adapter has not yet acknowledged that the changes have been
persisted to the backend.
Example
```javascript
var record = store.createRecord('model');
record.get('isSaving'); // false
var promise = record.save();
record.get('isSaving'); // true
promise.then(function() {
record.get('isSaving'); // false
});
```
@property isSaving
@type {Boolean}
@readOnly
*/
isSaving: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `deleted` state
and has been marked for deletion. When `isDeleted` is true and
`isDirty` is true, the record is deleted locally but the deletion
was not yet persisted. When `isSaving` is true, the change is
in-flight. When both `isDirty` and `isSaving` are false, the
change has persisted.
Example
```javascript
var record = store.createRecord('model');
record.get('isDeleted'); // false
record.deleteRecord();
// Locally deleted
record.get('isDeleted'); // true
record.get('isDirty'); // true
record.get('isSaving'); // false
// Persisting the deletion
var promise = record.save();
record.get('isDeleted'); // true
record.get('isSaving'); // true
// Deletion Persisted
promise.then(function() {
record.get('isDeleted'); // true
record.get('isSaving'); // false
record.get('isDirty'); // false
});
```
@property isDeleted
@type {Boolean}
@readOnly
*/
isDeleted: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `new` state. A
record will be in the `new` state when it has been created on the
client and the adapter has not yet report that it was successfully
saved.
Example
```javascript
var record = store.createRecord('model');
record.get('isNew'); // true
record.save().then(function(model) {
model.get('isNew'); // false
});
```
@property isNew
@type {Boolean}
@readOnly
*/
isNew: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If this property is `true` the record is in the `valid` state.
A record will be in the `valid` state when the adapter did not report any
server-side validation failures.
@property isValid
@type {Boolean}
@readOnly
*/
isValid: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If the record is in the dirty state this property will report what
kind of change has caused it to move into the dirty
state. Possible values are:
- `created` The record has been created by the client and not yet saved to the adapter.
- `updated` The record has been updated by the client and not yet saved to the adapter.
- `deleted` The record has been deleted by the client and not yet saved to the adapter.
Example
```javascript
var record = store.createRecord('model');
record.get('dirtyType'); // 'created'
```
@property dirtyType
@type {String}
@readOnly
*/
dirtyType: ember$data$lib$system$model$model$$retrieveFromCurrentState,
/**
If `true` the adapter reported that it was unable to save local
changes to the backend for any reason other than a server-side
validation error.
Example
```javascript
record.get('isError'); // false
record.set('foo', 'valid value');
record.save().then(null, function() {
record.get('isError'); // true
});
```
@property isError
@type {Boolean}
@readOnly
*/
isError: false,
/**
If `true` the store is attempting to reload the record form the adapter.
Example
```javascript
record.get('isReloading'); // false
record.reload();
record.get('isReloading'); // true
```
@property isReloading
@type {Boolean}
@readOnly
*/
isReloading: false,
/**
All ember models have an id property. This is an identifier
managed by an external source. These are always coerced to be
strings before being used internally. Note when declaring the
attributes for a model it is an error to declare an id
attribute.
```javascript
var record = store.createRecord('model');
record.get('id'); // null
store.find('model', 1).then(function(model) {
model.get('id'); // '1'
});
```
@property id
@type {String}
*/
id: null,
/**
@property currentState
@private
@type {Object}
*/
/**
When the record is in the `invalid` state this object will contain
any errors returned by the adapter. When present the errors hash
contains keys corresponding to the invalid property names
and values which are arrays of Javascript objects with two keys:
- `message` A string containing the error message from the backend
- `attribute` The name of the property associated with this error message
```javascript
record.get('errors.length'); // 0
record.set('foo', 'invalid value');
record.save().catch(function() {
record.get('errors').get('foo');
// [{message: 'foo should be a number.', attribute: 'foo'}]
});
```
The `errors` property us useful for displaying error messages to
the user.
```handlebars
<label>Username: {{input value=username}} </label>
{{#each model.errors.username as |error|}}
<div class="error">
{{error.message}}
</div>
{{/each}}
<label>Email: {{input value=email}} </label>
{{#each model.errors.email as |error|}}
<div class="error">
{{error.message}}
</div>
{{/each}}
```
You can also access the special `messages` property on the error
object to get an array of all the error strings.
```handlebars
{{#each model.errors.messages as |message|}}
<div class="error">
{{message}}
</div>
{{/each}}
```
@property errors
@type {DS.Errors}
*/
errors: Ember.computed(function () {
return this._internalModel.getErrors();
}).readOnly(),
/**
Create a JSON representation of the record, using the serialization
strategy of the store's adapter.
`serialize` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method serialize
@param {Object} options
@return {Object} an object whose values are primitive JSON values only
*/
serialize: function (options) {
return this.store.serialize(this, options);
},
/**
Use [DS.JSONSerializer](DS.JSONSerializer.html) to
get the JSON representation of a record.
`toJSON` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method toJSON
@param {Object} options
@return {Object} A JSON representation of the object.
*/
toJSON: function (options) {
// container is for lazy transform lookups
var serializer = this.store.serializerFor('-default');
var snapshot = this._internalModel.createSnapshot();
return serializer.serialize(snapshot, options);
},
/**
Fired when the record is ready to be interacted with,
that is either loaded from the server or created locally.
@event ready
*/
ready: Ember.K,
/**
Fired when the record is loaded from the server.
@event didLoad
*/
didLoad: Ember.K,
/**
Fired when the record is updated.
@event didUpdate
*/
didUpdate: Ember.K,
/**
Fired when a new record is commited to the server.
@event didCreate
*/
didCreate: Ember.K,
/**
Fired when the record is deleted.
@event didDelete
*/
didDelete: Ember.K,
/**
Fired when the record becomes invalid.
@event becameInvalid
*/
becameInvalid: Ember.K,
/**
Fired when the record enters the error state.
@event becameError
*/
becameError: Ember.K,
/**
Fired when the record is rolled back.
@event rolledBack
*/
rolledBack: Ember.K,
/**
@property data
@private
@type {Object}
*/
data: Ember.computed.readOnly('_internalModel._data'),
//TODO Do we want to deprecate these?
/**
@method send
@private
@param {String} name
@param {Object} context
*/
send: function (name, context) {
return this._internalModel.send(name, context);
},
/**
@method transitionTo
@private
@param {String} name
*/
transitionTo: function (name) {
return this._internalModel.transitionTo(name);
},
/**
Marks the record as deleted but does not save it. You must call
`save` afterwards if you want to persist it. You might use this
method if you want to allow the user to still `rollback()` a
delete after it was made.
Example
```app/routes/model/delete.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
softDelete: function() {
this.controller.get('model').deleteRecord();
},
confirm: function() {
this.controller.get('model').save();
},
undo: function() {
this.controller.get('model').rollback();
}
}
});
```
@method deleteRecord
*/
deleteRecord: function () {
this._internalModel.deleteRecord();
},
/**
Same as `deleteRecord`, but saves the record immediately.
Example
```app/routes/model/delete.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
delete: function() {
var controller = this.controller;
controller.get('model').destroyRecord().then(function() {
controller.transitionToRoute('model.index');
});
}
}
});
```
@method destroyRecord
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
destroyRecord: function () {
this.deleteRecord();
return this.save();
},
/**
@method unloadRecord
@private
*/
unloadRecord: function () {
if (this.isDestroyed) {
return;
}
this._internalModel.unloadRecord();
},
/**
@method _notifyProperties
@private
*/
_notifyProperties: function (keys) {
Ember.beginPropertyChanges();
var key;
for (var i = 0, length = keys.length; i < length; i++) {
key = keys[i];
this.notifyPropertyChange(key);
}
Ember.endPropertyChanges();
},
/**
Returns an object, whose keys are changed properties, and value is
an [oldProp, newProp] array.
Example
```app/models/mascot.js
import DS from 'ember-data';
export default DS.Model.extend({
name: attr('string')
});
```
```javascript
var mascot = store.createRecord('mascot');
mascot.changedAttributes(); // {}
mascot.set('name', 'Tomster');
mascot.changedAttributes(); // {name: [undefined, 'Tomster']}
```
@method changedAttributes
@return {Object} an object, whose keys are changed properties,
and value is an [oldProp, newProp] array.
*/
changedAttributes: function () {
var oldData = ember$data$lib$system$model$model$$get(this._internalModel, '_data');
var newData = ember$data$lib$system$model$model$$get(this._internalModel, '_attributes');
var diffData = Ember.create(null);
var prop;
for (prop in newData) {
diffData[prop] = [oldData[prop], newData[prop]];
}
return diffData;
},
//TODO discuss with tomhuda about events/hooks
//Bring back as hooks?
/**
@method adapterWillCommit
@private
adapterWillCommit: function() {
this.send('willCommit');
},
/**
@method adapterDidDirty
@private
adapterDidDirty: function() {
this.send('becomeDirty');
this.updateRecordArraysLater();
},
*/
/**
If the model `isDirty` this function will discard any unsaved
changes. If the model `isNew` it will be removed from the store.
Example
```javascript
record.get('name'); // 'Untitled Document'
record.set('name', 'Doc 1');
record.get('name'); // 'Doc 1'
record.rollback();
record.get('name'); // 'Untitled Document'
```
@method rollback
*/
rollback: function () {
this._internalModel.rollback();
},
/*
@method _createSnapshot
@private
*/
_createSnapshot: function () {
return this._internalModel.createSnapshot();
},
toStringExtension: function () {
return ember$data$lib$system$model$model$$get(this, 'id');
},
/**
Save the record and persist any changes to the record to an
external source via the adapter.
Example
```javascript
record.set('name', 'Tomster');
record.save().then(function() {
// Success callback
}, function() {
// Error callback
});
```
@method save
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
save: function () {
var model = this;
return ember$data$lib$system$promise$proxies$$PromiseObject.create({
promise: this._internalModel.save().then(function () {
return model;
})
});
},
/**
Reload the record from the adapter.
This will only work if the record has already finished loading
and has not yet been modified (`isLoaded` but not `isDirty`,
or `isSaving`).
Example
```app/routes/model/view.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
reload: function() {
this.controller.get('model').reload().then(function(model) {
// do something with the reloaded model
});
}
}
});
```
@method reload
@return {Promise} a promise that will be resolved with the record when the
adapter returns successfully or rejected if the adapter returns
with an error.
*/
reload: function () {
var model = this;
return ember$data$lib$system$promise$proxies$$PromiseObject.create({
promise: this._internalModel.reload().then(function () {
return model;
})
});
},
/**
Override the default event firing from Ember.Evented to
also call methods with the given name.
@method trigger
@private
@param {String} name
*/
trigger: function (name) {
var length = arguments.length;
var args = new Array(length - 1);
for (var i = 1; i < length; i++) {
args[i - 1] = arguments[i];
}
Ember.tryInvoke(this, name, args);
this._super.apply(this, arguments);
},
willDestroy: function () {
//TODO Move!
this._internalModel.clearRelationships();
this._internalModel.recordObjectWillDestroy();
this._super.apply(this, arguments);
//TODO should we set internalModel to null here?
},
// This is a temporary solution until we refactor DS.Model to not
// rely on the data property.
willMergeMixin: function (props) {
var constructor = this.constructor;
},
attr: function () {
},
belongsTo: function () {
},
hasMany: function () {
}
});
ember$data$lib$system$model$model$$Model.reopenClass({
/**
Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model
instances from within the store, but if end users accidentally call `create()`
(instead of `createRecord()`), we can raise an error.
@method _create
@private
@static
*/
_create: ember$data$lib$system$model$model$$Model.create,
/**
Override the class' `create()` method to raise an error. This
prevents end users from inadvertently calling `create()` instead
of `createRecord()`. The store is still able to create instances
by calling the `_create()` method. To create an instance of a
`DS.Model` use [store.createRecord](DS.Store.html#method_createRecord).
@method create
@private
@static
*/
create: function () {
throw new Ember.Error('You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set.');
},
/**
Represents the model's class name as a string. This can be used to look up the model through
DS.Store's modelFor method.
`modelName` is generated for you by Ember Data. It will be a lowercased, dasherized string.
For example:
```javascript
store.modelFor('post').modelName; // 'post'
store.modelFor('blog-post').modelName; // 'blog-post'
```
The most common place you'll want to access `modelName` is in your serializer's `payloadKeyFromModelName` method. For example, to change payload
keys to underscore (instead of dasherized), you might use the following code:
```javascript
export default var PostSerializer = DS.RESTSerializer.extend({
payloadKeyFromModelName: function(modelName) {
return Ember.String.underscore(modelName);
}
});
```
@property
@type String
@readonly
*/
modelName: null
});
var ember$data$lib$system$model$model$$default = ember$data$lib$system$model$model$$Model;
var ember$data$lib$utils$supports$computed$getter$setter$$supportsComputedGetterSetter;
try {
Ember.computed({
get: function () {},
set: function () {}
});
ember$data$lib$utils$supports$computed$getter$setter$$supportsComputedGetterSetter = true;
} catch (e) {
ember$data$lib$utils$supports$computed$getter$setter$$supportsComputedGetterSetter = false;
}
var ember$data$lib$utils$supports$computed$getter$setter$$default = ember$data$lib$utils$supports$computed$getter$setter$$supportsComputedGetterSetter;
var ember$data$lib$utils$computed$polyfill$$computed = Ember.computed;
var ember$data$lib$utils$computed$polyfill$$default = function () {
var polyfillArguments = [];
var config = arguments[arguments.length - 1];
if (typeof config === 'function' || ember$data$lib$utils$supports$computed$getter$setter$$default) {
return ember$data$lib$utils$computed$polyfill$$computed.apply(null, arguments);
}
for (var i = 0, l = arguments.length - 1; i < l; i++) {
polyfillArguments.push(arguments[i]);
}
var func;
if (config.set) {
func = function (key, value) {
if (arguments.length > 1) {
return config.set.call(this, key, value);
} else {
return config.get.call(this, key);
}
};
} else {
func = function (key) {
return config.get.call(this, key);
};
}
polyfillArguments.push(func);
return ember$data$lib$utils$computed$polyfill$$computed.apply(null, polyfillArguments);
};
var ember$data$lib$system$model$attributes$$default = ember$data$lib$system$model$attributes$$attr;
/**
@module ember-data
*/
var ember$data$lib$system$model$attributes$$get = Ember.get;
/**
@class Model
@namespace DS
*/
ember$data$lib$system$model$model$$default.reopenClass({
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are the meta object for the
property.
Example
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: attr('string'),
lastName: attr('string'),
birthday: attr('date')
});
```
```javascript
import Ember from 'ember';
import Person from 'app/models/person';
var attributes = Ember.get(Person, 'attributes')
attributes.forEach(function(name, meta) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@property attributes
@static
@type {Ember.Map}
@readOnly
*/
attributes: Ember.computed(function () {
var map = ember$data$lib$system$map$$Map.create();
this.eachComputedProperty(function (name, meta) {
if (meta.isAttribute) {
meta.name = name;
map.set(name, meta);
}
});
return map;
}).readOnly(),
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are type of transformation
applied to each attribute. This map does not include any
attributes that do not have an transformation type.
Example
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: attr(),
lastName: attr('string'),
birthday: attr('date')
});
```
```javascript
import Ember from 'ember';
import Person from 'app/models/person';
var transformedAttributes = Ember.get(Person, 'transformedAttributes')
transformedAttributes.forEach(function(field, type) {
console.log(field, type);
});
// prints:
// lastName string
// birthday date
```
@property transformedAttributes
@static
@type {Ember.Map}
@readOnly
*/
transformedAttributes: Ember.computed(function () {
var map = ember$data$lib$system$map$$Map.create();
this.eachAttribute(function (key, meta) {
if (meta.type) {
map.set(key, meta.type);
}
});
return map;
}).readOnly(),
/**
Iterates through the attributes of the model, calling the passed function on each
attribute.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, meta);
```
- `name` the name of the current property in the iteration
- `meta` the meta object for the attribute property in the iteration
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
import DS from 'ember-data';
var Person = DS.Model.extend({
firstName: attr('string'),
lastName: attr('string'),
birthday: attr('date')
});
Person.eachAttribute(function(name, meta) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@method eachAttribute
@param {Function} callback The callback to execute
@param {Object} [binding] the value to which the callback's `this` should be bound
@static
*/
eachAttribute: function (callback, binding) {
ember$data$lib$system$model$attributes$$get(this, "attributes").forEach(function (meta, name) {
callback.call(binding, name, meta);
}, binding);
},
/**
Iterates through the transformedAttributes of the model, calling
the passed function on each attribute. Note the callback will not be
called for any attributes that do not have an transformation type.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, type);
```
- `name` the name of the current property in the iteration
- `type` a string containing the name of the type of transformed
applied to the attribute
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
import DS from 'ember-data';
var Person = DS.Model.extend({
firstName: attr(),
lastName: attr('string'),
birthday: attr('date')
});
Person.eachTransformedAttribute(function(name, type) {
console.log(name, type);
});
// prints:
// lastName string
// birthday date
```
@method eachTransformedAttribute
@param {Function} callback The callback to execute
@param {Object} [binding] the value to which the callback's `this` should be bound
@static
*/
eachTransformedAttribute: function (callback, binding) {
ember$data$lib$system$model$attributes$$get(this, "transformedAttributes").forEach(function (type, name) {
callback.call(binding, name, type);
});
}
});
ember$data$lib$system$model$model$$default.reopen({
eachAttribute: function (callback, binding) {
this.constructor.eachAttribute(callback, binding);
}
});
function ember$data$lib$system$model$attributes$$getDefaultValue(record, options, key) {
if (typeof options.defaultValue === "function") {
return options.defaultValue.apply(null, arguments);
} else {
return options.defaultValue;
}
}
function ember$data$lib$system$model$attributes$$hasValue(record, key) {
return key in record._attributes || key in record._inFlightAttributes || key in record._data;
}
function ember$data$lib$system$model$attributes$$getValue(record, key) {
if (key in record._attributes) {
return record._attributes[key];
} else if (key in record._inFlightAttributes) {
return record._inFlightAttributes[key];
} else {
return record._data[key];
}
}
/**
`DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html).
By default, attributes are passed through as-is, however you can specify an
optional type to have the value automatically transformed.
Ember Data ships with four basic transform types: `string`, `number`,
`boolean` and `date`. You can define your own transforms by subclassing
[DS.Transform](/api/data/classes/DS.Transform.html).
Note that you cannot use `attr` to define an attribute of `id`.
`DS.attr` takes an optional hash as a second parameter, currently
supported options are:
- `defaultValue`: Pass a string or a function to be called to set the attribute
to a default value if none is supplied.
Example
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
username: DS.attr('string'),
email: DS.attr('string'),
verified: DS.attr('boolean', {defaultValue: false})
});
```
Default value can also be a function. This is useful it you want to return
a new object for each attribute.
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
username: attr('string'),
email: attr('string'),
settings: attr({defaultValue: function() {
return {};
}})
});
```
@namespace
@method attr
@for DS
@param {String} type the attribute type
@param {Object} options a hash of options
@return {Attribute}
*/
function ember$data$lib$system$model$attributes$$attr(type, options) {
if (typeof type === "object") {
options = type;
type = undefined;
} else {
options = options || {};
}
var meta = {
type: type,
isAttribute: true,
options: options
};
return ember$data$lib$utils$computed$polyfill$$default({
get: function (key) {
var internalModel = this._internalModel;
if (ember$data$lib$system$model$attributes$$hasValue(internalModel, key)) {
return ember$data$lib$system$model$attributes$$getValue(internalModel, key);
} else {
return ember$data$lib$system$model$attributes$$getDefaultValue(this, options, key);
}
},
set: function (key, value) {
var internalModel = this._internalModel;
var oldValue = ember$data$lib$system$model$attributes$$getValue(internalModel, key);
if (value !== oldValue) {
// Add the new value to the changed attributes hash; it will get deleted by
// the 'didSetProperty' handler if it is no different from the original value
internalModel._attributes[key] = value;
this._internalModel.send("didSetProperty", {
name: key,
oldValue: oldValue,
originalValue: internalModel._data[key],
value: value
});
}
return value;
}
}).meta(meta);
}
var ember$data$lib$system$model$$default = ember$data$lib$system$model$model$$default;
var ember$data$lib$system$store$$Backburner = Ember.Backburner || Ember.__loader.require("backburner")["default"] || Ember.__loader.require("backburner")["Backburner"];
//Shim Backburner.join
if (!ember$data$lib$system$store$$Backburner.prototype.join) {
var ember$data$lib$system$store$$isString = function (suspect) {
return typeof suspect === "string";
};
ember$data$lib$system$store$$Backburner.prototype.join = function () {
var method, target;
if (this.currentInstance) {
var length = arguments.length;
if (length === 1) {
method = arguments[0];
target = null;
} else {
target = arguments[0];
method = arguments[1];
}
if (ember$data$lib$system$store$$isString(method)) {
method = target[method];
}
if (length === 1) {
return method();
} else if (length === 2) {
return method.call(target);
} else {
var args = new Array(length - 2);
for (var i = 0, l = length - 2; i < l; i++) {
args[i] = arguments[i + 2];
}
return method.apply(target, args);
}
} else {
return this.run.apply(this, arguments);
}
};
}
//Get the materialized model from the internalModel/promise that returns
//an internal model and return it in a promiseObject. Useful for returning
//from find methods
function ember$data$lib$system$store$$promiseRecord(internalModel, label) {
//TODO cleanup
var toReturn = internalModel;
if (!internalModel.then) {
toReturn = internalModel.getRecord();
} else {
toReturn = internalModel.then(function (model) {
return model.getRecord();
});
}
return ember$data$lib$system$promise$proxies$$promiseObject(toReturn, label);
}
var ember$data$lib$system$store$$get = Ember.get;
var ember$data$lib$system$store$$set = Ember.set;
var ember$data$lib$system$store$$once = Ember.run.once;
var ember$data$lib$system$store$$isNone = Ember.isNone;
var ember$data$lib$system$store$$forEach = Ember.EnumerableUtils.forEach;
var ember$data$lib$system$store$$indexOf = Ember.EnumerableUtils.indexOf;
var ember$data$lib$system$store$$map = Ember.EnumerableUtils.map;
var ember$data$lib$system$store$$Promise = Ember.RSVP.Promise;
var ember$data$lib$system$store$$copy = Ember.copy;
var ember$data$lib$system$store$$Store;
var ember$data$lib$system$store$$Service = Ember.Service;
if (!ember$data$lib$system$store$$Service) {
ember$data$lib$system$store$$Service = Ember.Object;
}
// Implementors Note:
//
// The variables in this file are consistently named according to the following
// scheme:
//
// * +id+ means an identifier managed by an external source, provided inside
// the data provided by that source. These are always coerced to be strings
// before being used internally.
// * +clientId+ means a transient numerical identifier generated at runtime by
// the data store. It is important primarily because newly created objects may
// not yet have an externally generated id.
// * +internalModel+ means a record internalModel object, which holds metadata about a
// record, even if it has not yet been fully materialized.
// * +type+ means a DS.Model.
/**
The store contains all of the data for records loaded from the server.
It is also responsible for creating instances of `DS.Model` that wrap
the individual data for a record, so that they can be bound to in your
Handlebars templates.
Define your application's store like this:
```app/stores/application.js
import DS from 'ember-data';
export default DS.Store.extend({
});
```
Most Ember.js applications will only have a single `DS.Store` that is
automatically created by their `Ember.Application`.
You can retrieve models from the store in several ways. To retrieve a record
for a specific id, use `DS.Store`'s `find()` method:
```javascript
store.find('person', 123).then(function (person) {
});
```
By default, the store will talk to your backend using a standard
REST mechanism. You can customize how the store talks to your
backend by specifying a custom adapter:
```app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
});
```
You can learn more about writing a custom adapter by reading the `DS.Adapter`
documentation.
### Store createRecord() vs. push() vs. pushPayload()
The store provides multiple ways to create new record objects. They have
some subtle differences in their use which are detailed below:
[createRecord](#method_createRecord) is used for creating new
records on the client side. This will return a new record in the
`created.uncommitted` state. In order to persist this record to the
backend you will need to call `record.save()`.
[push](#method_push) is used to notify Ember Data's store of new or
updated records that exist in the backend. This will return a record
in the `loaded.saved` state. The primary use-case for `store#push` is
to notify Ember Data about record updates (full or partial) that happen
outside of the normal adapter methods (for example
[SSE](http://dev.w3.org/html5/eventsource/) or [Web
Sockets](http://www.w3.org/TR/2009/WD-websockets-20091222/)).
[pushPayload](#method_pushPayload) is a convenience wrapper for
`store#push` that will deserialize payloads if the
Serializer implements a `pushPayload` method.
Note: When creating a new record using any of the above methods
Ember Data will update `DS.RecordArray`s such as those returned by
`store#all()`, `store#findAll()` or `store#filter()`. This means any
data bindings or computed properties that depend on the RecordArray
will automatically be synced to include the new or updated record
values.
@class Store
@namespace DS
@extends Ember.Service
*/
ember$data$lib$system$store$$Store = ember$data$lib$system$store$$Service.extend({
/**
@method init
@private
*/
init: function () {
this._backburner = new ember$data$lib$system$store$$Backburner(["normalizeRelationships", "syncRelationships", "finished"]);
// internal bookkeeping; not observable
this.typeMaps = {};
this.recordArrayManager = ember$data$lib$system$record$array$manager$$default.create({
store: this
});
this._pendingSave = [];
this._instanceCache = new ember$data$lib$system$store$container$instance$cache$$default(this.container);
//Used to keep track of all the find requests that need to be coalesced
this._pendingFetch = ember$data$lib$system$map$$Map.create();
},
/**
The adapter to use to communicate to a backend server or other persistence layer.
This can be specified as an instance, class, or string.
If you want to specify `app/adapters/custom.js` as a string, do:
```js
adapter: 'custom'
```
@property adapter
@default DS.RESTAdapter
@type {(DS.Adapter|String)}
*/
adapter: "-rest",
/**
Returns a JSON representation of the record using a custom
type-specific serializer, if one exists.
The available options are:
* `includeId`: `true` if the record's ID should be included in
the JSON representation
@method serialize
@private
@param {DS.Model} record the record to serialize
@param {Object} options an options hash
*/
serialize: function (record, options) {
var snapshot = record._internalModel.createSnapshot();
return snapshot.serialize(options);
},
/**
This property returns the adapter, after resolving a possible
string key.
If the supplied `adapter` was a class, or a String property
path resolved to a class, this property will instantiate the
class.
This property is cacheable, so the same instance of a specified
adapter class should be used for the lifetime of the store.
@property defaultAdapter
@private
@return DS.Adapter
*/
defaultAdapter: Ember.computed("adapter", function () {
var adapter = ember$data$lib$system$store$$get(this, "adapter");
adapter = this.retrieveManagedInstance("adapter", adapter);
return adapter;
}),
// .....................
// . CREATE NEW RECORD .
// .....................
/**
Create a new record in the current store. The properties passed
to this method are set on the newly created record.
To create a new instance of `App.Post`:
```js
store.createRecord('post', {
title: "Rails is omakase"
});
```
@method createRecord
@param {String} modelName
@param {Object} inputProperties a hash of properties to set on the
newly created record.
@return {DS.Model} record
*/
createRecord: function (modelName, inputProperties) {
var typeClass = this.modelFor(modelName);
var properties = ember$data$lib$system$store$$copy(inputProperties) || Ember.create(null);
// If the passed properties do not include a primary key,
// give the adapter an opportunity to generate one. Typically,
// client-side ID generators will use something like uuid.js
// to avoid conflicts.
if (ember$data$lib$system$store$$isNone(properties.id)) {
properties.id = this._generateId(modelName, properties);
}
// Coerce ID to a string
properties.id = ember$data$lib$system$coerce$id$$default(properties.id);
var internalModel = this.buildInternalModel(typeClass, properties.id);
var record = internalModel.getRecord();
// Move the record out of its initial `empty` state into
// the `loaded` state.
internalModel.loadedData();
// Set the properties specified on the record.
record.setProperties(properties);
internalModel.eachRelationship(function (key, descriptor) {
internalModel._relationships.get(key).setHasData(true);
});
return record;
},
/**
If possible, this method asks the adapter to generate an ID for
a newly created record.
@method _generateId
@private
@param {String} modelName
@param {Object} properties from the new record
@return {String} if the adapter can generate one, an ID
*/
_generateId: function (modelName, properties) {
var adapter = this.adapterFor(modelName);
if (adapter && adapter.generateIdForRecord) {
return adapter.generateIdForRecord(this, modelName, properties);
}
return null;
},
// .................
// . DELETE RECORD .
// .................
/**
For symmetry, a record can be deleted via the store.
Example
```javascript
var post = store.createRecord('post', {
title: "Rails is omakase"
});
store.deleteRecord(post);
```
@method deleteRecord
@param {DS.Model} record
*/
deleteRecord: function (record) {
record.deleteRecord();
},
/**
For symmetry, a record can be unloaded via the store. Only
non-dirty records can be unloaded.
Example
```javascript
store.find('post', 1).then(function(post) {
store.unloadRecord(post);
});
```
@method unloadRecord
@param {DS.Model} record
*/
unloadRecord: function (record) {
record.unloadRecord();
},
// ................
// . FIND RECORDS .
// ................
/**
This is the main entry point into finding records. The first parameter to
this method is the model's name as a string.
---
To find a record by ID, pass the `id` as the second parameter:
```javascript
store.find('person', 1);
```
The `find` method will always return a **promise** that will be resolved
with the record. If the record was already in the store, the promise will
be resolved immediately. Otherwise, the store will ask the adapter's `find`
method to find the necessary data.
The `find` method will always resolve its promise with the same object for
a given type and `id`.
---
You can optionally `preload` specific attributes and relationships that you know of
by passing them as the third argument to find.
For example, if your Ember route looks like `/posts/1/comments/2` and your API route
for the comment also looks like `/posts/1/comments/2` if you want to fetch the comment
without fetching the post you can pass in the post to the `find` call:
```javascript
store.find('comment', 2, {post: 1});
```
If you have access to the post model you can also pass the model itself:
```javascript
store.find('post', 1).then(function (myPostModel) {
store.find('comment', 2, {post: myPostModel});
});
```
This way, your adapter's `find` or `buildURL` method will be able to look up the
relationship on the record and construct the nested URL without having to first
fetch the post.
---
To find all records for a type, call `find` with no additional parameters:
```javascript
store.find('person');
```
This will ask the adapter's `findAll` method to find the records for the
given type, and return a promise that will be resolved once the server
returns the values. The promise will resolve into all records of this type
present in the store, even if the server only returns a subset of them.
---
To find a record by a query, call `find` with a hash as the second
parameter:
```javascript
store.find('person', { page: 1 });
```
By passing an object `{page: 1}` as an argument to the find method, it
delegates to the adapter's findQuery method. The adapter then makes
a call to the server, transforming the object `{page: 1}` as parameters
that are sent along, and will return a RecordArray when the promise
resolves.
Exposing queries this way seems preferable to creating an abstract query
language for all server-side queries, and then require all adapters to
implement them.
The call made to the server, using a Rails backend, will look something like this:
```
Started GET "/api/v1/person?page=1"
Processing by Api::V1::PersonsController#index as HTML
Parameters: {"page"=>"1"}
```
If you do something like this:
```javascript
store.find('person', {ids: [1, 2, 3]});
```
The call to the server, using a Rails backend, will look something like this:
```
Started GET "/api/v1/person?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3"
Processing by Api::V1::PersonsController#index as HTML
Parameters: {"ids"=>["1", "2", "3"]}
```
@method find
@param {String} modelName
@param {(Object|String|Integer|null)} id
@param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models
@return {Promise} promise
*/
find: function (modelName, id, preload) {
if (arguments.length === 1) {
return this.findAll(modelName);
}
// We are passed a query instead of an id.
if (Ember.typeOf(id) === "object") {
return this.findQuery(modelName, id);
}
return this.findById(modelName, ember$data$lib$system$coerce$id$$default(id), preload);
},
/**
This method returns a fresh record for a given type and id combination.
If a record is available for the given type/id combination, then
it will fetch this record from the store and call `reload()` on it.
That will fire a request to server and return a promise that will
resolve once the record has been reloaded.
If there's no record corresponding in the store it will simply call
`store.find`.
Example
```app/routes/post.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function(params) {
return this.store.fetchById('post', params.post_id);
}
});
```
@method fetchById
@param {String} modelName
@param {(String|Integer)} id
@param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models
@return {Promise} promise
*/
fetchById: function (modelName, id, preload) {
if (this.hasRecordForId(modelName, id)) {
return this.getById(modelName, id).reload();
} else {
return this.find(modelName, id, preload);
}
},
/**
This method returns a fresh collection from the server, regardless of if there is already records
in the store or not.
@method fetchAll
@param {String} modelName
@return {Promise} promise
*/
fetchAll: function (modelName) {
var typeClass = this.modelFor(modelName);
return this._fetchAll(typeClass, this.all(modelName));
},
/**
@method fetch
@param {String} modelName
@param {(String|Integer)} id
@param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models
@return {Promise} promise
@deprecated Use [fetchById](#method_fetchById) instead
*/
fetch: function (modelName, id, preload) {
return this.fetchById(modelName, id, preload);
},
/**
This method returns a record for a given type and id combination.
@method findById
@private
@param {String} modelName
@param {(String|Integer)} id
@param {Object} preload - optional set of attributes and relationships passed in either as IDs or as actual models
@return {Promise} promise
*/
findById: function (modelName, id, preload) {
var internalModel = this._internalModelForId(modelName, id);
return this._findByInternalModel(internalModel, preload);
},
_findByInternalModel: function (internalModel, preload) {
var fetchedInternalModel;
if (preload) {
internalModel._preloadData(preload);
}
if (internalModel.isEmpty()) {
fetchedInternalModel = this.scheduleFetch(internalModel);
//TODO double check about reloading
} else if (internalModel.isLoading()) {
fetchedInternalModel = internalModel._loadingPromise;
}
return ember$data$lib$system$store$$promiseRecord(fetchedInternalModel || internalModel, "DS: Store#findByRecord " + internalModel.typeKey + " with id: " + ember$data$lib$system$store$$get(internalModel, "id"));
},
/**
This method makes a series of requests to the adapter's `find` method
and returns a promise that resolves once they are all loaded.
@private
@method findByIds
@param {String} modelName
@param {Array} ids
@return {Promise} promise
*/
findByIds: function (modelName, ids) {
var store = this;
return ember$data$lib$system$promise$proxies$$promiseArray(Ember.RSVP.all(ember$data$lib$system$store$$map(ids, function (id) {
return store.findById(modelName, id);
})).then(Ember.A, null, "DS: Store#findByIds of " + modelName + " complete"));
},
/**
This method is called by `findById` if it discovers that a particular
type/id pair hasn't been loaded yet to kick off a request to the
adapter.
@method fetchRecord
@private
@param {InternalModel} internalModel model
@return {Promise} promise
*/
fetchRecord: function (internalModel) {
var typeClass = internalModel.type;
var id = internalModel.id;
var adapter = this.adapterFor(typeClass.modelName);
var promise = ember$data$lib$system$store$finders$$_find(adapter, this, typeClass, id, internalModel);
return promise;
},
scheduleFetchMany: function (records) {
var internalModels = ember$data$lib$system$store$$map(records, function (record) {
return record._internalModel;
});
return ember$data$lib$system$store$$Promise.all(ember$data$lib$system$store$$map(internalModels, this.scheduleFetch, this));
},
scheduleFetch: function (internalModel) {
var typeClass = internalModel.type;
if (internalModel._loadingPromise) {
return internalModel._loadingPromise;
}
var resolver = Ember.RSVP.defer("Fetching " + typeClass + "with id: " + internalModel.id);
var recordResolverPair = {
record: internalModel,
resolver: resolver
};
var promise = resolver.promise;
internalModel.loadingData(promise);
if (!this._pendingFetch.get(typeClass)) {
this._pendingFetch.set(typeClass, [recordResolverPair]);
} else {
this._pendingFetch.get(typeClass).push(recordResolverPair);
}
Ember.run.scheduleOnce("afterRender", this, this.flushAllPendingFetches);
return promise;
},
flushAllPendingFetches: function () {
if (this.isDestroyed || this.isDestroying) {
return;
}
this._pendingFetch.forEach(this._flushPendingFetchForType, this);
this._pendingFetch = ember$data$lib$system$map$$Map.create();
},
_flushPendingFetchForType: function (recordResolverPairs, typeClass) {
var store = this;
var adapter = store.adapterFor(typeClass.modelName);
var shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests;
var records = Ember.A(recordResolverPairs).mapBy("record");
function _fetchRecord(recordResolverPair) {
recordResolverPair.resolver.resolve(store.fetchRecord(recordResolverPair.record));
}
function resolveFoundRecords(records) {
ember$data$lib$system$store$$forEach(records, function (record) {
var pair = Ember.A(recordResolverPairs).findBy("record", record);
if (pair) {
var resolver = pair.resolver;
resolver.resolve(record);
}
});
return records;
}
function makeMissingRecordsRejector(requestedRecords) {
return function rejectMissingRecords(resolvedRecords) {
resolvedRecords = Ember.A(resolvedRecords);
var missingRecords = requestedRecords.reject(function (record) {
return resolvedRecords.contains(record);
});
if (missingRecords.length) {
}
rejectRecords(missingRecords);
};
}
function makeRecordsRejector(records) {
return function (error) {
rejectRecords(records, error);
};
}
function rejectRecords(records, error) {
ember$data$lib$system$store$$forEach(records, function (record) {
var pair = Ember.A(recordResolverPairs).findBy("record", record);
if (pair) {
var resolver = pair.resolver;
resolver.reject(error);
}
});
}
if (recordResolverPairs.length === 1) {
_fetchRecord(recordResolverPairs[0]);
} else if (shouldCoalesce) {
// TODO: Improve records => snapshots => records => snapshots
//
// We want to provide records to all store methods and snapshots to all
// adapter methods. To make sure we're doing that we're providing an array
// of snapshots to adapter.groupRecordsForFindMany(), which in turn will
// return grouped snapshots instead of grouped records.
//
// But since the _findMany() finder is a store method we need to get the
// records from the grouped snapshots even though the _findMany() finder
// will once again convert the records to snapshots for adapter.findMany()
var snapshots = Ember.A(records).invoke("createSnapshot");
var groups = adapter.groupRecordsForFindMany(this, snapshots);
ember$data$lib$system$store$$forEach(groups, function (groupOfSnapshots) {
var groupOfRecords = Ember.A(groupOfSnapshots).mapBy("_internalModel");
var requestedRecords = Ember.A(groupOfRecords);
var ids = requestedRecords.mapBy("id");
if (ids.length > 1) {
ember$data$lib$system$store$finders$$_findMany(adapter, store, typeClass, ids, requestedRecords).then(resolveFoundRecords).then(makeMissingRecordsRejector(requestedRecords)).then(null, makeRecordsRejector(requestedRecords));
} else if (ids.length === 1) {
var pair = Ember.A(recordResolverPairs).findBy("record", groupOfRecords[0]);
_fetchRecord(pair);
} else {
}
});
} else {
ember$data$lib$system$store$$forEach(recordResolverPairs, _fetchRecord);
}
},
/**
Get a record by a given type and ID without triggering a fetch.
This method will synchronously return the record if it is available in the store,
otherwise it will return `null`. A record is available if it has been fetched earlier, or
pushed manually into the store.
_Note: This is an synchronous method and does not return a promise._
```js
var post = store.getById('post', 1);
post.get('id'); // 1
```
@method getById
@param {String} modelName
@param {String|Integer} id
@return {DS.Model|null} record
*/
getById: function (modelName, id) {
if (this.hasRecordForId(modelName, id)) {
return this._internalModelForId(modelName, id).getRecord();
} else {
return null;
}
},
/**
This method is called by the record's `reload` method.
This method calls the adapter's `find` method, which returns a promise. When
**that** promise resolves, `reloadRecord` will resolve the promise returned
by the record's `reload`.
@method reloadRecord
@private
@param {DS.Model} internalModel
@return {Promise} promise
*/
reloadRecord: function (internalModel) {
var modelName = internalModel.type.modelName;
var adapter = this.adapterFor(modelName);
var id = internalModel.id;
return this.scheduleFetch(internalModel);
},
/**
Returns true if a record for a given type and ID is already loaded.
@method hasRecordForId
@param {(String|DS.Model)} modelName
@param {(String|Integer)} inputId
@return {Boolean}
*/
hasRecordForId: function (modelName, inputId) {
var typeClass = this.modelFor(modelName);
var id = ember$data$lib$system$coerce$id$$default(inputId);
var internalModel = this.typeMapFor(typeClass).idToRecord[id];
return !!internalModel && internalModel.isLoaded();
},
/**
Returns id record for a given type and ID. If one isn't already loaded,
it builds a new record and leaves it in the `empty` state.
@method recordForId
@private
@param {String} modelName
@param {(String|Integer)} id
@return {DS.Model} record
*/
recordForId: function (modelName, id) {
return this._internalModelForId(modelName, id).getRecord();
},
_internalModelForId: function (typeName, inputId) {
var typeClass = this.modelFor(typeName);
var id = ember$data$lib$system$coerce$id$$default(inputId);
var idToRecord = this.typeMapFor(typeClass).idToRecord;
var record = idToRecord[id];
if (!record || !idToRecord[id]) {
record = this.buildInternalModel(typeClass, id);
}
return record;
},
/**
@method findMany
@private
@param {Array} internalModels
@return {Promise} promise
*/
findMany: function (internalModels) {
var store = this;
return ember$data$lib$system$store$$Promise.all(ember$data$lib$system$store$$map(internalModels, function (internalModel) {
return store._findByInternalModel(internalModel);
}));
},
/**
If a relationship was originally populated by the adapter as a link
(as opposed to a list of IDs), this method is called when the
relationship is fetched.
The link (which is usually a URL) is passed through unchanged, so the
adapter can make whatever request it wants.
The usual use-case is for the server to register a URL as a link, and
then use that URL in the future to make a request for the relationship.
@method findHasMany
@private
@param {DS.Model} owner
@param {any} link
@param {(Relationship)} relationship
@return {Promise} promise
*/
findHasMany: function (owner, link, relationship) {
var adapter = this.adapterFor(owner.type.modelName);
return ember$data$lib$system$store$finders$$_findHasMany(adapter, this, owner, link, relationship);
},
/**
@method findBelongsTo
@private
@param {DS.Model} owner
@param {any} link
@param {Relationship} relationship
@return {Promise} promise
*/
findBelongsTo: function (owner, link, relationship) {
var adapter = this.adapterFor(owner.type.modelName);
return ember$data$lib$system$store$finders$$_findBelongsTo(adapter, this, owner, link, relationship);
},
/**
This method delegates a query to the adapter. This is the one place where
adapter-level semantics are exposed to the application.
Exposing queries this way seems preferable to creating an abstract query
language for all server-side queries, and then require all adapters to
implement them.
This method returns a promise, which is resolved with a `RecordArray`
once the server returns.
@method findQuery
@private
@param {String} modelName
@param {any} query an opaque query to be used by the adapter
@return {Promise} promise
*/
findQuery: function (modelName, query) {
var typeClass = this.modelFor(modelName);
var array = this.recordArrayManager.createAdapterPopulatedRecordArray(typeClass, query);
var adapter = this.adapterFor(modelName);
return ember$data$lib$system$promise$proxies$$promiseArray(ember$data$lib$system$store$finders$$_findQuery(adapter, this, typeClass, query, array));
},
/**
This method returns an array of all records adapter can find.
It triggers the adapter's `findAll` method to give it an opportunity to populate
the array with records of that type.
@method findAll
@private
@param {String} modelName
@return {DS.AdapterPopulatedRecordArray}
*/
findAll: function (modelName) {
return this.fetchAll(modelName);
},
/**
@method _fetchAll
@private
@param {DS.Model} typeClass
@param {DS.RecordArray} array
@return {Promise} promise
*/
_fetchAll: function (typeClass, array) {
var adapter = this.adapterFor(typeClass.modelName);
var sinceToken = this.typeMapFor(typeClass).metadata.since;
ember$data$lib$system$store$$set(array, "isUpdating", true);
return ember$data$lib$system$promise$proxies$$promiseArray(ember$data$lib$system$store$finders$$_findAll(adapter, this, typeClass, sinceToken));
},
/**
@method didUpdateAll
@param {DS.Model} typeClass
@private
*/
didUpdateAll: function (typeClass) {
var findAllCache = this.typeMapFor(typeClass).findAllCache;
ember$data$lib$system$store$$set(findAllCache, "isUpdating", false);
},
/**
This method returns a filtered array that contains all of the
known records for a given type in the store.
Note that because it's just a filter, the result will contain any
locally created records of the type, however, it will not make a
request to the backend to retrieve additional records. If you
would like to request all the records from the backend please use
[store.find](#method_find).
Also note that multiple calls to `all` for a given type will always
return the same `RecordArray`.
Example
```javascript
var localPosts = store.all('post');
```
@method all
@param {String} modelName
@return {DS.RecordArray}
*/
all: function (modelName) {
var typeClass = this.modelFor(modelName);
var typeMap = this.typeMapFor(typeClass);
var findAllCache = typeMap.findAllCache;
if (findAllCache) {
this.recordArrayManager.updateFilter(findAllCache, typeClass);
return findAllCache;
}
var array = this.recordArrayManager.createRecordArray(typeClass);
typeMap.findAllCache = array;
return array;
},
/**
This method unloads all records in the store.
Optionally you can pass a type which unload all records for a given type.
```javascript
store.unloadAll();
store.unloadAll('post');
```
@method unloadAll
@param {String=} modelName
*/
unloadAll: function (modelName) {
if (arguments.length === 0) {
var typeMaps = this.typeMaps;
var keys = Ember.keys(typeMaps);
var types = ember$data$lib$system$store$$map(keys, byType);
ember$data$lib$system$store$$forEach(types, this.unloadAll, this);
} else {
var typeClass = this.modelFor(modelName);
var typeMap = this.typeMapFor(typeClass);
var records = typeMap.records.slice();
var record;
for (var i = 0; i < records.length; i++) {
record = records[i];
record.unloadRecord();
record.destroy(); // maybe within unloadRecord
}
typeMap.findAllCache = null;
typeMap.metadata = Ember.create(null);
}
function byType(entry) {
return typeMaps[entry]["type"].modelName;
}
},
/**
Takes a type and filter function, and returns a live RecordArray that
remains up to date as new records are loaded into the store or created
locally.
The filter function takes a materialized record, and returns true
if the record should be included in the filter and false if it should
not.
Example
```javascript
store.filter('post', function(post) {
return post.get('unread');
});
```
The filter function is called once on all records for the type when
it is created, and then once on each newly loaded or created record.
If any of a record's properties change, or if it changes state, the
filter function will be invoked again to determine whether it should
still be in the array.
Optionally you can pass a query, which is the equivalent of calling
[find](#method_find) with that same query, to fetch additional records
from the server. The results returned by the server could then appear
in the filter if they match the filter function.
The query itself is not used to filter records, it's only sent to your
server for you to be able to do server-side filtering. The filter
function will be applied on the returned results regardless.
Example
```javascript
store.filter('post', { unread: true }, function(post) {
return post.get('unread');
}).then(function(unreadPosts) {
unreadPosts.get('length'); // 5
var unreadPost = unreadPosts.objectAt(0);
unreadPost.set('unread', false);
unreadPosts.get('length'); // 4
});
```
@method filter
@param {String} modelName
@param {Object} query optional query
@param {Function} filter
@return {DS.PromiseArray}
*/
filter: function (modelName, query, filter) {
var promise;
var length = arguments.length;
var array;
var hasQuery = length === 3;
// allow an optional server query
if (hasQuery) {
promise = this.findQuery(modelName, query);
} else if (arguments.length === 2) {
filter = query;
}
modelName = this.modelFor(modelName);
if (hasQuery) {
array = this.recordArrayManager.createFilteredRecordArray(modelName, filter, query);
} else {
array = this.recordArrayManager.createFilteredRecordArray(modelName, filter);
}
promise = promise || ember$data$lib$system$store$$Promise.cast(array);
return ember$data$lib$system$promise$proxies$$promiseArray(promise.then(function () {
return array;
}, null, "DS: Store#filter of " + modelName));
},
/**
This method returns if a certain record is already loaded
in the store. Use this function to know beforehand if a find()
will result in a request or that it will be a cache hit.
Example
```javascript
store.recordIsLoaded('post', 1); // false
store.find('post', 1).then(function() {
store.recordIsLoaded('post', 1); // true
});
```
@method recordIsLoaded
@param {String} modelName
@param {string} id
@return {boolean}
*/
recordIsLoaded: function (modelName, id) {
return this.hasRecordForId(modelName, id);
},
/**
This method returns the metadata for a specific type.
@method metadataFor
@param {String} modelName
@return {object}
*/
metadataFor: function (modelName) {
var typeClass = this.modelFor(modelName);
return this.typeMapFor(typeClass).metadata;
},
/**
This method sets the metadata for a specific type.
@method setMetadataFor
@param {String} modelName
@param {Object} metadata metadata to set
@return {object}
*/
setMetadataFor: function (modelName, metadata) {
var typeClass = this.modelFor(modelName);
Ember.merge(this.typeMapFor(typeClass).metadata, metadata);
},
// ............
// . UPDATING .
// ............
/**
If the adapter updates attributes the record will notify
the store to update its membership in any filters.
To avoid thrashing, this method is invoked only once per
run loop per record.
@method dataWasUpdated
@private
@param {Class} type
@param {InternalModel} internalModel
*/
dataWasUpdated: function (type, internalModel) {
this.recordArrayManager.recordDidChange(internalModel);
},
// ..............
// . PERSISTING .
// ..............
/**
This method is called by `record.save`, and gets passed a
resolver for the promise that `record.save` returns.
It schedules saving to happen at the end of the run loop.
@method scheduleSave
@private
@param {InternalModel} internalModel
@param {Resolver} resolver
*/
scheduleSave: function (internalModel, resolver) {
var snapshot = internalModel.createSnapshot();
internalModel.flushChangedAttributes();
internalModel.adapterWillCommit();
this._pendingSave.push([snapshot, resolver]);
ember$data$lib$system$store$$once(this, "flushPendingSave");
},
/**
This method is called at the end of the run loop, and
flushes any records passed into `scheduleSave`
@method flushPendingSave
@private
*/
flushPendingSave: function () {
var pending = this._pendingSave.slice();
this._pendingSave = [];
ember$data$lib$system$store$$forEach(pending, function (tuple) {
var snapshot = tuple[0];
var resolver = tuple[1];
var record = snapshot._internalModel;
var adapter = this.adapterFor(record.type.modelName);
var operation;
if (ember$data$lib$system$store$$get(record, "currentState.stateName") === "root.deleted.saved") {
return resolver.resolve();
} else if (record.isNew()) {
operation = "createRecord";
} else if (record.isDeleted()) {
operation = "deleteRecord";
} else {
operation = "updateRecord";
}
resolver.resolve(ember$data$lib$system$store$$_commit(adapter, this, operation, snapshot));
}, this);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is resolved.
If the data provides a server-generated ID, it will
update the record and the store's indexes.
@method didSaveRecord
@private
@param {InternalModel} internalModel the in-flight internal model
@param {Object} data optional data (see above)
*/
didSaveRecord: function (internalModel, data) {
if (data) {
// normalize relationship IDs into records
this._backburner.schedule("normalizeRelationships", this, "_setupRelationships", internalModel, internalModel.type, data);
this.updateId(internalModel, data);
}
//We first make sure the primary data has been updated
//TODO try to move notification to the user to the end of the runloop
internalModel.adapterDidCommit(data);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is rejected with a `DS.InvalidError`.
@method recordWasInvalid
@private
@param {InternalModel} internalModel
@param {Object} errors
*/
recordWasInvalid: function (internalModel, errors) {
internalModel.adapterDidInvalidate(errors);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is rejected (with anything other than a `DS.InvalidError`).
@method recordWasError
@private
@param {InternalModel} internalModel
*/
recordWasError: function (internalModel) {
internalModel.adapterDidError();
},
/**
When an adapter's `createRecord`, `updateRecord` or `deleteRecord`
resolves with data, this method extracts the ID from the supplied
data.
@method updateId
@private
@param {InternalModel} internalModel
@param {Object} data
*/
updateId: function (internalModel, data) {
var oldId = internalModel.id;
var id = ember$data$lib$system$coerce$id$$default(data.id);
this.typeMapFor(internalModel.type).idToRecord[id] = internalModel;
internalModel.setId(id);
},
/**
Returns a map of IDs to client IDs for a given type.
@method typeMapFor
@private
@param {DS.Model} typeClass
@return {Object} typeMap
*/
typeMapFor: function (typeClass) {
var typeMaps = ember$data$lib$system$store$$get(this, "typeMaps");
var guid = Ember.guidFor(typeClass);
var typeMap = typeMaps[guid];
if (typeMap) {
return typeMap;
}
typeMap = {
idToRecord: Ember.create(null),
records: [],
metadata: Ember.create(null),
type: typeClass
};
typeMaps[guid] = typeMap;
return typeMap;
},
// ................
// . LOADING DATA .
// ................
/**
This internal method is used by `push`.
@method _load
@private
@param {(String|DS.Model)} type
@param {Object} data
*/
_load: function (type, data) {
var id = ember$data$lib$system$coerce$id$$default(data.id);
var internalModel = this._internalModelForId(type, id);
internalModel.setupData(data);
this.recordArrayManager.recordDidChange(internalModel);
return internalModel;
},
/*
In case someone defined a relationship to a mixin, for example:
```
var Comment = DS.Model.extend({
owner: belongsTo('commentable'. { polymorphic: true})
});
var Commentable = Ember.Mixin.create({
comments: hasMany('comment')
});
```
we want to look up a Commentable class which has all the necessary
relationship metadata. Thus, we look up the mixin and create a mock
DS.Model, so we can access the relationship CPs of the mixin (`comments`)
in this case
*/
_modelForMixin: function (modelName) {
var normalizedModelName = ember$data$lib$system$normalize$model$name$$default(modelName);
var registry = this.container._registry ? this.container._registry : this.container;
var mixin = registry.resolve("mixin:" + normalizedModelName);
if (mixin) {
//Cache the class as a model
registry.register("model:" + normalizedModelName, DS.Model.extend(mixin));
}
var factory = this.modelFactoryFor(normalizedModelName);
if (factory) {
factory.__isMixin = true;
factory.__mixin = mixin;
}
return factory;
},
/**
Returns a model class for a particular key. Used by
methods that take a type key (like `find`, `createRecord`,
etc.)
@method modelFor
@param {String} modelName
@return {DS.Model}
*/
modelFor: function (modelName) {
var factory = this.modelFactoryFor(modelName);
if (!factory) {
//Support looking up mixins as base types for polymorphic relationships
factory = this._modelForMixin(modelName);
}
if (!factory) {
throw new Ember.Error("No model was found for '" + modelName + "'");
}
factory.modelName = factory.modelName || ember$data$lib$system$normalize$model$name$$default(modelName);
// deprecate typeKey
if (!("typeKey" in factory)) {
Ember.defineProperty(factory, "typeKey", {
enumerable: true,
configurable: false,
get: function () {
var typeKey = this.modelName;
if (typeKey) {
typeKey = Ember.String.camelize(this.modelName);
}
return typeKey;
},
set: function () {
}
});
}
return factory;
},
modelFactoryFor: function (modelName) {
var normalizedKey = ember$data$lib$system$normalize$model$name$$default(modelName);
return this.container.lookupFactory("model:" + normalizedKey);
},
/**
Push some data for a given type into the store.
This method expects normalized data:
* The ID is a key named `id` (an ID is mandatory)
* The names of attributes are the ones you used in
your model's `DS.attr`s.
* Your relationships must be:
* represented as IDs or Arrays of IDs
* represented as model instances
* represented as URLs, under the `links` key
For this model:
```app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr(),
lastName: DS.attr(),
children: DS.hasMany('person')
});
```
To represent the children as IDs:
```js
{
id: 1,
firstName: "Tom",
lastName: "Dale",
children: [1, 2, 3]
}
```
To represent the children relationship as a URL:
```js
{
id: 1,
firstName: "Tom",
lastName: "Dale",
links: {
children: "/people/1/children"
}
}
```
If you're streaming data or implementing an adapter, make sure
that you have converted the incoming data into this form. The
store's [normalize](#method_normalize) method is a convenience
helper for converting a json payload into the form Ember Data
expects.
```js
store.push('person', store.normalize('person', data));
```
This method can be used both to push in brand new
records, as well as to update existing records.
@method push
@param {String} modelName
@param {Object} data
@return {DS.Model} the record that was created or
updated.
*/
push: function (modelName, data) {
var internalModel = this._pushInternalModel(modelName, data);
return internalModel.getRecord();
},
_pushInternalModel: function (modelName, data) {
var type = this.modelFor(modelName);
var filter = Ember.EnumerableUtils.filter;
// If Ember.ENV.DS_WARN_ON_UNKNOWN_KEYS is set to true and the payload
// contains unknown keys, log a warning.
if (Ember.ENV.DS_WARN_ON_UNKNOWN_KEYS) {
}
// Actually load the record into the store.
var internalModel = this._load(modelName, data);
var store = this;
this._backburner.join(function () {
store._backburner.schedule("normalizeRelationships", store, "_setupRelationships", internalModel, type, data);
});
return internalModel;
},
_setupRelationships: function (record, type, data) {
// If the payload contains relationships that are specified as
// IDs, normalizeRelationships will convert them into DS.Model instances
// (possibly unloaded) before we push the payload into the
// store.
data = ember$data$lib$system$store$$normalizeRelationships(this, type, data);
// Now that the pushed record as well as any related records
// are in the store, create the data structures used to track
// relationships.
ember$data$lib$system$store$$setupRelationships(this, record, data);
},
/**
Push some raw data into the store.
This method can be used both to push in brand new
records, as well as to update existing records. You
can push in more than one type of object at once.
All objects should be in the format expected by the
serializer.
```app/serializers/application.js
import DS from 'ember-data';
export default DS.ActiveModelSerializer;
```
```js
var pushData = {
posts: [
{id: 1, post_title: "Great post", comment_ids: [2]}
],
comments: [
{id: 2, comment_body: "Insightful comment"}
]
}
store.pushPayload(pushData);
```
By default, the data will be deserialized using a default
serializer (the application serializer if it exists).
Alternatively, `pushPayload` will accept a model type which
will determine which serializer will process the payload.
However, the serializer itself (processing this data via
`normalizePayload`) will not know which model it is
deserializing.
```app/serializers/application.js
import DS from 'ember-data';
export default DS.ActiveModelSerializer;
```
```app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer;
```
```js
store.pushPayload('comment', pushData); // Will use the application serializer
store.pushPayload('post', pushData); // Will use the post serializer
```
@method pushPayload
@param {String} modelName Optionally, a model type used to determine which serializer will be used
@param {Object} inputPayload
*/
pushPayload: function (modelName, inputPayload) {
var serializer;
var payload;
if (!inputPayload) {
payload = modelName;
serializer = ember$data$lib$system$store$$defaultSerializer(this.container);
} else {
payload = inputPayload;
serializer = this.serializerFor(modelName);
}
var store = this;
this._adapterRun(function () {
serializer.pushPayload(store, payload);
});
},
/**
`normalize` converts a json payload into the normalized form that
[push](#method_push) expects.
Example
```js
socket.on('message', function(message) {
var modelName = message.model;
var data = message.data;
store.push(modelName, store.normalize(modelName, data));
});
```
@method normalize
@param {String} modelName The name of the model type for this payload
@param {Object} payload
@return {Object} The normalized payload
*/
normalize: function (modelName, payload) {
var serializer = this.serializerFor(modelName);
var model = this.modelFor(modelName);
return serializer.normalize(model, payload);
},
/**
@method update
@param {String} modelName
@param {Object} data
@return {DS.Model} the record that was updated.
@deprecated Use [push](#method_push) instead
*/
update: function (modelName, data) {
return this.push(modelName, data);
},
/**
If you have an Array of normalized data to push,
you can call `pushMany` with the Array, and it will
call `push` repeatedly for you.
@method pushMany
@param {String} modelName
@param {Array} datas
@return {Array}
*/
pushMany: function (modelName, datas) {
var length = datas.length;
var result = new Array(length);
for (var i = 0; i < length; i++) {
result[i] = this.push(modelName, datas[i]);
}
return result;
},
/**
@method metaForType
@param {String} modelName
@param {Object} metadata
@deprecated Use [setMetadataFor](#method_setMetadataFor) instead
*/
metaForType: function (modelName, metadata) {
this.setMetadataFor(modelName, metadata);
},
/**
Build a brand new record for a given type, ID, and
initial data.
@method buildRecord
@private
@param {DS.Model} type
@param {String} id
@param {Object} data
@return {InternalModel} internal model
*/
buildInternalModel: function (type, id, data) {
var typeMap = this.typeMapFor(type);
var idToRecord = typeMap.idToRecord;
// lookupFactory should really return an object that creates
// instances with the injections applied
var internalModel = new ember$data$lib$system$model$internal$model$$default(type, id, this, this.container, data);
// if we're creating an item, this process will be done
// later, once the object has been persisted.
if (id) {
idToRecord[id] = internalModel;
}
typeMap.records.push(internalModel);
return internalModel;
},
//Called by the state machine to notify the store that the record is ready to be interacted with
recordWasLoaded: function (record) {
this.recordArrayManager.recordWasLoaded(record);
},
// ...............
// . DESTRUCTION .
// ...............
/**
@method dematerializeRecord
@private
@param {DS.Model} record
@deprecated Use [unloadRecord](#method_unloadRecord) instead
*/
dematerializeRecord: function (record) {
this._dematerializeRecord(record);
},
/**
When a record is destroyed, this un-indexes it and
removes it from any record arrays so it can be GCed.
@method _dematerializeRecord
@private
@param {InternalModel} internalModel
*/
_dematerializeRecord: function (internalModel) {
var type = internalModel.type;
var typeMap = this.typeMapFor(type);
var id = internalModel.id;
internalModel.updateRecordArrays();
if (id) {
delete typeMap.idToRecord[id];
}
var loc = ember$data$lib$system$store$$indexOf(typeMap.records, internalModel);
typeMap.records.splice(loc, 1);
},
// ......................
// . PER-TYPE ADAPTERS
// ......................
/**
Returns an instance of the adapter for a given type. For
example, `adapterFor('person')` will return an instance of
`App.PersonAdapter`.
If no `App.PersonAdapter` is found, this method will look
for an `App.ApplicationAdapter` (the default adapter for
your entire application).
If no `App.ApplicationAdapter` is found, it will return
the value of the `defaultAdapter`.
@method adapterFor
@private
@param {String} modelName
@return DS.Adapter
*/
adapterFor: function (modelOrClass) {
var modelName;
if (typeof modelOrClass !== "string") {
modelName = modelOrClass.modelName;
} else {
modelName = modelOrClass;
}
return this.lookupAdapter(modelName);
},
_adapterRun: function (fn) {
return this._backburner.run(fn);
},
// ..............................
// . RECORD CHANGE NOTIFICATION .
// ..............................
/**
Returns an instance of the serializer for a given type. For
example, `serializerFor('person')` will return an instance of
`App.PersonSerializer`.
If no `App.PersonSerializer` is found, this method will look
for an `App.ApplicationSerializer` (the default serializer for
your entire application).
if no `App.ApplicationSerializer` is found, it will attempt
to get the `defaultSerializer` from the `PersonAdapter`
(`adapterFor('person')`).
If a serializer cannot be found on the adapter, it will fall back
to an instance of `DS.JSONSerializer`.
@method serializerFor
@private
@param {String} modelName the record to serialize
@return {DS.Serializer}
*/
serializerFor: function (modelOrClass) {
var modelName;
if (typeof modelOrClass !== "string") {
modelName = modelOrClass.modelName;
} else {
modelName = modelOrClass;
}
var fallbacks = ["application", this.adapterFor(modelName).get("defaultSerializer"), "-default"];
var serializer = this.lookupSerializer(modelName, fallbacks);
return serializer;
},
/**
Retrieve a particular instance from the
container cache. If not found, creates it and
placing it in the cache.
Enabled a store to manage local instances of
adapters and serializers.
@method retrieveManagedInstance
@private
@param {String} modelName the object modelName
@param {String} name the object name
@param {Array} fallbacks the fallback objects to lookup if the lookup for modelName or 'application' fails
@return {Ember.Object}
*/
retrieveManagedInstance: function (type, modelName, fallbacks) {
var normalizedModelName = ember$data$lib$system$normalize$model$name$$default(modelName);
var instance = this._instanceCache.get(type, normalizedModelName, fallbacks);
ember$data$lib$system$store$$set(instance, "store", this);
return instance;
},
lookupAdapter: function (name) {
return this.retrieveManagedInstance("adapter", name, this.get("_adapterFallbacks"));
},
_adapterFallbacks: Ember.computed("adapter", function () {
var adapter = this.get("adapter");
return ["application", adapter, "-rest"];
}),
lookupSerializer: function (name, fallbacks) {
return this.retrieveManagedInstance("serializer", name, fallbacks);
},
willDestroy: function () {
this.recordArrayManager.destroy();
this.unloadAll();
for (var cacheKey in this._containerCache) {
this._containerCache[cacheKey].destroy();
delete this._containerCache[cacheKey];
}
delete this._containerCache;
}
});
function ember$data$lib$system$store$$normalizeRelationships(store, type, data, record) {
type.eachRelationship(function (key, relationship) {
var kind = relationship.kind;
var value = data[key];
if (kind === "belongsTo") {
ember$data$lib$system$store$$deserializeRecordId(store, data, key, relationship, value);
} else if (kind === "hasMany") {
ember$data$lib$system$store$$deserializeRecordIds(store, data, key, relationship, value);
}
});
return data;
}
function ember$data$lib$system$store$$deserializeRecordId(store, data, key, relationship, id) {
if (ember$data$lib$system$store$$isNone(id)) {
return;
}
//If record objects were given to push directly, uncommon, not sure whether we should actually support
if (id instanceof ember$data$lib$system$model$$default) {
data[key] = id._internalModel;
return;
}
var type;
if (typeof id === "number" || typeof id === "string") {
type = ember$data$lib$system$store$$typeFor(relationship, key, data);
data[key] = store._internalModelForId(type, id);
} else if (typeof id === "object") {
// hasMany polymorphic
data[key] = store._internalModelForId(id.type, id.id);
}
}
function ember$data$lib$system$store$$typeFor(relationship, key, data) {
if (relationship.options.polymorphic) {
return data[key + "Type"];
} else {
return relationship.type;
}
}
function ember$data$lib$system$store$$deserializeRecordIds(store, data, key, relationship, ids) {
if (ember$data$lib$system$store$$isNone(ids)) {
return;
}
for (var i = 0, l = ids.length; i < l; i++) {
ember$data$lib$system$store$$deserializeRecordId(store, ids, i, relationship, ids[i]);
}
}
// Delegation to the adapter and promise management
function ember$data$lib$system$store$$defaultSerializer(container) {
return container.lookup("serializer:application") || container.lookup("serializer:-default");
}
function ember$data$lib$system$store$$_commit(adapter, store, operation, snapshot) {
var record = snapshot._internalModel;
var modelName = snapshot.modelName;
var type = store.modelFor(modelName);
var promise = adapter[operation](store, type, snapshot);
var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, modelName);
var label = "DS: Extract and notify about " + operation + " completion of " + record;
promise = ember$data$lib$system$store$$Promise.cast(promise, label);
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, store));
promise = ember$data$lib$system$store$common$$_guard(promise, ember$data$lib$system$store$common$$_bind(ember$data$lib$system$store$common$$_objectIsAlive, record));
return promise.then(function (adapterPayload) {
var payload;
store._adapterRun(function () {
if (adapterPayload) {
payload = serializer.extract(store, type, adapterPayload, snapshot.id, operation);
}
store.didSaveRecord(record, payload);
});
return record;
}, function (reason) {
if (reason instanceof ember$data$lib$system$model$errors$invalid$$default) {
var errors = serializer.extractErrors(store, type, reason.errors, snapshot.id);
store.recordWasInvalid(record, errors);
reason = new ember$data$lib$system$model$errors$invalid$$default(errors);
} else {
store.recordWasError(record, reason);
}
throw reason;
}, label);
}
function ember$data$lib$system$store$$setupRelationships(store, record, data) {
var typeClass = record.type;
typeClass.eachRelationship(function (key, descriptor) {
var kind = descriptor.kind;
var value = data[key];
var relationship;
if (data.links && data.links[key]) {
relationship = record._relationships.get(key);
relationship.updateLink(data.links[key]);
}
if (value !== undefined) {
if (kind === "belongsTo") {
relationship = record._relationships.get(key);
relationship.setCanonicalRecord(value);
} else if (kind === "hasMany") {
relationship = record._relationships.get(key);
relationship.updateRecordsFromAdapter(value);
}
}
});
}
var ember$data$lib$system$store$$default = ember$data$lib$system$store$$Store;
var ember$data$lib$initializers$store$$default = ember$data$lib$initializers$store$$initializeStore;
/**
Configures a registry for use with an Ember-Data
store. Accepts an optional namespace argument.
@method initializeStore
@param {Ember.Registry} registry
@param {Object} [application] an application namespace
*/
function ember$data$lib$initializers$store$$initializeStore(registry, application) {
registry.optionsForType("serializer", { singleton: false });
registry.optionsForType("adapter", { singleton: false });
registry.register("store:application", application && application.Store || ember$data$lib$system$store$$default);
// allow older names to be looked up
var proxy = new ember$data$lib$system$container$proxy$$default(registry);
proxy.registerDeprecations([{ deprecated: "serializer:_default", valid: "serializer:-default" }, { deprecated: "serializer:_rest", valid: "serializer:-rest" }, { deprecated: "adapter:_rest", valid: "adapter:-rest" }, { deprecated: "store:main", valid: "store:application" }]);
// new go forward paths
registry.register("serializer:-default", ember$data$lib$serializers$json$serializer$$default);
registry.register("serializer:-rest", ember$data$lib$serializers$rest$serializer$$default);
registry.register("adapter:-rest", ember$data$lib$adapters$rest$adapter$$default);
}
var ember$data$lib$transforms$base$$default = Ember.Object.extend({
/**
When given a deserialized value from a record attribute this
method must return the serialized value.
Example
```javascript
serialize: function(deserialized) {
return Ember.isEmpty(deserialized) ? null : Number(deserialized);
}
```
@method serialize
@param deserialized The deserialized value
@return The serialized value
*/
serialize: null,
/**
When given a serialize value from a JSON object this method must
return the deserialized value for the record attribute.
Example
```javascript
deserialize: function(serialized) {
return empty(serialized) ? null : Number(serialized);
}
```
@method deserialize
@param serialized The serialized value
@return The deserialized value
*/
deserialize: null
});
var ember$data$lib$transforms$number$$empty = Ember.isEmpty;
function ember$data$lib$transforms$number$$isNumber(value) {
return value === value && value !== Infinity && value !== -Infinity;
}
var ember$data$lib$transforms$number$$default = ember$data$lib$transforms$base$$default.extend({
deserialize: function (serialized) {
var transformed;
if (ember$data$lib$transforms$number$$empty(serialized)) {
return null;
} else {
transformed = Number(serialized);
return ember$data$lib$transforms$number$$isNumber(transformed) ? transformed : null;
}
},
serialize: function (deserialized) {
var transformed;
if (ember$data$lib$transforms$number$$empty(deserialized)) {
return null;
} else {
transformed = Number(deserialized);
return ember$data$lib$transforms$number$$isNumber(transformed) ? transformed : null;
}
}
});
// Date.prototype.toISOString shim
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
var ember$data$lib$transforms$date$$toISOString = Date.prototype.toISOString || function () {
function pad(number) {
if (number < 10) {
return '0' + number;
}
return number;
}
return this.getUTCFullYear() + '-' + pad(this.getUTCMonth() + 1) + '-' + pad(this.getUTCDate()) + 'T' + pad(this.getUTCHours()) + ':' + pad(this.getUTCMinutes()) + ':' + pad(this.getUTCSeconds()) + '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z';
};
if (Ember.SHIM_ES5) {
if (!Date.prototype.toISOString) {
Date.prototype.toISOString = ember$data$lib$transforms$date$$toISOString;
}
}
var ember$data$lib$transforms$date$$default = ember$data$lib$transforms$base$$default.extend({
deserialize: function (serialized) {
var type = typeof serialized;
if (type === 'string') {
return new Date(Ember.Date.parse(serialized));
} else if (type === 'number') {
return new Date(serialized);
} else if (serialized === null || serialized === undefined) {
// if the value is null return null
// if the value is not present in the data return undefined
return serialized;
} else {
return null;
}
},
serialize: function (date) {
if (date instanceof Date) {
return ember$data$lib$transforms$date$$toISOString.call(date);
} else {
return null;
}
}
});
var ember$data$lib$transforms$string$$none = Ember.isNone;
var ember$data$lib$transforms$string$$default = ember$data$lib$transforms$base$$default.extend({
deserialize: function (serialized) {
return ember$data$lib$transforms$string$$none(serialized) ? null : String(serialized);
},
serialize: function (deserialized) {
return ember$data$lib$transforms$string$$none(deserialized) ? null : String(deserialized);
}
});
var ember$data$lib$transforms$boolean$$default = ember$data$lib$transforms$base$$default.extend({
deserialize: function (serialized) {
var type = typeof serialized;
if (type === "boolean") {
return serialized;
} else if (type === "string") {
return serialized.match(/^true$|^t$|^1$/i) !== null;
} else if (type === "number") {
return serialized === 1;
} else {
return false;
}
},
serialize: function (deserialized) {
return Boolean(deserialized);
}
});
var ember$data$lib$initializers$transforms$$default = ember$data$lib$initializers$transforms$$initializeTransforms;
/**
Configures a registry for use with Ember-Data
transforms.
@method initializeTransforms
@param {Ember.Registry} registry
*/
function ember$data$lib$initializers$transforms$$initializeTransforms(registry) {
registry.register('transform:boolean', ember$data$lib$transforms$boolean$$default);
registry.register('transform:date', ember$data$lib$transforms$date$$default);
registry.register('transform:number', ember$data$lib$transforms$number$$default);
registry.register('transform:string', ember$data$lib$transforms$string$$default);
}
var ember$data$lib$initializers$store$injections$$default = ember$data$lib$initializers$store$injections$$initializeStoreInjections;
/**
Configures a registry with injections on Ember applications
for the Ember-Data store. Accepts an optional namespace argument.
@method initializeStoreInjections
@param {Ember.Registry} registry
*/
function ember$data$lib$initializers$store$injections$$initializeStoreInjections(registry) {
registry.injection('controller', 'store', 'store:application');
registry.injection('route', 'store', 'store:application');
registry.injection('data-adapter', 'store', 'store:application');
}
var ember$data$lib$system$debug$debug$adapter$$get = Ember.get;
var ember$data$lib$system$debug$debug$adapter$$capitalize = Ember.String.capitalize;
var ember$data$lib$system$debug$debug$adapter$$underscore = Ember.String.underscore;
var ember$data$lib$system$debug$debug$adapter$$_Ember = Ember;
var ember$data$lib$system$debug$debug$adapter$$assert = ember$data$lib$system$debug$debug$adapter$$_Ember.assert;
var ember$data$lib$system$debug$debug$adapter$$default = Ember.DataAdapter.extend({
getFilters: function () {
return [{ name: 'isNew', desc: 'New' }, { name: 'isModified', desc: 'Modified' }, { name: 'isClean', desc: 'Clean' }];
},
detect: function (typeClass) {
return typeClass !== ember$data$lib$system$model$$default && ember$data$lib$system$model$$default.detect(typeClass);
},
columnsForType: function (typeClass) {
var columns = [{
name: 'id',
desc: 'Id'
}];
var count = 0;
var self = this;
ember$data$lib$system$debug$debug$adapter$$get(typeClass, 'attributes').forEach(function (meta, name) {
if (count++ > self.attributeLimit) {
return false;
}
var desc = ember$data$lib$system$debug$debug$adapter$$capitalize(ember$data$lib$system$debug$debug$adapter$$underscore(name).replace('_', ' '));
columns.push({ name: name, desc: desc });
});
return columns;
},
getRecords: function (modelClass, modelName) {
if (arguments.length < 2) {
// Legacy Ember.js < 1.13 support
var containerKey = modelClass._debugContainerKey;
if (containerKey) {
var match = containerKey.match(/model:(.*)/);
if (match) {
modelName = match[1];
}
}
}
ember$data$lib$system$debug$debug$adapter$$assert('Cannot find model name. Please upgrade to Ember.js >= 1.13 for Ember Inspector support', !!modelName);
return this.get('store').all(modelName);
},
getRecordColumnValues: function (record) {
var self = this;
var count = 0;
var columnValues = { id: ember$data$lib$system$debug$debug$adapter$$get(record, 'id') };
record.eachAttribute(function (key) {
if (count++ > self.attributeLimit) {
return false;
}
var value = ember$data$lib$system$debug$debug$adapter$$get(record, key);
columnValues[key] = value;
});
return columnValues;
},
getRecordKeywords: function (record) {
var keywords = [];
var keys = Ember.A(['id']);
record.eachAttribute(function (key) {
keys.push(key);
});
keys.forEach(function (key) {
keywords.push(ember$data$lib$system$debug$debug$adapter$$get(record, key));
});
return keywords;
},
getRecordFilterValues: function (record) {
return {
isNew: record.get('isNew'),
isModified: record.get('isDirty') && !record.get('isNew'),
isClean: !record.get('isDirty')
};
},
getRecordColor: function (record) {
var color = 'black';
if (record.get('isNew')) {
color = 'green';
} else if (record.get('isDirty')) {
color = 'blue';
}
return color;
},
observeRecord: function (record, recordUpdated) {
var releaseMethods = Ember.A();
var self = this;
var keysToObserve = Ember.A(['id', 'isNew', 'isDirty']);
record.eachAttribute(function (key) {
keysToObserve.push(key);
});
keysToObserve.forEach(function (key) {
var handler = function () {
recordUpdated(self.wrapRecord(record));
};
Ember.addObserver(record, key, handler);
releaseMethods.push(function () {
Ember.removeObserver(record, key, handler);
});
});
var release = function () {
releaseMethods.forEach(function (fn) {
fn();
});
};
return release;
}
});
var ember$data$lib$initializers$data$adapter$$default = ember$data$lib$initializers$data$adapter$$initializeDebugAdapter;
/**
Configures a registry with injections on Ember applications
for the Ember-Data store. Accepts an optional namespace argument.
@method initializeStoreInjections
@param {Ember.Registry} registry
*/
function ember$data$lib$initializers$data$adapter$$initializeDebugAdapter(registry) {
registry.register("data-adapter:main", ember$data$lib$system$debug$debug$adapter$$default);
}
var ember$data$lib$instance$initializers$initialize$store$service$$default = ember$data$lib$instance$initializers$initialize$store$service$$initializeStoreService;
/**
Configures a registry for use with an Ember-Data
store.
@method initializeStore
@param {Ember.ApplicationInstance} applicationOrRegistry
*/
function ember$data$lib$instance$initializers$initialize$store$service$$initializeStoreService(applicationOrRegistry) {
var registry, container;
if (applicationOrRegistry.registry && applicationOrRegistry.container) {
// initializeStoreService was registered with an
// instanceInitializer. The first argument is the application
// instance.
registry = applicationOrRegistry.registry;
container = applicationOrRegistry.container;
} else {
// initializeStoreService was called by an initializer instead of
// an instanceInitializer. The first argument is a registy. This
// case allows ED to support Ember pre 1.12
registry = applicationOrRegistry;
if (registry.container) {
// Support Ember 1.10 - 1.11
container = registry.container();
} else {
// Support Ember 1.9
container = registry;
}
}
// Eagerly generate the store so defaultStore is populated.
var store = container.lookup('store:application');
registry.register('service:store', store, { instantiate: false });
}
var ember$data$lib$setup$container$$default = ember$data$lib$setup$container$$setupContainer;
function ember$data$lib$setup$container$$setupContainer(registry, application) {
// application is not a required argument. This ensures
// testing setups can setup a container without booting an
// entire ember application.
ember$data$lib$setup$container$$initializeInjects(registry, application);
ember$data$lib$instance$initializers$initialize$store$service$$default(registry);
}
function ember$data$lib$setup$container$$initializeInjects(registry, application) {
ember$data$lib$initializers$data$adapter$$default(registry, application);
ember$data$lib$initializers$transforms$$default(registry, application);
ember$data$lib$initializers$store$injections$$default(registry, application);
activemodel$adapter$lib$setup$container$$default(registry, application);
ember$data$lib$initializers$store$$default(registry, application);
}
var ember$data$lib$ember$initializer$$K = Ember.K;
/**
@module ember-data
*/
/*
This code initializes Ember-Data onto an Ember application.
If an Ember.js developer defines a subclass of DS.Store on their application,
as `App.ApplicationStore` (or via a module system that resolves to `store:application`)
this code will automatically instantiate it and make it available on the
router.
Additionally, after an application's controllers have been injected, they will
each have the store made available to them.
For example, imagine an Ember.js application with the following classes:
App.ApplicationStore = DS.Store.extend({
adapter: 'custom'
});
App.PostsController = Ember.ArrayController.extend({
// ...
});
When the application is initialized, `App.ApplicationStore` will automatically be
instantiated, and the instance of `App.PostsController` will have its `store`
property set to that instance.
Note that this code will only be run if the `ember-application` package is
loaded. If Ember Data is being used in an environment other than a
typical application (e.g., node.js where only `ember-runtime` is available),
this code will be ignored.
*/
Ember.onLoad('Ember.Application', function (Application) {
Application.initializer({
name: 'ember-data',
initialize: ember$data$lib$setup$container$$initializeInjects
});
if (Application.instanceInitializer) {
Application.instanceInitializer({
name: 'ember-data',
initialize: ember$data$lib$instance$initializers$initialize$store$service$$default
});
} else {
Application.initializer({
name: 'ember-data-store-service',
after: 'ember-data',
initialize: ember$data$lib$instance$initializers$initialize$store$service$$default
});
}
// Deprecated initializers to satisfy old code that depended on them
Application.initializer({
name: 'store',
after: 'ember-data',
initialize: ember$data$lib$ember$initializer$$K
});
Application.initializer({
name: 'activeModelAdapter',
before: 'store',
initialize: ember$data$lib$ember$initializer$$K
});
Application.initializer({
name: 'transforms',
before: 'store',
initialize: ember$data$lib$ember$initializer$$K
});
Application.initializer({
name: 'data-adapter',
before: 'store',
initialize: ember$data$lib$ember$initializer$$K
});
Application.initializer({
name: 'injectStore',
before: 'store',
initialize: ember$data$lib$ember$initializer$$K
});
});
Ember.Date = Ember.Date || {};
var origParse = Date.parse;
var numericKeys = [1, 4, 5, 6, 7, 10, 11];
/**
@method parse
@param {Date} date
@return {Number} timestamp
*/
Ember.Date.parse = function (date) {
var timestamp, struct;
var minutesOffset = 0;
// ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string
// before falling back to any implementation-specific date parsing, so that’s what we do, even if native
// implementations could be faster
// 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm
if (struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date)) {
// avoid NaN timestamps caused by “undefined” values being passed to Date.UTC
for (var i = 0, k; k = numericKeys[i]; ++i) {
struct[k] = +struct[k] || 0;
}
// allow undefined days and months
struct[2] = (+struct[2] || 1) - 1;
struct[3] = +struct[3] || 1;
if (struct[8] !== 'Z' && struct[9] !== undefined) {
minutesOffset = struct[10] * 60 + struct[11];
if (struct[9] === '+') {
minutesOffset = 0 - minutesOffset;
}
}
timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]);
} else {
timestamp = origParse ? origParse(date) : NaN;
}
return timestamp;
};
if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) {
Date.parse = Ember.Date.parse;
}
ember$data$lib$system$model$$default.reopen({
/**
Provides info about the model for debugging purposes
by grouping the properties into more semantic groups.
Meant to be used by debugging tools such as the Chrome Ember Extension.
- Groups all attributes in "Attributes" group.
- Groups all belongsTo relationships in "Belongs To" group.
- Groups all hasMany relationships in "Has Many" group.
- Groups all flags in "Flags" group.
- Flags relationship CPs as expensive properties.
@method _debugInfo
@for DS.Model
@private
*/
_debugInfo: function () {
var attributes = ['id'];
var relationships = { belongsTo: [], hasMany: [] };
var expensiveProperties = [];
this.eachAttribute(function (name, meta) {
attributes.push(name);
}, this);
this.eachRelationship(function (name, relationship) {
relationships[relationship.kind].push(name);
expensiveProperties.push(name);
});
var groups = [{
name: 'Attributes',
properties: attributes,
expand: true
}, {
name: 'Belongs To',
properties: relationships.belongsTo,
expand: true
}, {
name: 'Has Many',
properties: relationships.hasMany,
expand: true
}, {
name: 'Flags',
properties: ['isLoaded', 'isDirty', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid']
}];
return {
propertyInfo: {
// include all other mixins / properties (not just the grouped ones)
includeOtherProperties: true,
groups: groups,
// don't pre-calculate unless cached
expensiveProperties: expensiveProperties
}
};
}
});
var ember$data$lib$system$debug$debug$info$$default = ember$data$lib$system$model$$default;
var ember$data$lib$system$debug$$default = ember$data$lib$system$debug$debug$adapter$$default;
var ember$data$lib$serializers$embedded$records$mixin$$forEach = Ember.EnumerableUtils.forEach;
var ember$data$lib$serializers$embedded$records$mixin$$camelize = Ember.String.camelize;
/**
## Using Embedded Records
`DS.EmbeddedRecordsMixin` supports serializing embedded records.
To set up embedded records, include the mixin when extending a serializer
then define and configure embedded (model) relationships.
Below is an example of a per-type serializer ('post' type).
```app/serializers/post.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
author: { embedded: 'always' },
comments: { serialize: 'ids' }
}
});
```
Note that this use of `{ embedded: 'always' }` is unrelated to
the `{ embedded: 'always' }` that is defined as an option on `DS.attr` as part of
defining a model while working with the ActiveModelSerializer. Nevertheless,
using `{ embedded: 'always' }` as an option to DS.attr is not a valid way to setup
embedded records.
The `attrs` option for a resource `{ embedded: 'always' }` is shorthand for:
```js
{
serialize: 'records',
deserialize: 'records'
}
```
### Configuring Attrs
A resource's `attrs` option may be set to use `ids`, `records` or false for the
`serialize` and `deserialize` settings.
The `attrs` property can be set on the ApplicationSerializer or a per-type
serializer.
In the case where embedded JSON is expected while extracting a payload (reading)
the setting is `deserialize: 'records'`, there is no need to use `ids` when
extracting as that is the default behavior without this mixin if you are using
the vanilla EmbeddedRecordsMixin. Likewise, to embed JSON in the payload while
serializing `serialize: 'records'` is the setting to use. There is an option of
not embedding JSON in the serialized payload by using `serialize: 'ids'`. If you
do not want the relationship sent at all, you can use `serialize: false`.
### EmbeddedRecordsMixin defaults
If you do not overwrite `attrs` for a specific relationship, the `EmbeddedRecordsMixin`
will behave in the following way:
BelongsTo: `{ serialize: 'id', deserialize: 'id' }`
HasMany: `{ serialize: false, deserialize: 'ids' }`
### Model Relationships
Embedded records must have a model defined to be extracted and serialized. Note that
when defining any relationships on your model such as `belongsTo` and `hasMany`, you
should not both specify `async:true` and also indicate through the serializer's
`attrs` attribute that the related model should be embedded for deserialization.
If a model is declared embedded for deserialization (`embedded: 'always'`,
`deserialize: 'record'` or `deserialize: 'records'`), then do not use `async:true`.
To successfully extract and serialize embedded records the model relationships
must be setup correcty See the
[defining relationships](/guides/models/defining-models/#toc_defining-relationships)
section of the **Defining Models** guide page.
Records without an `id` property are not considered embedded records, model
instances must have an `id` property to be used with Ember Data.
### Example JSON payloads, Models and Serializers
**When customizing a serializer it is important to grok what the customizations
are. Please read the docs for the methods this mixin provides, in case you need
to modify it to fit your specific needs.**
For example review the docs for each method of this mixin:
* [normalize](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_normalize)
* [serializeBelongsTo](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeBelongsTo)
* [serializeHasMany](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeHasMany)
@class EmbeddedRecordsMixin
@namespace DS
*/
var ember$data$lib$serializers$embedded$records$mixin$$EmbeddedRecordsMixin = Ember.Mixin.create({
/**
Normalize the record and recursively normalize/extract all the embedded records
while pushing them into the store as they are encountered
A payload with an attr configured for embedded records needs to be extracted:
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"comments": [{
"id": "1",
"body": "Rails is unagi"
}, {
"id": "2",
"body": "Omakase O_o"
}]
}
}
```
@method normalize
@param {DS.Model} typeClass
@param {Object} hash to be normalized
@param {String} prop the hash has been referenced by
@return {Object} the normalized hash
**/
normalize: function (typeClass, hash, prop) {
var normalizedHash = this._super(typeClass, hash, prop);
return ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedRecords(this, this.store, typeClass, normalizedHash);
},
keyForRelationship: function (key, typeClass, method) {
if (method === 'serialize' && this.hasSerializeRecordsOption(key) || method === 'deserialize' && this.hasDeserializeRecordsOption(key)) {
return this.keyForAttribute(key, method);
} else {
return this._super(key, typeClass, method) || key;
}
},
/**
Serialize `belongsTo` relationship when it is configured as an embedded object.
This example of an author model belongs to a post model:
```js
Post = DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string'),
author: DS.belongsTo('author')
});
Author = DS.Model.extend({
name: DS.attr('string'),
post: DS.belongsTo('post')
});
```
Use a custom (type) serializer for the post model to configure embedded author
```app/serializers/post.js
import DS from 'ember-data;
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
author: {embedded: 'always'}
}
})
```
A payload with an attribute configured for embedded records can serialize
the records together under the root attribute's payload:
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"author": {
"id": "2"
"name": "dhh"
}
}
}
```
@method serializeBelongsTo
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializeBelongsTo: function (snapshot, json, relationship) {
var attr = relationship.key;
if (this.noSerializeOptionSpecified(attr)) {
this._super(snapshot, json, relationship);
return;
}
var includeIds = this.hasSerializeIdsOption(attr);
var includeRecords = this.hasSerializeRecordsOption(attr);
var embeddedSnapshot = snapshot.belongsTo(attr);
var key;
if (includeIds) {
key = this.keyForRelationship(attr, relationship.kind, 'serialize');
if (!embeddedSnapshot) {
json[key] = null;
} else {
json[key] = embeddedSnapshot.id;
}
} else if (includeRecords) {
key = this.keyForAttribute(attr, 'serialize');
if (!embeddedSnapshot) {
json[key] = null;
} else {
json[key] = embeddedSnapshot.record.serialize({ includeId: true });
this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json[key]);
}
}
},
/**
Serialize `hasMany` relationship when it is configured as embedded objects.
This example of a post model has many comments:
```js
Post = DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string'),
comments: DS.hasMany('comment')
});
Comment = DS.Model.extend({
body: DS.attr('string'),
post: DS.belongsTo('post')
});
```
Use a custom (type) serializer for the post model to configure embedded comments
```app/serializers/post.js
import DS from 'ember-data;
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
comments: {embedded: 'always'}
}
})
```
A payload with an attribute configured for embedded records can serialize
the records together under the root attribute's payload:
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"body": "I want this for my ORM, I want that for my template language..."
"comments": [{
"id": "1",
"body": "Rails is unagi"
}, {
"id": "2",
"body": "Omakase O_o"
}]
}
}
```
The attrs options object can use more specific instruction for extracting and
serializing. When serializing, an option to embed `ids` or `records` can be set.
When extracting the only option is `records`.
So `{embedded: 'always'}` is shorthand for:
`{serialize: 'records', deserialize: 'records'}`
To embed the `ids` for a related object (using a hasMany relationship):
```app/serializers/post.js
import DS from 'ember-data;
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
comments: {serialize: 'ids', deserialize: 'records'}
}
})
```
```js
{
"post": {
"id": "1"
"title": "Rails is omakase",
"body": "I want this for my ORM, I want that for my template language..."
"comments": ["1", "2"]
}
}
```
@method serializeHasMany
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
*/
serializeHasMany: function (snapshot, json, relationship) {
var attr = relationship.key;
if (this.noSerializeOptionSpecified(attr)) {
this._super(snapshot, json, relationship);
return;
}
var includeIds = this.hasSerializeIdsOption(attr);
var includeRecords = this.hasSerializeRecordsOption(attr);
var key, hasMany;
if (includeIds) {
key = this.keyForRelationship(attr, relationship.kind, 'serialize');
json[key] = snapshot.hasMany(attr, { ids: true });
} else if (includeRecords) {
key = this.keyForAttribute(attr, 'serialize');
hasMany = snapshot.hasMany(attr);
json[key] = Ember.A(hasMany).map(function (embeddedSnapshot) {
var embeddedJson = embeddedSnapshot.record.serialize({ includeId: true });
this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, embeddedJson);
return embeddedJson;
}, this);
}
},
/**
When serializing an embedded record, modify the property (in the json payload)
that refers to the parent record (foreign key for relationship).
Serializing a `belongsTo` relationship removes the property that refers to the
parent record
Serializing a `hasMany` relationship does not remove the property that refers to
the parent record.
@method removeEmbeddedForeignKey
@param {DS.Snapshot} snapshot
@param {DS.Snapshot} embeddedSnapshot
@param {Object} relationship
@param {Object} json
*/
removeEmbeddedForeignKey: function (snapshot, embeddedSnapshot, relationship, json) {
if (relationship.kind === 'hasMany') {
return;
} else if (relationship.kind === 'belongsTo') {
var parentRecord = snapshot.type.inverseFor(relationship.key, this.store);
if (parentRecord) {
var name = parentRecord.name;
var embeddedSerializer = this.store.serializerFor(embeddedSnapshot.modelName);
var parentKey = embeddedSerializer.keyForRelationship(name, parentRecord.kind, 'deserialize');
if (parentKey) {
delete json[parentKey];
}
}
}
},
// checks config for attrs option to embedded (always) - serialize and deserialize
hasEmbeddedAlwaysOption: function (attr) {
var option = this.attrsOption(attr);
return option && option.embedded === 'always';
},
// checks config for attrs option to serialize ids
hasSerializeRecordsOption: function (attr) {
var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr);
var option = this.attrsOption(attr);
return alwaysEmbed || option && option.serialize === 'records';
},
// checks config for attrs option to serialize records
hasSerializeIdsOption: function (attr) {
var option = this.attrsOption(attr);
return option && (option.serialize === 'ids' || option.serialize === 'id');
},
// checks config for attrs option to serialize records
noSerializeOptionSpecified: function (attr) {
var option = this.attrsOption(attr);
return !(option && (option.serialize || option.embedded));
},
// checks config for attrs option to deserialize records
// a defined option object for a resource is treated the same as
// `deserialize: 'records'`
hasDeserializeRecordsOption: function (attr) {
var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr);
var option = this.attrsOption(attr);
return alwaysEmbed || option && option.deserialize === 'records';
},
attrsOption: function (attr) {
var attrs = this.get('attrs');
return attrs && (attrs[ember$data$lib$serializers$embedded$records$mixin$$camelize(attr)] || attrs[attr]);
}
});
// chooses a relationship kind to branch which function is used to update payload
// does not change payload if attr is not embedded
function ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedRecords(serializer, store, typeClass, partial) {
typeClass.eachRelationship(function (key, relationship) {
if (serializer.hasDeserializeRecordsOption(key)) {
var embeddedTypeClass = store.modelFor(relationship.type);
if (relationship.kind === 'hasMany') {
if (relationship.options.polymorphic) {
ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedHasManyPolymorphic(store, key, partial);
} else {
ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedHasMany(store, key, embeddedTypeClass, partial);
}
}
if (relationship.kind === 'belongsTo') {
if (relationship.options.polymorphic) {
ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedBelongsToPolymorphic(store, key, partial);
} else {
ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedBelongsTo(store, key, embeddedTypeClass, partial);
}
}
}
});
return partial;
}
// handles embedding for `hasMany` relationship
function ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedHasMany(store, key, embeddedTypeClass, hash) {
if (!hash[key]) {
return hash;
}
var ids = [];
var embeddedSerializer = store.serializerFor(embeddedTypeClass.modelName);
ember$data$lib$serializers$embedded$records$mixin$$forEach(hash[key], function (data) {
var embeddedRecord = embeddedSerializer.normalize(embeddedTypeClass, data, null);
store.push(embeddedTypeClass.modelName, embeddedRecord);
ids.push(embeddedRecord.id);
});
hash[key] = ids;
return hash;
}
function ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedHasManyPolymorphic(store, key, hash) {
if (!hash[key]) {
return hash;
}
var ids = [];
ember$data$lib$serializers$embedded$records$mixin$$forEach(hash[key], function (data) {
var modelName = data.type;
var embeddedSerializer = store.serializerFor(modelName);
var embeddedTypeClass = store.modelFor(modelName);
// var primaryKey = embeddedSerializer.get('primaryKey');
var embeddedRecord = embeddedSerializer.normalize(embeddedTypeClass, data, null);
store.push(embeddedTypeClass.modelName, embeddedRecord);
ids.push({ id: embeddedRecord.id, type: modelName });
});
hash[key] = ids;
return hash;
}
function ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedBelongsTo(store, key, embeddedTypeClass, hash) {
if (!hash[key]) {
return hash;
}
var embeddedSerializer = store.serializerFor(embeddedTypeClass.modelName);
var embeddedRecord = embeddedSerializer.normalize(embeddedTypeClass, hash[key], null);
store.push(embeddedTypeClass.modelName, embeddedRecord);
hash[key] = embeddedRecord.id;
//TODO Need to add a reference to the parent later so relationship works between both `belongsTo` records
return hash;
}
function ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedBelongsToPolymorphic(store, key, hash) {
if (!hash[key]) {
return hash;
}
var data = hash[key];
var modelName = data.type;
var embeddedSerializer = store.serializerFor(modelName);
var embeddedTypeClass = store.modelFor(modelName);
var embeddedRecord = embeddedSerializer.normalize(embeddedTypeClass, data, null);
store.push(embeddedTypeClass.modelName, embeddedRecord);
hash[key] = embeddedRecord.id;
hash[key + 'Type'] = modelName;
return hash;
}
var ember$data$lib$serializers$embedded$records$mixin$$default = ember$data$lib$serializers$embedded$records$mixin$$EmbeddedRecordsMixin;
/**
`DS.belongsTo` is used to define One-To-One and One-To-Many
relationships on a [DS.Model](/api/data/classes/DS.Model.html).
`DS.belongsTo` takes an optional hash as a second parameter, currently
supported options are:
- `async`: A boolean value used to explicitly declare this to be an async relationship.
- `inverse`: A string used to identify the inverse property on a
related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses)
#### One-To-One
To declare a one-to-one relationship between two models, use
`DS.belongsTo`:
```app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
profile: DS.belongsTo('profile')
});
```
```app/models/profile.js
import DS from 'ember-data';
export default DS.Model.extend({
user: DS.belongsTo('user')
});
```
#### One-To-Many
To declare a one-to-many relationship between two models, use
`DS.belongsTo` in combination with `DS.hasMany`, like this:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('comment')
});
```
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
post: DS.belongsTo('post')
});
```
You can avoid passing a string as the first parameter. In that case Ember Data
will infer the type from the key name.
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
post: DS.belongsTo()
});
```
will lookup for a Post type.
@namespace
@method belongsTo
@for DS
@param {String} modelName (optional) type of the relationship
@param {Object} options (optional) a hash of options
@return {Ember.computed} relationship
*/
function ember$data$lib$system$relationships$belongs$to$$belongsTo(modelName, options) {
var opts, userEnteredModelName;
if (typeof modelName === "object") {
opts = modelName;
userEnteredModelName = undefined;
} else {
opts = options;
userEnteredModelName = modelName;
}
if (typeof userEnteredModelName === "string") {
userEnteredModelName = ember$data$lib$system$normalize$model$name$$default(userEnteredModelName);
}
opts = opts || {};
var meta = {
type: userEnteredModelName,
isRelationship: true,
options: opts,
kind: "belongsTo",
key: null
};
return ember$data$lib$utils$computed$polyfill$$default({
get: function (key) {
return this._internalModel._relationships.get(key).getRecord();
},
set: function (key, value) {
if (value === undefined) {
value = null;
}
if (value && value.then) {
this._internalModel._relationships.get(key).setRecordPromise(value);
} else if (value) {
this._internalModel._relationships.get(key).setRecord(value._internalModel);
} else {
this._internalModel._relationships.get(key).setRecord(value);
}
return this._internalModel._relationships.get(key).getRecord();
}
}).meta(meta);
}
/*
These observers observe all `belongsTo` relationships on the record. See
`relationships/ext` to see how these observers get their dependencies.
*/
ember$data$lib$system$model$$default.reopen({
notifyBelongsToChanged: function (key) {
this.notifyPropertyChange(key);
}
});
var ember$data$lib$system$relationships$belongs$to$$default = ember$data$lib$system$relationships$belongs$to$$belongsTo;
/**
`DS.hasMany` is used to define One-To-Many and Many-To-Many
relationships on a [DS.Model](/api/data/classes/DS.Model.html).
`DS.hasMany` takes an optional hash as a second parameter, currently
supported options are:
- `async`: A boolean value used to explicitly declare this to be an async relationship.
- `inverse`: A string used to identify the inverse property on a related model.
#### One-To-Many
To declare a one-to-many relationship between two models, use
`DS.belongsTo` in combination with `DS.hasMany`, like this:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('comment')
});
```
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
post: DS.belongsTo('post')
});
```
#### Many-To-Many
To declare a many-to-many relationship between two models, use
`DS.hasMany`:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
tags: DS.hasMany('tag')
});
```
```app/models/tag.js
import DS from 'ember-data';
export default DS.Model.extend({
posts: DS.hasMany('post')
});
```
You can avoid passing a string as the first parameter. In that case Ember Data
will infer the type from the singularized key name.
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
tags: DS.hasMany()
});
```
will lookup for a Tag type.
#### Explicit Inverses
Ember Data will do its best to discover which relationships map to
one another. In the one-to-many code above, for example, Ember Data
can figure out that changing the `comments` relationship should update
the `post` relationship on the inverse because post is the only
relationship to that model.
However, sometimes you may have multiple `belongsTo`/`hasManys` for the
same type. You can specify which property on the related model is
the inverse using `DS.hasMany`'s `inverse` option:
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
onePost: DS.belongsTo('post'),
twoPost: DS.belongsTo('post'),
redPost: DS.belongsTo('post'),
bluePost: DS.belongsTo('post')
});
```
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('comment', {
inverse: 'redPost'
})
});
```
You can also specify an inverse on a `belongsTo`, which works how
you'd expect.
@namespace
@method hasMany
@for DS
@param {String} type (optional) type of the relationship
@param {Object} options (optional) a hash of options
@return {Ember.computed} relationship
*/
function ember$data$lib$system$relationships$has$many$$hasMany(type, options) {
if (typeof type === "object") {
options = type;
type = undefined;
}
options = options || {};
if (typeof type === "string") {
type = ember$data$lib$system$normalize$model$name$$default(type);
}
// Metadata about relationships is stored on the meta of
// the relationship. This is used for introspection and
// serialization. Note that `key` is populated lazily
// the first time the CP is called.
var meta = {
type: type,
isRelationship: true,
options: options,
kind: "hasMany",
key: null
};
return ember$data$lib$utils$computed$polyfill$$default({
get: function (key) {
var relationship = this._internalModel._relationships.get(key);
return relationship.getRecords();
},
set: function (key, records) {
var relationship = this._internalModel._relationships.get(key);
relationship.clear();
relationship.addRecords(Ember.A(records).mapBy("_internalModel"));
return relationship.getRecords();
}
}).meta(meta);
}
ember$data$lib$system$model$$default.reopen({
notifyHasManyAdded: function (key) {
//We need to notifyPropertyChange in the adding case because we need to make sure
//we fetch the newly added record in case it is unloaded
//TODO(Igor): Consider whether we could do this only if the record state is unloaded
//Goes away once hasMany is double promisified
this.notifyPropertyChange(key);
}
});
var ember$data$lib$system$relationships$has$many$$default = ember$data$lib$system$relationships$has$many$$hasMany;
function ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(meta) {
var modelName;
modelName = meta.type || meta.key;
if (meta.kind === 'hasMany') {
modelName = ember$inflector$lib$lib$system$string$$singularize(ember$data$lib$system$normalize$model$name$$default(modelName));
}
return modelName;
}
function ember$data$lib$system$relationship$meta$$relationshipFromMeta(meta) {
return {
key: meta.key,
kind: meta.kind,
type: ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(meta),
options: meta.options,
parentType: meta.parentType,
isRelationship: true
};
}
var ember$data$lib$system$relationships$ext$$get = Ember.get;
var ember$data$lib$system$relationships$ext$$filter = Ember.ArrayPolyfills.filter;
var ember$data$lib$system$relationships$ext$$relationshipsDescriptor = Ember.computed(function () {
if (Ember.testing === true && ember$data$lib$system$relationships$ext$$relationshipsDescriptor._cacheable === true) {
ember$data$lib$system$relationships$ext$$relationshipsDescriptor._cacheable = false;
}
var map = new ember$data$lib$system$map$$MapWithDefault({
defaultValue: function () {
return [];
}
});
// Loop through each computed property on the class
this.eachComputedProperty(function (name, meta) {
// If the computed property is a relationship, add
// it to the map.
if (meta.isRelationship) {
meta.key = name;
var relationshipsForType = map.get(ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(meta));
relationshipsForType.push({
name: name,
kind: meta.kind
});
}
});
return map;
}).readOnly();
var ember$data$lib$system$relationships$ext$$relatedTypesDescriptor = Ember.computed(function () {
if (Ember.testing === true && ember$data$lib$system$relationships$ext$$relatedTypesDescriptor._cacheable === true) {
ember$data$lib$system$relationships$ext$$relatedTypesDescriptor._cacheable = false;
}
var modelName;
var types = Ember.A();
// Loop through each computed property on the class,
// and create an array of the unique types involved
// in relationships
this.eachComputedProperty(function (name, meta) {
if (meta.isRelationship) {
meta.key = name;
modelName = ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(meta);
if (!types.contains(modelName)) {
types.push(modelName);
}
}
});
return types;
}).readOnly();
var ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor = Ember.computed(function () {
if (Ember.testing === true && ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor._cacheable === true) {
ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor._cacheable = false;
}
var map = ember$data$lib$system$map$$Map.create();
this.eachComputedProperty(function (name, meta) {
if (meta.isRelationship) {
meta.key = name;
var relationship = ember$data$lib$system$relationship$meta$$relationshipFromMeta(meta);
relationship.type = ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(meta);
map.set(name, relationship);
}
});
return map;
}).readOnly();
/**
@module ember-data
*/
/*
This file defines several extensions to the base `DS.Model` class that
add support for one-to-many relationships.
*/
/**
@class Model
@namespace DS
*/
ember$data$lib$system$model$$default.reopen({
/**
This Ember.js hook allows an object to be notified when a property
is defined.
In this case, we use it to be notified when an Ember Data user defines a
belongs-to relationship. In that case, we need to set up observers for
each one, allowing us to track relationship changes and automatically
reflect changes in the inverse has-many array.
This hook passes the class being set up, as well as the key and value
being defined. So, for example, when the user does this:
```javascript
DS.Model.extend({
parent: DS.belongsTo('user')
});
```
This hook would be called with "parent" as the key and the computed
property returned by `DS.belongsTo` as the value.
@method didDefineProperty
@param {Object} proto
@param {String} key
@param {Ember.ComputedProperty} value
*/
didDefineProperty: function (proto, key, value) {
// Check if the value being set is a computed property.
if (value instanceof Ember.ComputedProperty) {
// If it is, get the metadata for the relationship. This is
// populated by the `DS.belongsTo` helper when it is creating
// the computed property.
var meta = value.meta();
meta.parentType = proto.constructor;
}
}
});
/*
These DS.Model extensions add class methods that provide relationship
introspection abilities about relationships.
A note about the computed properties contained here:
**These properties are effectively sealed once called for the first time.**
To avoid repeatedly doing expensive iteration over a model's fields, these
values are computed once and then cached for the remainder of the runtime of
your application.
If your application needs to modify a class after its initial definition
(for example, using `reopen()` to add additional attributes), make sure you
do it before using your model with the store, which uses these properties
extensively.
*/
ember$data$lib$system$model$$default.reopenClass({
/**
For a given relationship name, returns the model type of the relationship.
For example, if you define a model like this:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('comment')
});
```
Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`.
@method typeForRelationship
@static
@param {String} name the name of the relationship
@param {store} store an instance of DS.Store
@return {DS.Model} the type of the relationship, or undefined
*/
typeForRelationship: function (name, store) {
var relationship = ember$data$lib$system$relationships$ext$$get(this, "relationshipsByName").get(name);
return relationship && store.modelFor(relationship.type);
},
inverseMap: Ember.computed(function () {
return Ember.create(null);
}),
/**
Find the relationship which is the inverse of the one asked for.
For example, if you define models like this:
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('message')
});
```
```app/models/message.js
import DS from 'ember-data';
export default DS.Model.extend({
owner: DS.belongsTo('post')
});
```
App.Post.inverseFor('comments') -> {type: App.Message, name:'owner', kind:'belongsTo'}
App.Message.inverseFor('owner') -> {type: App.Post, name:'comments', kind:'hasMany'}
@method inverseFor
@static
@param {String} name the name of the relationship
@return {Object} the inverse relationship, or null
*/
inverseFor: function (name, store) {
var inverseMap = ember$data$lib$system$relationships$ext$$get(this, "inverseMap");
if (inverseMap[name]) {
return inverseMap[name];
} else {
var inverse = this._findInverseFor(name, store);
inverseMap[name] = inverse;
return inverse;
}
},
//Calculate the inverse, ignoring the cache
_findInverseFor: function (name, store) {
var inverseType = this.typeForRelationship(name, store);
if (!inverseType) {
return null;
}
var propertyMeta = this.metaForProperty(name);
//If inverse is manually specified to be null, like `comments: DS.hasMany('message', {inverse: null})`
var options = propertyMeta.options;
if (options.inverse === null) {
return null;
}
var inverseName, inverseKind, inverse;
//If inverse is specified manually, return the inverse
if (options.inverse) {
inverseName = options.inverse;
inverse = Ember.get(inverseType, "relationshipsByName").get(inverseName);
inverseKind = inverse.kind;
} else {
//No inverse was specified manually, we need to use a heuristic to guess one
var possibleRelationships = findPossibleInverses(this, inverseType);
if (possibleRelationships.length === 0) {
return null;
}
var filteredRelationships = ember$data$lib$system$relationships$ext$$filter.call(possibleRelationships, function (possibleRelationship) {
var optionsForRelationship = inverseType.metaForProperty(possibleRelationship.name).options;
return name === optionsForRelationship.inverse;
});
if (filteredRelationships.length === 1) {
possibleRelationships = filteredRelationships;
}
inverseName = possibleRelationships[0].name;
inverseKind = possibleRelationships[0].kind;
}
function findPossibleInverses(type, inverseType, relationshipsSoFar) {
var possibleRelationships = relationshipsSoFar || [];
var relationshipMap = ember$data$lib$system$relationships$ext$$get(inverseType, "relationships");
if (!relationshipMap) {
return possibleRelationships;
}
var relationships = relationshipMap.get(type.modelName);
relationships = ember$data$lib$system$relationships$ext$$filter.call(relationships, function (relationship) {
var optionsForRelationship = inverseType.metaForProperty(relationship.name).options;
if (!optionsForRelationship.inverse) {
return true;
}
return name === optionsForRelationship.inverse;
});
if (relationships) {
possibleRelationships.push.apply(possibleRelationships, relationships);
}
//Recurse to support polymorphism
if (type.superclass) {
findPossibleInverses(type.superclass, inverseType, possibleRelationships);
}
return possibleRelationships;
}
return {
type: inverseType,
name: inverseName,
kind: inverseKind
};
},
/**
The model's relationships as a map, keyed on the type of the
relationship. The value of each entry is an array containing a descriptor
for each relationship with that type, describing the name of the relationship
as well as the type.
For example, given the following model definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This computed property would return a map describing these
relationships, like this:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
var relationships = Ember.get(Blog, 'relationships');
relationships.get(App.User);
//=> [ { name: 'users', kind: 'hasMany' },
// { name: 'owner', kind: 'belongsTo' } ]
relationships.get(App.Post);
//=> [ { name: 'posts', kind: 'hasMany' } ]
```
@property relationships
@static
@type Ember.Map
@readOnly
*/
relationships: ember$data$lib$system$relationships$ext$$relationshipsDescriptor,
/**
A hash containing lists of the model's relationships, grouped
by the relationship kind. For example, given a model with this
definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
var relationshipNames = Ember.get(Blog, 'relationshipNames');
relationshipNames.hasMany;
//=> ['users', 'posts']
relationshipNames.belongsTo;
//=> ['owner']
```
@property relationshipNames
@static
@type Object
@readOnly
*/
relationshipNames: Ember.computed(function () {
var names = {
hasMany: [],
belongsTo: []
};
this.eachComputedProperty(function (name, meta) {
if (meta.isRelationship) {
names[meta.kind].push(name);
}
});
return names;
}),
/**
An array of types directly related to a model. Each type will be
included once, regardless of the number of relationships it has with
the model.
For example, given a model with this definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
var relatedTypes = Ember.get(Blog, 'relatedTypes');
//=> [ App.User, App.Post ]
```
@property relatedTypes
@static
@type Ember.Array
@readOnly
*/
relatedTypes: ember$data$lib$system$relationships$ext$$relatedTypesDescriptor,
/**
A map whose keys are the relationships of a model and whose values are
relationship descriptors.
For example, given a model with this
definition:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
import Ember from 'ember';
import Blog from 'app/models/blog';
var relationshipsByName = Ember.get(Blog, 'relationshipsByName');
relationshipsByName.get('users');
//=> { key: 'users', kind: 'hasMany', type: App.User }
relationshipsByName.get('owner');
//=> { key: 'owner', kind: 'belongsTo', type: App.User }
```
@property relationshipsByName
@static
@type Ember.Map
@readOnly
*/
relationshipsByName: ember$data$lib$system$relationships$ext$$relationshipsByNameDescriptor,
/**
A map whose keys are the fields of the model and whose values are strings
describing the kind of the field. A model's fields are the union of all of its
attributes and relationships.
For example:
```app/models/blog.js
import DS from 'ember-data';
export default DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post'),
title: DS.attr('string')
});
```
```js
import Ember from 'ember';
import Blog from 'app/models/blog';
var fields = Ember.get(Blog, 'fields');
fields.forEach(function(kind, field) {
console.log(field, kind);
});
// prints:
// users, hasMany
// owner, belongsTo
// posts, hasMany
// title, attribute
```
@property fields
@static
@type Ember.Map
@readOnly
*/
fields: Ember.computed(function () {
var map = ember$data$lib$system$map$$Map.create();
this.eachComputedProperty(function (name, meta) {
if (meta.isRelationship) {
map.set(name, meta.kind);
} else if (meta.isAttribute) {
map.set(name, "attribute");
}
});
return map;
}).readOnly(),
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
@method eachRelationship
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship: function (callback, binding) {
ember$data$lib$system$relationships$ext$$get(this, "relationshipsByName").forEach(function (relationship, name) {
callback.call(binding, name, relationship);
});
},
/**
Given a callback, iterates over each of the types related to a model,
invoking the callback with the related type's class. Each type will be
returned just once, regardless of how many different relationships it has
with a model.
@method eachRelatedType
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelatedType: function (callback, binding) {
ember$data$lib$system$relationships$ext$$get(this, "relatedTypes").forEach(function (type) {
callback.call(binding, type);
});
},
determineRelationshipType: function (knownSide, store) {
var knownKey = knownSide.key;
var knownKind = knownSide.kind;
var inverse = this.inverseFor(knownKey, store);
var key, otherKind;
if (!inverse) {
return knownKind === "belongsTo" ? "oneToNone" : "manyToNone";
}
key = inverse.name;
otherKind = inverse.kind;
if (otherKind === "belongsTo") {
return knownKind === "belongsTo" ? "oneToOne" : "manyToOne";
} else {
return knownKind === "belongsTo" ? "oneToMany" : "manyToMany";
}
}
});
ember$data$lib$system$model$$default.reopen({
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, descriptor);
```
- `name` the name of the current property in the iteration
- `descriptor` the meta object that describes this relationship
The relationship descriptor argument is an object with the following properties.
- **key** <span class="type">String</span> the name of this relationship on the Model
- **kind** <span class="type">String</span> "hasMany" or "belongsTo"
- **options** <span class="type">Object</span> the original options hash passed when the relationship was declared
- **parentType** <span class="type">DS.Model</span> the type of the Model that owns this relationship
- **type** <span class="type">DS.Model</span> the type of the related Model
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serialize: function(record, options) {
var json = {};
record.eachRelationship(function(name, descriptor) {
if (descriptor.kind === 'hasMany') {
var serializedHasManyName = name.toUpperCase() + '_IDS';
json[name.toUpperCase()] = record.get(name).mapBy('id');
}
});
return json;
}
});
```
@method eachRelationship
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship: function (callback, binding) {
this.constructor.eachRelationship(callback, binding);
},
relationshipFor: function (name) {
return ember$data$lib$system$relationships$ext$$get(this.constructor, "relationshipsByName").get(name);
},
inverseFor: function (key) {
return this.constructor.inverseFor(key, this.store);
}
});
/**
Ember Data
@module ember-data
@main ember-data
*/
if (Ember.VERSION.match(/^1\.[0-7]\./)) {
throw new Ember.Error("Ember Data requires at least Ember 1.8.0, but you have " + Ember.VERSION + ". Please upgrade your version of Ember, then upgrade Ember Data");
}
// support RSVP 2.x via resolve, but prefer RSVP 3.x's Promise.cast
Ember.RSVP.Promise.cast = Ember.RSVP.Promise.cast || Ember.RSVP.resolve;ember$data$lib$core$$default.Store = ember$data$lib$system$store$$Store;
ember$data$lib$core$$default.PromiseArray = ember$data$lib$system$promise$proxies$$PromiseArray;
ember$data$lib$core$$default.PromiseObject = ember$data$lib$system$promise$proxies$$PromiseObject;
ember$data$lib$core$$default.PromiseManyArray = ember$data$lib$system$promise$proxies$$PromiseManyArray;
ember$data$lib$core$$default.Model = ember$data$lib$system$model$$default;
ember$data$lib$core$$default.RootState = ember$data$lib$system$model$states$$default;
ember$data$lib$core$$default.attr = ember$data$lib$system$model$attributes$$default;
ember$data$lib$core$$default.Errors = ember$data$lib$system$model$errors$$default;
ember$data$lib$core$$default.InternalModel = ember$data$lib$system$model$internal$model$$default;
ember$data$lib$core$$default.Snapshot = ember$data$lib$system$snapshot$$default;
ember$data$lib$core$$default.Adapter = ember$data$lib$system$adapter$$Adapter;
ember$data$lib$core$$default.InvalidError = ember$data$lib$system$model$errors$invalid$$default;
ember$data$lib$core$$default.Serializer = ember$data$lib$system$serializer$$default;
ember$data$lib$core$$default.DebugAdapter = ember$data$lib$system$debug$$default;
ember$data$lib$core$$default.RecordArray = ember$data$lib$system$record$arrays$record$array$$default;
ember$data$lib$core$$default.FilteredRecordArray = ember$data$lib$system$record$arrays$filtered$record$array$$default;
ember$data$lib$core$$default.AdapterPopulatedRecordArray = ember$data$lib$system$record$arrays$adapter$populated$record$array$$default;
ember$data$lib$core$$default.ManyArray = ember$data$lib$system$many$array$$default;
ember$data$lib$core$$default.RecordArrayManager = ember$data$lib$system$record$array$manager$$default;
ember$data$lib$core$$default.RESTAdapter = ember$data$lib$adapters$rest$adapter$$default;
ember$data$lib$core$$default.BuildURLMixin = ember$data$lib$adapters$build$url$mixin$$default;
ember$data$lib$core$$default.RESTSerializer = ember$data$lib$serializers$rest$serializer$$default;
ember$data$lib$core$$default.JSONSerializer = ember$data$lib$serializers$json$serializer$$default;
ember$data$lib$core$$default.Transform = ember$data$lib$transforms$base$$default;
ember$data$lib$core$$default.DateTransform = ember$data$lib$transforms$date$$default;
ember$data$lib$core$$default.StringTransform = ember$data$lib$transforms$string$$default;
ember$data$lib$core$$default.NumberTransform = ember$data$lib$transforms$number$$default;
ember$data$lib$core$$default.BooleanTransform = ember$data$lib$transforms$boolean$$default;
ember$data$lib$core$$default.ActiveModelAdapter = activemodel$adapter$lib$system$active$model$adapter$$default;
ember$data$lib$core$$default.ActiveModelSerializer = activemodel$adapter$lib$system$active$model$serializer$$default;
ember$data$lib$core$$default.EmbeddedRecordsMixin = ember$data$lib$serializers$embedded$records$mixin$$default;
ember$data$lib$core$$default.belongsTo = ember$data$lib$system$relationships$belongs$to$$default;
ember$data$lib$core$$default.hasMany = ember$data$lib$system$relationships$has$many$$default;
ember$data$lib$core$$default.Relationship = ember$data$lib$system$relationships$state$relationship$$default;
ember$data$lib$core$$default.ContainerProxy = ember$data$lib$system$container$proxy$$default;
ember$data$lib$core$$default._setupContainer = ember$data$lib$setup$container$$default;
Ember.defineProperty(ember$data$lib$core$$default, "normalizeModelName", {
enumerable: true,
writable: false,
configurable: false,
value: ember$data$lib$system$normalize$model$name$$default
});
var ember$data$lib$main$$fixtureAdapterWasDeprecated = false;
if (Ember.platform.hasPropertyAccessors) {
Ember.defineProperty(ember$data$lib$core$$default, "FixtureAdapter", {
get: function () {
if (!ember$data$lib$main$$fixtureAdapterWasDeprecated) {
ember$data$lib$main$$fixtureAdapterWasDeprecated = true;
}
return ember$data$lib$adapters$fixture$adapter$$default;
}
});
} else {
ember$data$lib$core$$default.FixtureAdapter = ember$data$lib$adapters$fixture$adapter$$default;
}
Ember.lookup.DS = ember$data$lib$core$$default;
var ember$data$lib$main$$default = ember$data$lib$core$$default;
}).call(this);
|
packages/material-ui-icons/src/AirplayRounded.js | allanalexandre/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M8.41 22h7.17c.89 0 1.34-1.08.71-1.71L12.7 16.7a.9959.9959 0 0 0-1.41 0L7.7 20.29c-.62.63-.18 1.71.71 1.71zM21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h3c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1-.45-1-1V6c0-.55.45-1 1-1h16c.55 0 1 .45 1 1v10c0 .55-.45 1-1 1h-2c-.55 0-1 .45-1 1s.45 1 1 1h3c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z" /></React.Fragment>
, 'AirplayRounded');
|
client/react/Macweb.js | ed1d1a8d/macweb | import React, { Component } from 'react';
import Navbar from './Navbar.js'
class Macweb extends Component {
render() {
//Image map created by jtwright
let map = (
<map name="macg">
<area href="/entry/a" shape="poly" coords="285,68,329,92,417,42,417,93,329,144,285,119" alt="Link" data-maphilight='{"strokeColor":"ffffff","strokeWidth":2,"fillColor":"80eeff","fillOpacity":0.5}' title="A Entry" />
<area href="/entry/b" shape="poly" coords="285,119,329,144,417,93,417,144,329,194,285,169" alt="Link" data-maphilight='{"strokeColor":"ffffff","strokeWidth":2,"fillColor":"8080ff","fillOpacity":0.5}' title="B Entry" />
<area href="/entry/c" shape="poly" coords="285,169,329,194,417,144,417,195,329,245,285,220" alt="Link" data-maphilight='{"strokeColor":"ffffff","strokeWidth":2,"fillColor":"80ff80","fillOpacity":0.5}' title="C Entry" />
<area href="/entry/d" shape="poly" coords="285,220,329,245,417,195,417,245,329,295,285,270" alt="Link" data-maphilight='{"strokeColor":"ffffff","strokeWidth":2,"fillColor":"ff9180","fillOpacity":0.5}' title="D Entry" />
<area href="/entry/e" shape="poly" coords="285,270,329,295,402,254,418,244,402,254,402,304,329,346,285,321" alt="Link" data-maphilight='{"strokeColor":"ffffff","strokeWidth":2,"fillColor":"0f0f0f","fillOpacity":0.5}' title="E Entry" />
<area href="/entry/f" shape="poly" coords="402,254,446,228,593,313,593,381,520,423,520,355,475,330,447,346,402,322" alt="Link" data-maphilight='{"strokeColor":"ffffff","strokeWidth":2,"fillColor":"ff80ff","fillOpacity":0.5}' title="F Entry" />
<area href="/entry/g" shape="poly" coords="475,330,520,355,520,423,329,533,329,466,285,440" alt="Link" data-maphilight='{"strokeColor":"ffffff","strokeWidth":2,"fillColor":"ff6600","fillOpacity":0.5}' title="G Entry" />
<area href="/entry/h/index.html" shape="poly" coords="285,440,329,466,329,533,256,575,138,508,138,440,182,414,256,457" alt="Link" data-maphilight='{"strokeColor":"ffffff","strokeWidth":2,"fillColor":"88ff80","fillOpacity":0.5}' title="H Entry" />
<area href="/entry/j" shape="poly" coords="182,414,138,440,138,508,65,465,65,398,152,347,196,372,196,422" alt="Link" data-maphilight='{"strokeColor":"ffffff","strokeWidth":2,"fillColor":"bf80ff","fillOpacity":0.5}' title="J Entry" />
</map>
)
//Made with David Lynch's Maphilight: http://davidlynch.org/blog/2008/03/maphilight-image-map-mouseover-highlighting/
//reinsert the navbar before the container
return (
<div>
<noscript>
<p>Javascript is becoming core to the internet, this website requires it to function.</p>
</noscript>
<Navbar />
<br/>
<div className="container">
<div style={{width: "622px", margin: "0 auto"}} id="macg-image-map">
<img src="/images/macgregor-schematic-outline.png" width="622" height="610" className="map" useMap="#macg" />
{map}
<br/>
<p>Click on a letter to find out more about that entry.</p>
</div>
<br/><br/>
</div>
</div>
);
}
componentDidMount() {
$('img[usemap]').maphilight();
}
}
export default Macweb;
|
BackUp FIrebase/IQApp/index.android.js | victorditadi/IQApp | import { AppRegistry } from 'react-native';
import App from './src/app';
AppRegistry.registerComponent('IQApp', () => App);
// import React, { Component } from 'react';
// import {
// AppRegistry,
// Text,
// View,
// Dimensions,
// } from 'react-native';
// import Carousel from 'react-native-looped-carousel';
//
// const { width, height } = Dimensions.get('window');
//
// export default class CarouselExample extends Component {
//
// constructor(props) {
// super(props);
//
// this.state = {
// size: { width, height },
// };
// }
//
// _onLayoutDidChange = (e) => {
// const layout = e.nativeEvent.layout;
// this.setState({ size: { width: layout.width, height: layout.height } });
// }
//
// render() {
// return (
// <View style={{ flex: 1 }} onLayout={this._onLayoutDidChange}>
// <Carousel
// delay={2000}
// style={this.state.size}
// autoplay = {false}
// pageInfo
// onAnimateNextPage={(p) => console.log(p)}
// >
// <View style={[{ backgroundColor: '#BADA55' }, this.state.size]}><Text>1</Text></View>
// <View style={[{ backgroundColor: 'red' }, this.state.size]}><Text>2</Text></View>
// <View style={[{ backgroundColor: 'blue' }, this.state.size]}><Text>3</Text></View>
// </Carousel>
// </View>
// );
// }
// }
// AppRegistry.registerComponent('IQApp', () => CarouselExample);
|
server.js | owennicol/yaiza | if (typeof(window) == 'undefined'){
global.window = new Object();
}
var express = require('express')
var path = require('path')
var compression = require('compression')
var Helmet = require('react-helmet')
import React from 'react'
// we'll use this to render our app to an html string
import { renderToString } from 'react-dom/server'
// and these to match the url to routes and then render
import { match, RouterContext } from 'react-router'
import routes from './config/routes'
let MobileDetect = require('mobile-detect');
var app = express()
app.use(compression())
// serve our static stuff like index.css
app.use(express.static(path.join(__dirname, 'public')))
app.use(express.static(path.join(__dirname, 'fonts')))
app.get('*', (req, res) => {
let md = new MobileDetect(req.headers['user-agent']);
match({ routes: routes, location: req.url }, (err, redirect, props) => {
// in here we can make some decisions all at once
if (err) {
// there was an error somewhere during route matching
res.status(500).send(err.message)
} else if (redirect) {
// we haven't talked about `onEnter` hooks on routes, but before a
// route is entered, it can redirect. Here we handle on the server.
res.redirect(redirect.pathname + redirect.search)
} else if (props) {
// if we got props then we matched a route and can render
const appHtml = renderToString(<RouterContext {...props}/>)
const helmet = Helmet.renderStatic();
res.send(renderPage(appHtml))
} else {
// no errors, no redirect, we just didn't match anything
res.status(404).send('Not Found')
}
})
})
function renderPage(appHtml) {
return `
<!doctype html public="storage">
<html>
<head>
<meta charset=utf-8/>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, maximum-scale=1">
<title>Yaiza</title>
<base href="/">
<link type="text/css" rel="stylesheet" href="index.css">
</head>
<body>
<div id=app tabindex="-1">${appHtml}</div>
<script src="/bundle.js"></script>
</body>
</html>
`
}
var PORT = process.env.PORT || 5000
app.listen(PORT, function() {
console.log('Production Express server running at localhost:' + PORT)
})
|
packages/material-ui-icons/src/SettingsVoice.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M7 24h2v-2H7v2zm5-11c1.66 0 2.99-1.34 2.99-3L15 4c0-1.66-1.34-3-3-3S9 2.34 9 4v6c0 1.66 1.34 3 3 3zm-1 11h2v-2h-2v2zm4 0h2v-2h-2v2zm4-14h-1.7c0 3-2.54 5.1-5.3 5.1S6.7 13 6.7 10H5c0 3.41 2.72 6.23 6 6.72V20h2v-3.28c3.28-.49 6-3.31 6-6.72z" /><path fill="none" d="M0 0h24v24H0z" /></React.Fragment>
, 'SettingsVoice');
|
public/bower_components/react/JSXTransformer.js | pchinjr/ghostreporter-react | /**
* JSXTransformer v0.13.3
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JSXTransformer = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*/
/* jshint browser: true */
/* jslint evil: true */
/*eslint-disable no-eval */
/*eslint-disable block-scoped-var */
'use strict';
var ReactTools = _dereq_('../main');
var inlineSourceMap = _dereq_('./inline-source-map');
var headEl;
var dummyAnchor;
var inlineScriptCount = 0;
// The source-map library relies on Object.defineProperty, but IE8 doesn't
// support it fully even with es5-sham. Indeed, es5-sham's defineProperty
// throws when Object.prototype.__defineGetter__ is missing, so we skip building
// the source map in that case.
var supportsAccessors = Object.prototype.hasOwnProperty('__defineGetter__');
/**
* Run provided code through jstransform.
*
* @param {string} source Original source code
* @param {object?} options Options to pass to jstransform
* @return {object} object as returned from jstransform
*/
function transformReact(source, options) {
options = options || {};
// Force the sourcemaps option manually. We don't want to use it if it will
// break (see above note about supportsAccessors). We'll only override the
// value here if sourceMap was specified and is truthy. This guarantees that
// we won't override any user intent (since this method is exposed publicly).
if (options.sourceMap) {
options.sourceMap = supportsAccessors;
}
// Otherwise just pass all options straight through to react-tools.
return ReactTools.transformWithDetails(source, options);
}
/**
* Eval provided source after transforming it.
*
* @param {string} source Original source code
* @param {object?} options Options to pass to jstransform
*/
function exec(source, options) {
return eval(transformReact(source, options).code);
}
/**
* This method returns a nicely formated line of code pointing to the exact
* location of the error `e`. The line is limited in size so big lines of code
* are also shown in a readable way.
*
* Example:
* ... x', overflow:'scroll'}} id={} onScroll={this.scroll} class=" ...
* ^
*
* @param {string} code The full string of code
* @param {Error} e The error being thrown
* @return {string} formatted message
* @internal
*/
function createSourceCodeErrorMessage(code, e) {
var sourceLines = code.split('\n');
// e.lineNumber is non-standard so we can't depend on its availability. If
// we're in a browser where it isn't supported, don't even bother trying to
// format anything. We may also hit a case where the line number is reported
// incorrectly and is outside the bounds of the actual code. Handle that too.
if (!e.lineNumber || e.lineNumber > sourceLines.length) {
return '';
}
var erroneousLine = sourceLines[e.lineNumber - 1];
// Removes any leading indenting spaces and gets the number of
// chars indenting the `erroneousLine`
var indentation = 0;
erroneousLine = erroneousLine.replace(/^\s+/, function(leadingSpaces) {
indentation = leadingSpaces.length;
return '';
});
// Defines the number of characters that are going to show
// before and after the erroneous code
var LIMIT = 30;
var errorColumn = e.column - indentation;
if (errorColumn > LIMIT) {
erroneousLine = '... ' + erroneousLine.slice(errorColumn - LIMIT);
errorColumn = 4 + LIMIT;
}
if (erroneousLine.length - errorColumn > LIMIT) {
erroneousLine = erroneousLine.slice(0, errorColumn + LIMIT) + ' ...';
}
var message = '\n\n' + erroneousLine + '\n';
message += new Array(errorColumn - 1).join(' ') + '^';
return message;
}
/**
* Actually transform the code.
*
* @param {string} code
* @param {string?} url
* @param {object?} options
* @return {string} The transformed code.
* @internal
*/
function transformCode(code, url, options) {
try {
var transformed = transformReact(code, options);
} catch(e) {
e.message += '\n at ';
if (url) {
if ('fileName' in e) {
// We set `fileName` if it's supported by this error object and
// a `url` was provided.
// The error will correctly point to `url` in Firefox.
e.fileName = url;
}
e.message += url + ':' + e.lineNumber + ':' + e.columnNumber;
} else {
e.message += location.href;
}
e.message += createSourceCodeErrorMessage(code, e);
throw e;
}
if (!transformed.sourceMap) {
return transformed.code;
}
var source;
if (url == null) {
source = 'Inline JSX script';
inlineScriptCount++;
if (inlineScriptCount > 1) {
source += ' (' + inlineScriptCount + ')';
}
} else if (dummyAnchor) {
// Firefox has problems when the sourcemap source is a proper URL with a
// protocol and hostname, so use the pathname. We could use just the
// filename, but hopefully using the full path will prevent potential
// issues where the same filename exists in multiple directories.
dummyAnchor.href = url;
source = dummyAnchor.pathname.substr(1);
}
return (
transformed.code +
'\n' +
inlineSourceMap(transformed.sourceMap, code, source)
);
}
/**
* Appends a script element at the end of the <head> with the content of code,
* after transforming it.
*
* @param {string} code The original source code
* @param {string?} url Where the code came from. null if inline
* @param {object?} options Options to pass to jstransform
* @internal
*/
function run(code, url, options) {
var scriptEl = document.createElement('script');
scriptEl.text = transformCode(code, url, options);
headEl.appendChild(scriptEl);
}
/**
* Load script from the provided url and pass the content to the callback.
*
* @param {string} url The location of the script src
* @param {function} callback Function to call with the content of url
* @internal
*/
function load(url, successCallback, errorCallback) {
var xhr;
xhr = window.ActiveXObject ? new window.ActiveXObject('Microsoft.XMLHTTP')
: new XMLHttpRequest();
// async, however scripts will be executed in the order they are in the
// DOM to mirror normal script loading.
xhr.open('GET', url, true);
if ('overrideMimeType' in xhr) {
xhr.overrideMimeType('text/plain');
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 0 || xhr.status === 200) {
successCallback(xhr.responseText);
} else {
errorCallback();
throw new Error('Could not load ' + url);
}
}
};
return xhr.send(null);
}
/**
* Loop over provided script tags and get the content, via innerHTML if an
* inline script, or by using XHR. Transforms are applied if needed. The scripts
* are executed in the order they are found on the page.
*
* @param {array} scripts The <script> elements to load and run.
* @internal
*/
function loadScripts(scripts) {
var result = [];
var count = scripts.length;
function check() {
var script, i;
for (i = 0; i < count; i++) {
script = result[i];
if (script.loaded && !script.executed) {
script.executed = true;
run(script.content, script.url, script.options);
} else if (!script.loaded && !script.error && !script.async) {
break;
}
}
}
scripts.forEach(function(script, i) {
var options = {
sourceMap: true
};
if (/;harmony=true(;|$)/.test(script.type)) {
options.harmony = true;
}
if (/;stripTypes=true(;|$)/.test(script.type)) {
options.stripTypes = true;
}
// script.async is always true for non-javascript script tags
var async = script.hasAttribute('async');
if (script.src) {
result[i] = {
async: async,
error: false,
executed: false,
content: null,
loaded: false,
url: script.src,
options: options
};
load(script.src, function(content) {
result[i].loaded = true;
result[i].content = content;
check();
}, function() {
result[i].error = true;
check();
});
} else {
result[i] = {
async: async,
error: false,
executed: false,
content: script.innerHTML,
loaded: true,
url: null,
options: options
};
}
});
check();
}
/**
* Find and run all script tags with type="text/jsx".
*
* @internal
*/
function runScripts() {
var scripts = document.getElementsByTagName('script');
// Array.prototype.slice cannot be used on NodeList on IE8
var jsxScripts = [];
for (var i = 0; i < scripts.length; i++) {
if (/^text\/jsx(;|$)/.test(scripts.item(i).type)) {
jsxScripts.push(scripts.item(i));
}
}
if (jsxScripts.length < 1) {
return;
}
console.warn(
'You are using the in-browser JSX transformer. Be sure to precompile ' +
'your JSX for production - ' +
'http://facebook.github.io/react/docs/tooling-integration.html#jsx'
);
loadScripts(jsxScripts);
}
// Listen for load event if we're in a browser and then kick off finding and
// running of scripts.
if (typeof window !== 'undefined' && window !== null) {
headEl = document.getElementsByTagName('head')[0];
dummyAnchor = document.createElement('a');
if (window.addEventListener) {
window.addEventListener('DOMContentLoaded', runScripts, false);
} else {
window.attachEvent('onload', runScripts);
}
}
module.exports = {
transform: transformReact,
exec: exec
};
},{"../main":2,"./inline-source-map":41}],2:[function(_dereq_,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
/*eslint-disable no-undef*/
var visitors = _dereq_('./vendor/fbtransform/visitors');
var transform = _dereq_('jstransform').transform;
var typesSyntax = _dereq_('jstransform/visitors/type-syntax');
var inlineSourceMap = _dereq_('./vendor/inline-source-map');
module.exports = {
transform: function(input, options) {
options = processOptions(options);
var output = innerTransform(input, options);
var result = output.code;
if (options.sourceMap) {
var map = inlineSourceMap(
output.sourceMap,
input,
options.filename
);
result += '\n' + map;
}
return result;
},
transformWithDetails: function(input, options) {
options = processOptions(options);
var output = innerTransform(input, options);
var result = {};
result.code = output.code;
if (options.sourceMap) {
result.sourceMap = output.sourceMap.toJSON();
}
if (options.filename) {
result.sourceMap.sources = [options.filename];
}
return result;
}
};
/**
* Only copy the values that we need. We'll do some preprocessing to account for
* converting command line flags to options that jstransform can actually use.
*/
function processOptions(opts) {
opts = opts || {};
var options = {};
options.harmony = opts.harmony;
options.stripTypes = opts.stripTypes;
options.sourceMap = opts.sourceMap;
options.filename = opts.sourceFilename;
if (opts.es6module) {
options.sourceType = 'module';
}
if (opts.nonStrictEs6module) {
options.sourceType = 'nonStrictModule';
}
// Instead of doing any fancy validation, only look for 'es3'. If we have
// that, then use it. Otherwise use 'es5'.
options.es3 = opts.target === 'es3';
options.es5 = !options.es3;
return options;
}
function innerTransform(input, options) {
var visitorSets = ['react'];
if (options.harmony) {
visitorSets.push('harmony');
}
if (options.es3) {
visitorSets.push('es3');
}
if (options.stripTypes) {
// Stripping types needs to happen before the other transforms
// unfortunately, due to bad interactions. For example,
// es6-rest-param-visitors conflict with stripping rest param type
// annotation
input = transform(typesSyntax.visitorList, input, options).code;
}
var visitorList = visitors.getVisitorsBySet(visitorSets);
return transform(visitorList, input, options);
}
},{"./vendor/fbtransform/visitors":40,"./vendor/inline-source-map":41,"jstransform":22,"jstransform/visitors/type-syntax":36}],3:[function(_dereq_,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
* @license MIT
*/
var base64 = _dereq_('base64-js')
var ieee754 = _dereq_('ieee754')
var isArray = _dereq_('is-array')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
Buffer.poolSize = 8192 // not used by this implementation
var kMaxLength = 0x3fffffff
var rootParent = {}
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Note:
*
* - Implementation must support adding new properties to `Uint8Array` instances.
* Firefox 4-29 lacked support, fixed in Firefox 30+.
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
*
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will
* get the Object implementation, which is slower but will work correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = (function () {
try {
var buf = new ArrayBuffer(0)
var arr = new Uint8Array(buf)
arr.foo = function () { return 42 }
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
})()
/**
* Class: Buffer
* =============
*
* The Buffer constructor returns instances of `Uint8Array` that are augmented
* with function properties for all the node `Buffer` API functions. We use
* `Uint8Array` so that square bracket notation works as expected -- it returns
* a single octet.
*
* By augmenting the instances, we can avoid modifying the `Uint8Array`
* prototype.
*/
function Buffer (subject, encoding) {
var self = this
if (!(self instanceof Buffer)) return new Buffer(subject, encoding)
var type = typeof subject
var length
if (type === 'number') {
length = +subject
} else if (type === 'string') {
length = Buffer.byteLength(subject, encoding)
} else if (type === 'object' && subject !== null) {
// assume object is array-like
if (subject.type === 'Buffer' && isArray(subject.data)) subject = subject.data
length = +subject.length
} else {
throw new TypeError('must start with number, buffer, array or string')
}
if (length > kMaxLength) {
throw new RangeError('Attempt to allocate Buffer larger than maximum size: 0x' +
kMaxLength.toString(16) + ' bytes')
}
if (length < 0) length = 0
else length >>>= 0 // coerce to uint32
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Preferred: Return an augmented `Uint8Array` instance for best performance
self = Buffer._augment(new Uint8Array(length)) // eslint-disable-line consistent-this
} else {
// Fallback: Return THIS instance of Buffer (created by `new`)
self.length = length
self._isBuffer = true
}
var i
if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
// Speed optimization -- use set if we're copying from a typed array
self._set(subject)
} else if (isArrayish(subject)) {
// Treat array-ish objects as a byte array
if (Buffer.isBuffer(subject)) {
for (i = 0; i < length; i++) {
self[i] = subject.readUInt8(i)
}
} else {
for (i = 0; i < length; i++) {
self[i] = ((subject[i] % 256) + 256) % 256
}
}
} else if (type === 'string') {
self.write(subject, 0, encoding)
} else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT) {
for (i = 0; i < length; i++) {
self[i] = 0
}
}
if (length > 0 && length <= Buffer.poolSize) self.parent = rootParent
return self
}
function SlowBuffer (subject, encoding) {
if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
var buf = new Buffer(subject, encoding)
delete buf.parent
return buf
}
Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {}
if (i !== len) {
x = a[i]
y = b[i]
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'binary':
case 'base64':
case 'raw':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, totalLength) {
if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
if (list.length === 0) {
return new Buffer(0)
} else if (list.length === 1) {
return list[0]
}
var i
if (totalLength === undefined) {
totalLength = 0
for (i = 0; i < list.length; i++) {
totalLength += list[i].length
}
}
var buf = new Buffer(totalLength)
var pos = 0
for (i = 0; i < list.length; i++) {
var item = list[i]
item.copy(buf, pos)
pos += item.length
}
return buf
}
Buffer.byteLength = function byteLength (str, encoding) {
var ret
str = str + ''
switch (encoding || 'utf8') {
case 'ascii':
case 'binary':
case 'raw':
ret = str.length
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = str.length * 2
break
case 'hex':
ret = str.length >>> 1
break
case 'utf8':
case 'utf-8':
ret = utf8ToBytes(str).length
break
case 'base64':
ret = base64ToBytes(str).length
break
default:
ret = str.length
}
return ret
}
// pre-set for values that may exist in the future
Buffer.prototype.length = undefined
Buffer.prototype.parent = undefined
// toString(encoding, start=0, end=buffer.length)
Buffer.prototype.toString = function toString (encoding, start, end) {
var loweredCase = false
start = start >>> 0
end = end === undefined || end === Infinity ? this.length : end >>> 0
if (!encoding) encoding = 'utf8'
if (start < 0) start = 0
if (end > this.length) end = this.length
if (end <= start) return ''
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'binary':
return binarySlice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return 0
return Buffer.compare(this, b)
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
else if (byteOffset < -0x80000000) byteOffset = -0x80000000
byteOffset >>= 0
if (this.length === 0) return -1
if (byteOffset >= this.length) return -1
// Negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
if (typeof val === 'string') {
if (val.length === 0) return -1 // special case: looking for empty string always fails
return String.prototype.indexOf.call(this, val, byteOffset)
}
if (Buffer.isBuffer(val)) {
return arrayIndexOf(this, val, byteOffset)
}
if (typeof val === 'number') {
if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
}
return arrayIndexOf(this, [ val ], byteOffset)
}
function arrayIndexOf (arr, val, byteOffset) {
var foundIndex = -1
for (var i = 0; byteOffset + i < arr.length; i++) {
if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
} else {
foundIndex = -1
}
}
return -1
}
throw new TypeError('val must be string, number or Buffer')
}
// `get` will be removed in Node 0.13+
Buffer.prototype.get = function get (offset) {
console.log('.get() is deprecated. Access using array indexes instead.')
return this.readUInt8(offset)
}
// `set` will be removed in Node 0.13+
Buffer.prototype.set = function set (v, offset) {
console.log('.set() is deprecated. Access using array indexes instead.')
return this.writeUInt8(v, offset)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new Error('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; i++) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(parsed)) throw new Error('Invalid hex string')
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
var charsWritten = blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
return charsWritten
}
function asciiWrite (buf, string, offset, length) {
var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
return charsWritten
}
function binaryWrite (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
return charsWritten
}
function utf16leWrite (buf, string, offset, length) {
var charsWritten = blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
return charsWritten
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Support both (string, offset, length, encoding)
// and the legacy (string, encoding, offset, length)
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length
length = undefined
}
} else { // legacy
var swap = encoding
encoding = offset
offset = length
length = swap
}
offset = Number(offset) || 0
if (length < 0 || offset < 0 || offset > this.length) {
throw new RangeError('attempt to write outside buffer bounds')
}
var remaining = this.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
encoding = String(encoding || 'utf8').toLowerCase()
var ret
switch (encoding) {
case 'hex':
ret = hexWrite(this, string, offset, length)
break
case 'utf8':
case 'utf-8':
ret = utf8Write(this, string, offset, length)
break
case 'ascii':
ret = asciiWrite(this, string, offset, length)
break
case 'binary':
ret = binaryWrite(this, string, offset, length)
break
case 'base64':
ret = base64Write(this, string, offset, length)
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = utf16leWrite(this, string, offset, length)
break
default:
throw new TypeError('Unknown encoding: ' + encoding)
}
return ret
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
var res = ''
var tmp = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
if (buf[i] <= 0x7F) {
res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
tmp = ''
} else {
tmp += '%' + buf[i].toString(16)
}
}
return res + decodeUtf8Char(tmp)
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function binarySlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; i++) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = Buffer._augment(this.subarray(start, end))
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; i++) {
newBuf[i] = this[i + start]
}
}
if (newBuf.length) newBuf.parent = this.parent || this
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
if (value > max || value < min) throw new RangeError('value is out of bounds')
if (offset + ext > buf.length) throw new RangeError('index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) >>> 0 & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) >>> 0 & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = value
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = value
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = value
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkInt(
this, value, offset, byteLength,
Math.pow(2, 8 * byteLength - 1) - 1,
-Math.pow(2, 8 * byteLength - 1)
)
}
var i = 0
var mul = 1
var sub = value < 0 ? 1 : 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkInt(
this, value, offset, byteLength,
Math.pow(2, 8 * byteLength - 1) - 1,
-Math.pow(2, 8 * byteLength - 1)
)
}
var i = byteLength - 1
var mul = 1
var sub = value < 0 ? 1 : 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = value
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = value
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (value > max || value < min) throw new RangeError('value is out of bounds')
if (offset + ext > buf.length) throw new RangeError('index out of range')
if (offset < 0) throw new RangeError('index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, target_start, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (target_start >= target.length) target_start = target.length
if (!target_start) target_start = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (target_start < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - target_start < end - start) {
end = target.length - target_start + start
}
var len = end - start
if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < len; i++) {
target[i + target_start] = this[i + start]
}
} else {
target._set(this.subarray(start, start + len), target_start)
}
return len
}
// fill(value, start=0, end=buffer.length)
Buffer.prototype.fill = function fill (value, start, end) {
if (!value) value = 0
if (!start) start = 0
if (!end) end = this.length
if (end < start) throw new RangeError('end < start')
// Fill 0 bytes; we're done
if (end === start) return
if (this.length === 0) return
if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
var i
if (typeof value === 'number') {
for (i = start; i < end; i++) {
this[i] = value
}
} else {
var bytes = utf8ToBytes(value.toString())
var len = bytes.length
for (i = start; i < end; i++) {
this[i] = bytes[i % len]
}
}
return this
}
/**
* Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
* Added in Node 0.12. Only available in browsers that support ArrayBuffer.
*/
Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
if (typeof Uint8Array !== 'undefined') {
if (Buffer.TYPED_ARRAY_SUPPORT) {
return (new Buffer(this)).buffer
} else {
var buf = new Uint8Array(this.length)
for (var i = 0, len = buf.length; i < len; i += 1) {
buf[i] = this[i]
}
return buf.buffer
}
} else {
throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
}
}
// HELPER FUNCTIONS
// ================
var BP = Buffer.prototype
/**
* Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
*/
Buffer._augment = function _augment (arr) {
arr.constructor = Buffer
arr._isBuffer = true
// save reference to original Uint8Array set method before overwriting
arr._set = arr.set
// deprecated, will be removed in node 0.13+
arr.get = BP.get
arr.set = BP.set
arr.write = BP.write
arr.toString = BP.toString
arr.toLocaleString = BP.toString
arr.toJSON = BP.toJSON
arr.equals = BP.equals
arr.compare = BP.compare
arr.indexOf = BP.indexOf
arr.copy = BP.copy
arr.slice = BP.slice
arr.readUIntLE = BP.readUIntLE
arr.readUIntBE = BP.readUIntBE
arr.readUInt8 = BP.readUInt8
arr.readUInt16LE = BP.readUInt16LE
arr.readUInt16BE = BP.readUInt16BE
arr.readUInt32LE = BP.readUInt32LE
arr.readUInt32BE = BP.readUInt32BE
arr.readIntLE = BP.readIntLE
arr.readIntBE = BP.readIntBE
arr.readInt8 = BP.readInt8
arr.readInt16LE = BP.readInt16LE
arr.readInt16BE = BP.readInt16BE
arr.readInt32LE = BP.readInt32LE
arr.readInt32BE = BP.readInt32BE
arr.readFloatLE = BP.readFloatLE
arr.readFloatBE = BP.readFloatBE
arr.readDoubleLE = BP.readDoubleLE
arr.readDoubleBE = BP.readDoubleBE
arr.writeUInt8 = BP.writeUInt8
arr.writeUIntLE = BP.writeUIntLE
arr.writeUIntBE = BP.writeUIntBE
arr.writeUInt16LE = BP.writeUInt16LE
arr.writeUInt16BE = BP.writeUInt16BE
arr.writeUInt32LE = BP.writeUInt32LE
arr.writeUInt32BE = BP.writeUInt32BE
arr.writeIntLE = BP.writeIntLE
arr.writeIntBE = BP.writeIntBE
arr.writeInt8 = BP.writeInt8
arr.writeInt16LE = BP.writeInt16LE
arr.writeInt16BE = BP.writeInt16BE
arr.writeInt32LE = BP.writeInt32LE
arr.writeInt32BE = BP.writeInt32BE
arr.writeFloatLE = BP.writeFloatLE
arr.writeFloatBE = BP.writeFloatBE
arr.writeDoubleLE = BP.writeDoubleLE
arr.writeDoubleBE = BP.writeDoubleBE
arr.fill = BP.fill
arr.inspect = BP.inspect
arr.toArrayBuffer = BP.toArrayBuffer
return arr
}
var INVALID_BASE64_RE = /[^+\/0-9A-z\-]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function isArrayish (subject) {
return isArray(subject) || Buffer.isBuffer(subject) ||
subject && typeof subject === 'object' &&
typeof subject.length === 'number'
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
var i = 0
for (; i < length; i++) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (leadSurrogate) {
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
} else {
// valid surrogate pair
codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
leadSurrogate = null
}
} else {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else {
// valid lead
leadSurrogate = codePoint
continue
}
}
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = null
}
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x200000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; i++) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; i++) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
function decodeUtf8Char (str) {
try {
return decodeURIComponent(str)
} catch (err) {
return String.fromCharCode(0xFFFD) // UTF 8 invalid char
}
}
},{"base64-js":4,"ieee754":5,"is-array":6}],4:[function(_dereq_,module,exports){
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
;(function (exports) {
'use strict';
var Arr = (typeof Uint8Array !== 'undefined')
? Uint8Array
: Array
var PLUS = '+'.charCodeAt(0)
var SLASH = '/'.charCodeAt(0)
var NUMBER = '0'.charCodeAt(0)
var LOWER = 'a'.charCodeAt(0)
var UPPER = 'A'.charCodeAt(0)
var PLUS_URL_SAFE = '-'.charCodeAt(0)
var SLASH_URL_SAFE = '_'.charCodeAt(0)
function decode (elt) {
var code = elt.charCodeAt(0)
if (code === PLUS ||
code === PLUS_URL_SAFE)
return 62 // '+'
if (code === SLASH ||
code === SLASH_URL_SAFE)
return 63 // '/'
if (code < NUMBER)
return -1 //no match
if (code < NUMBER + 10)
return code - NUMBER + 26 + 26
if (code < UPPER + 26)
return code - UPPER
if (code < LOWER + 26)
return code - LOWER + 26
}
function b64ToByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
if (b64.length % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
var len = b64.length
placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
// base64 is 4/3 + up to two characters of the original data
arr = new Arr(b64.length * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? b64.length - 4 : b64.length
var L = 0
function push (v) {
arr[L++] = v
}
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
push((tmp & 0xFF0000) >> 16)
push((tmp & 0xFF00) >> 8)
push(tmp & 0xFF)
}
if (placeHolders === 2) {
tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
push(tmp & 0xFF)
} else if (placeHolders === 1) {
tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
push((tmp >> 8) & 0xFF)
push(tmp & 0xFF)
}
return arr
}
function uint8ToBase64 (uint8) {
var i,
extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
output = "",
temp, length
function encode (num) {
return lookup.charAt(num)
}
function tripletToBase64 (num) {
return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
}
// go through the array every three bytes, we'll deal with trailing stuff later
for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output += tripletToBase64(temp)
}
// pad the end with zeros, but make sure to not forget the extra bytes
switch (extraBytes) {
case 1:
temp = uint8[uint8.length - 1]
output += encode(temp >> 2)
output += encode((temp << 4) & 0x3F)
output += '=='
break
case 2:
temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
output += encode(temp >> 10)
output += encode((temp >> 4) & 0x3F)
output += encode((temp << 2) & 0x3F)
output += '='
break
}
return output
}
exports.toByteArray = b64ToByteArray
exports.fromByteArray = uint8ToBase64
}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
},{}],5:[function(_dereq_,module,exports){
exports.read = function(buffer, offset, isLE, mLen, nBytes) {
var e, m,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
nBits = -7,
i = isLE ? (nBytes - 1) : 0,
d = isLE ? -1 : 1,
s = buffer[offset + i];
i += d;
e = s & ((1 << (-nBits)) - 1);
s >>= (-nBits);
nBits += eLen;
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
m = e & ((1 << (-nBits)) - 1);
e >>= (-nBits);
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity);
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};
exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
i = isLE ? 0 : (nBytes - 1),
d = isLE ? 1 : -1,
s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
value = Math.abs(value);
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value) / Math.LN2);
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * Math.pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
e = (e << mLen) | m;
eLen += mLen;
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
buffer[offset + i - d] |= s * 128;
};
},{}],6:[function(_dereq_,module,exports){
/**
* isArray
*/
var isArray = Array.isArray;
/**
* toString
*/
var str = Object.prototype.toString;
/**
* Whether or not the given `val`
* is an array.
*
* example:
*
* isArray([]);
* // > true
* isArray(arguments);
* // > false
* isArray('');
* // > false
*
* @param {mixed} val
* @return {bool}
*/
module.exports = isArray || function (val) {
return !! val && '[object Array]' == str.call(val);
};
},{}],7:[function(_dereq_,module,exports){
(function (process){
// 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.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
return splitPathRe.exec(filename).slice(1);
};
// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
return !!p;
}), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(filter(path.split('/'), function(p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function(path) {
return path.charAt(0) === '/';
};
// posix version
exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(filter(paths, function(p, index) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
};
// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function(path) {
var result = splitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
exports.basename = function(path, ext) {
var f = splitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function(path) {
return splitPath(path)[3];
};
function filter (xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b'
? function (str, start, len) { return str.substr(start, len) }
: function (str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
}
;
}).call(this,_dereq_('_process'))
},{"_process":8}],8:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
function drainQueue() {
if (draining) {
return;
}
draining = true;
var currentQueue;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
var i = -1;
while (++i < len) {
currentQueue[i]();
}
len = queue.length;
}
draining = false;
}
process.nextTick = function (fun) {
queue.push(fun);
if (!draining) {
setTimeout(drainQueue, 0);
}
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],9:[function(_dereq_,module,exports){
/*
Copyright (C) 2013 Ariya Hidayat <[email protected]>
Copyright (C) 2013 Thaddee Tyl <[email protected]>
Copyright (C) 2012 Ariya Hidayat <[email protected]>
Copyright (C) 2012 Mathias Bynens <[email protected]>
Copyright (C) 2012 Joost-Wim Boekesteijn <[email protected]>
Copyright (C) 2012 Kris Kowal <[email protected]>
Copyright (C) 2012 Yusuke Suzuki <[email protected]>
Copyright (C) 2012 Arpad Borsos <[email protected]>
Copyright (C) 2011 Ariya Hidayat <[email protected]>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function (root, factory) {
'use strict';
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
// Rhino, and plain browser loading.
/* istanbul ignore next */
if (typeof define === 'function' && define.amd) {
define(['exports'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports);
} else {
factory((root.esprima = {}));
}
}(this, function (exports) {
'use strict';
var Token,
TokenName,
FnExprTokens,
Syntax,
PropertyKind,
Messages,
Regex,
SyntaxTreeDelegate,
XHTMLEntities,
ClassPropertyType,
source,
strict,
index,
lineNumber,
lineStart,
length,
delegate,
lookahead,
state,
extra;
Token = {
BooleanLiteral: 1,
EOF: 2,
Identifier: 3,
Keyword: 4,
NullLiteral: 5,
NumericLiteral: 6,
Punctuator: 7,
StringLiteral: 8,
RegularExpression: 9,
Template: 10,
JSXIdentifier: 11,
JSXText: 12
};
TokenName = {};
TokenName[Token.BooleanLiteral] = 'Boolean';
TokenName[Token.EOF] = '<end>';
TokenName[Token.Identifier] = 'Identifier';
TokenName[Token.Keyword] = 'Keyword';
TokenName[Token.NullLiteral] = 'Null';
TokenName[Token.NumericLiteral] = 'Numeric';
TokenName[Token.Punctuator] = 'Punctuator';
TokenName[Token.StringLiteral] = 'String';
TokenName[Token.JSXIdentifier] = 'JSXIdentifier';
TokenName[Token.JSXText] = 'JSXText';
TokenName[Token.RegularExpression] = 'RegularExpression';
// A function following one of those tokens is an expression.
FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
'return', 'case', 'delete', 'throw', 'void',
// assignment operators
'=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
'&=', '|=', '^=', ',',
// binary/unary operators
'+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
'|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
'<=', '<', '>', '!=', '!=='];
Syntax = {
AnyTypeAnnotation: 'AnyTypeAnnotation',
ArrayExpression: 'ArrayExpression',
ArrayPattern: 'ArrayPattern',
ArrayTypeAnnotation: 'ArrayTypeAnnotation',
ArrowFunctionExpression: 'ArrowFunctionExpression',
AssignmentExpression: 'AssignmentExpression',
BinaryExpression: 'BinaryExpression',
BlockStatement: 'BlockStatement',
BooleanTypeAnnotation: 'BooleanTypeAnnotation',
BreakStatement: 'BreakStatement',
CallExpression: 'CallExpression',
CatchClause: 'CatchClause',
ClassBody: 'ClassBody',
ClassDeclaration: 'ClassDeclaration',
ClassExpression: 'ClassExpression',
ClassImplements: 'ClassImplements',
ClassProperty: 'ClassProperty',
ComprehensionBlock: 'ComprehensionBlock',
ComprehensionExpression: 'ComprehensionExpression',
ConditionalExpression: 'ConditionalExpression',
ContinueStatement: 'ContinueStatement',
DebuggerStatement: 'DebuggerStatement',
DeclareClass: 'DeclareClass',
DeclareFunction: 'DeclareFunction',
DeclareModule: 'DeclareModule',
DeclareVariable: 'DeclareVariable',
DoWhileStatement: 'DoWhileStatement',
EmptyStatement: 'EmptyStatement',
ExportDeclaration: 'ExportDeclaration',
ExportBatchSpecifier: 'ExportBatchSpecifier',
ExportSpecifier: 'ExportSpecifier',
ExpressionStatement: 'ExpressionStatement',
ForInStatement: 'ForInStatement',
ForOfStatement: 'ForOfStatement',
ForStatement: 'ForStatement',
FunctionDeclaration: 'FunctionDeclaration',
FunctionExpression: 'FunctionExpression',
FunctionTypeAnnotation: 'FunctionTypeAnnotation',
FunctionTypeParam: 'FunctionTypeParam',
GenericTypeAnnotation: 'GenericTypeAnnotation',
Identifier: 'Identifier',
IfStatement: 'IfStatement',
ImportDeclaration: 'ImportDeclaration',
ImportDefaultSpecifier: 'ImportDefaultSpecifier',
ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
ImportSpecifier: 'ImportSpecifier',
InterfaceDeclaration: 'InterfaceDeclaration',
InterfaceExtends: 'InterfaceExtends',
IntersectionTypeAnnotation: 'IntersectionTypeAnnotation',
LabeledStatement: 'LabeledStatement',
Literal: 'Literal',
LogicalExpression: 'LogicalExpression',
MemberExpression: 'MemberExpression',
MethodDefinition: 'MethodDefinition',
ModuleSpecifier: 'ModuleSpecifier',
NewExpression: 'NewExpression',
NullableTypeAnnotation: 'NullableTypeAnnotation',
NumberTypeAnnotation: 'NumberTypeAnnotation',
ObjectExpression: 'ObjectExpression',
ObjectPattern: 'ObjectPattern',
ObjectTypeAnnotation: 'ObjectTypeAnnotation',
ObjectTypeCallProperty: 'ObjectTypeCallProperty',
ObjectTypeIndexer: 'ObjectTypeIndexer',
ObjectTypeProperty: 'ObjectTypeProperty',
Program: 'Program',
Property: 'Property',
QualifiedTypeIdentifier: 'QualifiedTypeIdentifier',
ReturnStatement: 'ReturnStatement',
SequenceExpression: 'SequenceExpression',
SpreadElement: 'SpreadElement',
SpreadProperty: 'SpreadProperty',
StringLiteralTypeAnnotation: 'StringLiteralTypeAnnotation',
StringTypeAnnotation: 'StringTypeAnnotation',
SwitchCase: 'SwitchCase',
SwitchStatement: 'SwitchStatement',
TaggedTemplateExpression: 'TaggedTemplateExpression',
TemplateElement: 'TemplateElement',
TemplateLiteral: 'TemplateLiteral',
ThisExpression: 'ThisExpression',
ThrowStatement: 'ThrowStatement',
TupleTypeAnnotation: 'TupleTypeAnnotation',
TryStatement: 'TryStatement',
TypeAlias: 'TypeAlias',
TypeAnnotation: 'TypeAnnotation',
TypeCastExpression: 'TypeCastExpression',
TypeofTypeAnnotation: 'TypeofTypeAnnotation',
TypeParameterDeclaration: 'TypeParameterDeclaration',
TypeParameterInstantiation: 'TypeParameterInstantiation',
UnaryExpression: 'UnaryExpression',
UnionTypeAnnotation: 'UnionTypeAnnotation',
UpdateExpression: 'UpdateExpression',
VariableDeclaration: 'VariableDeclaration',
VariableDeclarator: 'VariableDeclarator',
VoidTypeAnnotation: 'VoidTypeAnnotation',
WhileStatement: 'WhileStatement',
WithStatement: 'WithStatement',
JSXIdentifier: 'JSXIdentifier',
JSXNamespacedName: 'JSXNamespacedName',
JSXMemberExpression: 'JSXMemberExpression',
JSXEmptyExpression: 'JSXEmptyExpression',
JSXExpressionContainer: 'JSXExpressionContainer',
JSXElement: 'JSXElement',
JSXClosingElement: 'JSXClosingElement',
JSXOpeningElement: 'JSXOpeningElement',
JSXAttribute: 'JSXAttribute',
JSXSpreadAttribute: 'JSXSpreadAttribute',
JSXText: 'JSXText',
YieldExpression: 'YieldExpression',
AwaitExpression: 'AwaitExpression'
};
PropertyKind = {
Data: 1,
Get: 2,
Set: 4
};
ClassPropertyType = {
'static': 'static',
prototype: 'prototype'
};
// Error messages should be identical to V8.
Messages = {
UnexpectedToken: 'Unexpected token %0',
UnexpectedNumber: 'Unexpected number',
UnexpectedString: 'Unexpected string',
UnexpectedIdentifier: 'Unexpected identifier',
UnexpectedReserved: 'Unexpected reserved word',
UnexpectedTemplate: 'Unexpected quasi %0',
UnexpectedEOS: 'Unexpected end of input',
NewlineAfterThrow: 'Illegal newline after throw',
InvalidRegExp: 'Invalid regular expression',
UnterminatedRegExp: 'Invalid regular expression: missing /',
InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
InvalidLHSInFormalsList: 'Invalid left-hand side in formals list',
InvalidLHSInForIn: 'Invalid left-hand side in for-in',
MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
NoCatchOrFinally: 'Missing catch or finally after try',
UnknownLabel: 'Undefined label \'%0\'',
Redeclaration: '%0 \'%1\' has already been declared',
IllegalContinue: 'Illegal continue statement',
IllegalBreak: 'Illegal break statement',
IllegalDuplicateClassProperty: 'Illegal duplicate property in class definition',
IllegalClassConstructorProperty: 'Illegal constructor property in class definition',
IllegalReturn: 'Illegal return statement',
IllegalSpread: 'Illegal spread element',
StrictModeWith: 'Strict mode code may not include a with statement',
StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
StrictVarName: 'Variable name may not be eval or arguments in strict mode',
StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
ParameterAfterRestParameter: 'Rest parameter must be final parameter of an argument list',
DefaultRestParameter: 'Rest parameter can not have a default value',
ElementAfterSpreadElement: 'Spread must be the final element of an element list',
PropertyAfterSpreadProperty: 'A rest property must be the final property of an object literal',
ObjectPatternAsRestParameter: 'Invalid rest parameter',
ObjectPatternAsSpread: 'Invalid spread argument',
StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
StrictDelete: 'Delete of an unqualified identifier in strict mode.',
StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode',
AccessorDataProperty: 'Object literal may not have data and accessor property with the same name',
AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name',
StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
StrictReservedWord: 'Use of future reserved word in strict mode',
MissingFromClause: 'Missing from clause',
NoAsAfterImportNamespace: 'Missing as after import *',
InvalidModuleSpecifier: 'Invalid module specifier',
IllegalImportDeclaration: 'Illegal import declaration',
IllegalExportDeclaration: 'Illegal export declaration',
NoUninitializedConst: 'Const must be initialized',
ComprehensionRequiresBlock: 'Comprehension must have at least one block',
ComprehensionError: 'Comprehension Error',
EachNotAllowed: 'Each is not supported',
InvalidJSXAttributeValue: 'JSX value should be either an expression or a quoted JSX text',
ExpectedJSXClosingTag: 'Expected corresponding JSX closing tag for %0',
AdjacentJSXElements: 'Adjacent JSX elements must be wrapped in an enclosing tag',
ConfusedAboutFunctionType: 'Unexpected token =>. It looks like ' +
'you are trying to write a function type, but you ended up ' +
'writing a grouped type followed by an =>, which is a syntax ' +
'error. Remember, function type parameters are named so function ' +
'types look like (name1: type1, name2: type2) => returnType. You ' +
'probably wrote (type1) => returnType'
};
// See also tools/generate-unicode-regex.py.
Regex = {
NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'),
NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'),
LeadingZeros: new RegExp('^0+(?!$)')
};
// Ensure the condition is true, otherwise throw an error.
// This is only to have a better contract semantic, i.e. another safety net
// to catch a logic error. The condition shall be fulfilled in normal case.
// Do NOT use this to enforce a certain condition on any user input.
function assert(condition, message) {
/* istanbul ignore if */
if (!condition) {
throw new Error('ASSERT: ' + message);
}
}
function StringMap() {
this.$data = {};
}
StringMap.prototype.get = function (key) {
key = '$' + key;
return this.$data[key];
};
StringMap.prototype.set = function (key, value) {
key = '$' + key;
this.$data[key] = value;
return this;
};
StringMap.prototype.has = function (key) {
key = '$' + key;
return Object.prototype.hasOwnProperty.call(this.$data, key);
};
StringMap.prototype["delete"] = function (key) {
key = '$' + key;
return delete this.$data[key];
};
function isDecimalDigit(ch) {
return (ch >= 48 && ch <= 57); // 0..9
}
function isHexDigit(ch) {
return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
}
function isOctalDigit(ch) {
return '01234567'.indexOf(ch) >= 0;
}
// 7.2 White Space
function isWhiteSpace(ch) {
return (ch === 32) || // space
(ch === 9) || // tab
(ch === 0xB) ||
(ch === 0xC) ||
(ch === 0xA0) ||
(ch >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(String.fromCharCode(ch)) > 0);
}
// 7.3 Line Terminators
function isLineTerminator(ch) {
return (ch === 10) || (ch === 13) || (ch === 0x2028) || (ch === 0x2029);
}
// 7.6 Identifier Names and Identifiers
function isIdentifierStart(ch) {
return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore)
(ch >= 65 && ch <= 90) || // A..Z
(ch >= 97 && ch <= 122) || // a..z
(ch === 92) || // \ (backslash)
((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch)));
}
function isIdentifierPart(ch) {
return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore)
(ch >= 65 && ch <= 90) || // A..Z
(ch >= 97 && ch <= 122) || // a..z
(ch >= 48 && ch <= 57) || // 0..9
(ch === 92) || // \ (backslash)
((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch)));
}
// 7.6.1.2 Future Reserved Words
function isFutureReservedWord(id) {
switch (id) {
case 'class':
case 'enum':
case 'export':
case 'extends':
case 'import':
case 'super':
return true;
default:
return false;
}
}
function isStrictModeReservedWord(id) {
switch (id) {
case 'implements':
case 'interface':
case 'package':
case 'private':
case 'protected':
case 'public':
case 'static':
case 'yield':
case 'let':
return true;
default:
return false;
}
}
function isRestrictedWord(id) {
return id === 'eval' || id === 'arguments';
}
// 7.6.1.1 Keywords
function isKeyword(id) {
if (strict && isStrictModeReservedWord(id)) {
return true;
}
// 'const' is specialized as Keyword in V8.
// 'yield' is only treated as a keyword in strict mode.
// 'let' is for compatiblity with SpiderMonkey and ES.next.
// Some others are from future reserved words.
switch (id.length) {
case 2:
return (id === 'if') || (id === 'in') || (id === 'do');
case 3:
return (id === 'var') || (id === 'for') || (id === 'new') ||
(id === 'try') || (id === 'let');
case 4:
return (id === 'this') || (id === 'else') || (id === 'case') ||
(id === 'void') || (id === 'with') || (id === 'enum');
case 5:
return (id === 'while') || (id === 'break') || (id === 'catch') ||
(id === 'throw') || (id === 'const') ||
(id === 'class') || (id === 'super');
case 6:
return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
(id === 'switch') || (id === 'export') || (id === 'import');
case 7:
return (id === 'default') || (id === 'finally') || (id === 'extends');
case 8:
return (id === 'function') || (id === 'continue') || (id === 'debugger');
case 10:
return (id === 'instanceof');
default:
return false;
}
}
// 7.4 Comments
function addComment(type, value, start, end, loc) {
var comment;
assert(typeof start === 'number', 'Comment must have valid position');
// Because the way the actual token is scanned, often the comments
// (if any) are skipped twice during the lexical analysis.
// Thus, we need to skip adding a comment if the comment array already
// handled it.
if (state.lastCommentStart >= start) {
return;
}
state.lastCommentStart = start;
comment = {
type: type,
value: value
};
if (extra.range) {
comment.range = [start, end];
}
if (extra.loc) {
comment.loc = loc;
}
extra.comments.push(comment);
if (extra.attachComment) {
extra.leadingComments.push(comment);
extra.trailingComments.push(comment);
}
}
function skipSingleLineComment() {
var start, loc, ch, comment;
start = index - 2;
loc = {
start: {
line: lineNumber,
column: index - lineStart - 2
}
};
while (index < length) {
ch = source.charCodeAt(index);
++index;
if (isLineTerminator(ch)) {
if (extra.comments) {
comment = source.slice(start + 2, index - 1);
loc.end = {
line: lineNumber,
column: index - lineStart - 1
};
addComment('Line', comment, start, index - 1, loc);
}
if (ch === 13 && source.charCodeAt(index) === 10) {
++index;
}
++lineNumber;
lineStart = index;
return;
}
}
if (extra.comments) {
comment = source.slice(start + 2, index);
loc.end = {
line: lineNumber,
column: index - lineStart
};
addComment('Line', comment, start, index, loc);
}
}
function skipMultiLineComment() {
var start, loc, ch, comment;
if (extra.comments) {
start = index - 2;
loc = {
start: {
line: lineNumber,
column: index - lineStart - 2
}
};
}
while (index < length) {
ch = source.charCodeAt(index);
if (isLineTerminator(ch)) {
if (ch === 13 && source.charCodeAt(index + 1) === 10) {
++index;
}
++lineNumber;
++index;
lineStart = index;
if (index >= length) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
} else if (ch === 42) {
// Block comment ends with '*/' (char #42, char #47).
if (source.charCodeAt(index + 1) === 47) {
++index;
++index;
if (extra.comments) {
comment = source.slice(start + 2, index - 2);
loc.end = {
line: lineNumber,
column: index - lineStart
};
addComment('Block', comment, start, index, loc);
}
return;
}
++index;
} else {
++index;
}
}
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
function skipComment() {
var ch;
while (index < length) {
ch = source.charCodeAt(index);
if (isWhiteSpace(ch)) {
++index;
} else if (isLineTerminator(ch)) {
++index;
if (ch === 13 && source.charCodeAt(index) === 10) {
++index;
}
++lineNumber;
lineStart = index;
} else if (ch === 47) { // 47 is '/'
ch = source.charCodeAt(index + 1);
if (ch === 47) {
++index;
++index;
skipSingleLineComment();
} else if (ch === 42) { // 42 is '*'
++index;
++index;
skipMultiLineComment();
} else {
break;
}
} else {
break;
}
}
}
function scanHexEscape(prefix) {
var i, len, ch, code = 0;
len = (prefix === 'u') ? 4 : 2;
for (i = 0; i < len; ++i) {
if (index < length && isHexDigit(source[index])) {
ch = source[index++];
code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
} else {
return '';
}
}
return String.fromCharCode(code);
}
function scanUnicodeCodePointEscape() {
var ch, code, cu1, cu2;
ch = source[index];
code = 0;
// At least, one hex digit is required.
if (ch === '}') {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
while (index < length) {
ch = source[index++];
if (!isHexDigit(ch)) {
break;
}
code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
}
if (code > 0x10FFFF || ch !== '}') {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
// UTF-16 Encoding
if (code <= 0xFFFF) {
return String.fromCharCode(code);
}
cu1 = ((code - 0x10000) >> 10) + 0xD800;
cu2 = ((code - 0x10000) & 1023) + 0xDC00;
return String.fromCharCode(cu1, cu2);
}
function getEscapedIdentifier() {
var ch, id;
ch = source.charCodeAt(index++);
id = String.fromCharCode(ch);
// '\u' (char #92, char #117) denotes an escaped character.
if (ch === 92) {
if (source.charCodeAt(index) !== 117) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
++index;
ch = scanHexEscape('u');
if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
id = ch;
}
while (index < length) {
ch = source.charCodeAt(index);
if (!isIdentifierPart(ch)) {
break;
}
++index;
id += String.fromCharCode(ch);
// '\u' (char #92, char #117) denotes an escaped character.
if (ch === 92) {
id = id.substr(0, id.length - 1);
if (source.charCodeAt(index) !== 117) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
++index;
ch = scanHexEscape('u');
if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
id += ch;
}
}
return id;
}
function getIdentifier() {
var start, ch;
start = index++;
while (index < length) {
ch = source.charCodeAt(index);
if (ch === 92) {
// Blackslash (char #92) marks Unicode escape sequence.
index = start;
return getEscapedIdentifier();
}
if (isIdentifierPart(ch)) {
++index;
} else {
break;
}
}
return source.slice(start, index);
}
function scanIdentifier() {
var start, id, type;
start = index;
// Backslash (char #92) starts an escaped character.
id = (source.charCodeAt(index) === 92) ? getEscapedIdentifier() : getIdentifier();
// There is no keyword or literal with only one character.
// Thus, it must be an identifier.
if (id.length === 1) {
type = Token.Identifier;
} else if (isKeyword(id)) {
type = Token.Keyword;
} else if (id === 'null') {
type = Token.NullLiteral;
} else if (id === 'true' || id === 'false') {
type = Token.BooleanLiteral;
} else {
type = Token.Identifier;
}
return {
type: type,
value: id,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
// 7.7 Punctuators
function scanPunctuator() {
var start = index,
code = source.charCodeAt(index),
code2,
ch1 = source[index],
ch2,
ch3,
ch4;
if (state.inJSXTag || state.inJSXChild) {
// Don't need to check for '{' and '}' as it's already handled
// correctly by default.
switch (code) {
case 60: // <
case 62: // >
++index;
return {
type: Token.Punctuator,
value: String.fromCharCode(code),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
}
switch (code) {
// Check for most common single-character punctuators.
case 40: // ( open bracket
case 41: // ) close bracket
case 59: // ; semicolon
case 44: // , comma
case 123: // { open curly brace
case 125: // } close curly brace
case 91: // [
case 93: // ]
case 58: // :
case 63: // ?
case 126: // ~
++index;
if (extra.tokenize) {
if (code === 40) {
extra.openParenToken = extra.tokens.length;
} else if (code === 123) {
extra.openCurlyToken = extra.tokens.length;
}
}
return {
type: Token.Punctuator,
value: String.fromCharCode(code),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
default:
code2 = source.charCodeAt(index + 1);
// '=' (char #61) marks an assignment or comparison operator.
if (code2 === 61) {
switch (code) {
case 37: // %
case 38: // &
case 42: // *:
case 43: // +
case 45: // -
case 47: // /
case 60: // <
case 62: // >
case 94: // ^
case 124: // |
index += 2;
return {
type: Token.Punctuator,
value: String.fromCharCode(code) + String.fromCharCode(code2),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
case 33: // !
case 61: // =
index += 2;
// !== and ===
if (source.charCodeAt(index) === 61) {
++index;
}
return {
type: Token.Punctuator,
value: source.slice(start, index),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
default:
break;
}
}
break;
}
// Peek more characters.
ch2 = source[index + 1];
ch3 = source[index + 2];
ch4 = source[index + 3];
// 4-character punctuator: >>>=
if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
if (ch4 === '=') {
index += 4;
return {
type: Token.Punctuator,
value: '>>>=',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
}
// 3-character punctuators: === !== >>> <<= >>=
if (ch1 === '>' && ch2 === '>' && ch3 === '>' && !state.inType) {
index += 3;
return {
type: Token.Punctuator,
value: '>>>',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '<' && ch2 === '<' && ch3 === '=') {
index += 3;
return {
type: Token.Punctuator,
value: '<<=',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '>' && ch2 === '>' && ch3 === '=') {
index += 3;
return {
type: Token.Punctuator,
value: '>>=',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '.' && ch2 === '.' && ch3 === '.') {
index += 3;
return {
type: Token.Punctuator,
value: '...',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
// Other 2-character punctuators: ++ -- << >> && ||
// Don't match these tokens if we're in a type, since they never can
// occur and can mess up types like Map<string, Array<string>>
if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0) && !state.inType) {
index += 2;
return {
type: Token.Punctuator,
value: ch1 + ch2,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '=' && ch2 === '>') {
index += 2;
return {
type: Token.Punctuator,
value: '=>',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
++index;
return {
type: Token.Punctuator,
value: ch1,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '.') {
++index;
return {
type: Token.Punctuator,
value: ch1,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
// 7.8.3 Numeric Literals
function scanHexLiteral(start) {
var number = '';
while (index < length) {
if (!isHexDigit(source[index])) {
break;
}
number += source[index++];
}
if (number.length === 0) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
if (isIdentifierStart(source.charCodeAt(index))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.NumericLiteral,
value: parseInt('0x' + number, 16),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanBinaryLiteral(start) {
var ch, number;
number = '';
while (index < length) {
ch = source[index];
if (ch !== '0' && ch !== '1') {
break;
}
number += source[index++];
}
if (number.length === 0) {
// only 0b or 0B
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
if (index < length) {
ch = source.charCodeAt(index);
/* istanbul ignore else */
if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
return {
type: Token.NumericLiteral,
value: parseInt(number, 2),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanOctalLiteral(prefix, start) {
var number, octal;
if (isOctalDigit(prefix)) {
octal = true;
number = '0' + source[index++];
} else {
octal = false;
++index;
number = '';
}
while (index < length) {
if (!isOctalDigit(source[index])) {
break;
}
number += source[index++];
}
if (!octal && number.length === 0) {
// only 0o or 0O
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.NumericLiteral,
value: parseInt(number, 8),
octal: octal,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanNumericLiteral() {
var number, start, ch;
ch = source[index];
assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
'Numeric literal must start with a decimal digit or a decimal point');
start = index;
number = '';
if (ch !== '.') {
number = source[index++];
ch = source[index];
// Hex number starts with '0x'.
// Octal number starts with '0'.
// Octal number in ES6 starts with '0o'.
// Binary number in ES6 starts with '0b'.
if (number === '0') {
if (ch === 'x' || ch === 'X') {
++index;
return scanHexLiteral(start);
}
if (ch === 'b' || ch === 'B') {
++index;
return scanBinaryLiteral(start);
}
if (ch === 'o' || ch === 'O' || isOctalDigit(ch)) {
return scanOctalLiteral(ch, start);
}
// decimal number starts with '0' such as '09' is illegal.
if (ch && isDecimalDigit(ch.charCodeAt(0))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
while (isDecimalDigit(source.charCodeAt(index))) {
number += source[index++];
}
ch = source[index];
}
if (ch === '.') {
number += source[index++];
while (isDecimalDigit(source.charCodeAt(index))) {
number += source[index++];
}
ch = source[index];
}
if (ch === 'e' || ch === 'E') {
number += source[index++];
ch = source[index];
if (ch === '+' || ch === '-') {
number += source[index++];
}
if (isDecimalDigit(source.charCodeAt(index))) {
while (isDecimalDigit(source.charCodeAt(index))) {
number += source[index++];
}
} else {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
if (isIdentifierStart(source.charCodeAt(index))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.NumericLiteral,
value: parseFloat(number),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
// 7.8.4 String Literals
function scanStringLiteral() {
var str = '', quote, start, ch, code, unescaped, restore, octal = false;
quote = source[index];
assert((quote === '\'' || quote === '"'),
'String literal must starts with a quote');
start = index;
++index;
while (index < length) {
ch = source[index++];
if (ch === quote) {
quote = '';
break;
} else if (ch === '\\') {
ch = source[index++];
if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
switch (ch) {
case 'n':
str += '\n';
break;
case 'r':
str += '\r';
break;
case 't':
str += '\t';
break;
case 'u':
case 'x':
if (source[index] === '{') {
++index;
str += scanUnicodeCodePointEscape();
} else {
restore = index;
unescaped = scanHexEscape(ch);
if (unescaped) {
str += unescaped;
} else {
index = restore;
str += ch;
}
}
break;
case 'b':
str += '\b';
break;
case 'f':
str += '\f';
break;
case 'v':
str += '\x0B';
break;
default:
if (isOctalDigit(ch)) {
code = '01234567'.indexOf(ch);
// \0 is not octal escape sequence
if (code !== 0) {
octal = true;
}
/* istanbul ignore else */
if (index < length && isOctalDigit(source[index])) {
octal = true;
code = code * 8 + '01234567'.indexOf(source[index++]);
// 3 digits are only allowed when string starts
// with 0, 1, 2, 3
if ('0123'.indexOf(ch) >= 0 &&
index < length &&
isOctalDigit(source[index])) {
code = code * 8 + '01234567'.indexOf(source[index++]);
}
}
str += String.fromCharCode(code);
} else {
str += ch;
}
break;
}
} else {
++lineNumber;
if (ch === '\r' && source[index] === '\n') {
++index;
}
lineStart = index;
}
} else if (isLineTerminator(ch.charCodeAt(0))) {
break;
} else {
str += ch;
}
}
if (quote !== '') {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.StringLiteral,
value: str,
octal: octal,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanTemplate() {
var cooked = '', ch, start, terminated, tail, restore, unescaped, code, octal;
terminated = false;
tail = false;
start = index;
++index;
while (index < length) {
ch = source[index++];
if (ch === '`') {
tail = true;
terminated = true;
break;
} else if (ch === '$') {
if (source[index] === '{') {
++index;
terminated = true;
break;
}
cooked += ch;
} else if (ch === '\\') {
ch = source[index++];
if (!isLineTerminator(ch.charCodeAt(0))) {
switch (ch) {
case 'n':
cooked += '\n';
break;
case 'r':
cooked += '\r';
break;
case 't':
cooked += '\t';
break;
case 'u':
case 'x':
if (source[index] === '{') {
++index;
cooked += scanUnicodeCodePointEscape();
} else {
restore = index;
unescaped = scanHexEscape(ch);
if (unescaped) {
cooked += unescaped;
} else {
index = restore;
cooked += ch;
}
}
break;
case 'b':
cooked += '\b';
break;
case 'f':
cooked += '\f';
break;
case 'v':
cooked += '\v';
break;
default:
if (isOctalDigit(ch)) {
code = '01234567'.indexOf(ch);
// \0 is not octal escape sequence
if (code !== 0) {
octal = true;
}
/* istanbul ignore else */
if (index < length && isOctalDigit(source[index])) {
octal = true;
code = code * 8 + '01234567'.indexOf(source[index++]);
// 3 digits are only allowed when string starts
// with 0, 1, 2, 3
if ('0123'.indexOf(ch) >= 0 &&
index < length &&
isOctalDigit(source[index])) {
code = code * 8 + '01234567'.indexOf(source[index++]);
}
}
cooked += String.fromCharCode(code);
} else {
cooked += ch;
}
break;
}
} else {
++lineNumber;
if (ch === '\r' && source[index] === '\n') {
++index;
}
lineStart = index;
}
} else if (isLineTerminator(ch.charCodeAt(0))) {
++lineNumber;
if (ch === '\r' && source[index] === '\n') {
++index;
}
lineStart = index;
cooked += '\n';
} else {
cooked += ch;
}
}
if (!terminated) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.Template,
value: {
cooked: cooked,
raw: source.slice(start + 1, index - ((tail) ? 1 : 2))
},
tail: tail,
octal: octal,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanTemplateElement(option) {
var startsWith, template;
lookahead = null;
skipComment();
startsWith = (option.head) ? '`' : '}';
if (source[index] !== startsWith) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
template = scanTemplate();
peek();
return template;
}
function testRegExp(pattern, flags) {
var tmp = pattern,
value;
if (flags.indexOf('u') >= 0) {
// Replace each astral symbol and every Unicode code point
// escape sequence with a single ASCII symbol to avoid throwing on
// regular expressions that are only valid in combination with the
// `/u` flag.
// Note: replacing with the ASCII symbol `x` might cause false
// negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
// perfectly valid pattern that is equivalent to `[a-b]`, but it
// would be replaced by `[x-b]` which throws an error.
tmp = tmp
.replace(/\\u\{([0-9a-fA-F]+)\}/g, function ($0, $1) {
if (parseInt($1, 16) <= 0x10FFFF) {
return 'x';
}
throwError({}, Messages.InvalidRegExp);
})
.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x');
}
// First, detect invalid regular expressions.
try {
value = new RegExp(tmp);
} catch (e) {
throwError({}, Messages.InvalidRegExp);
}
// Return a regular expression object for this pattern-flag pair, or
// `null` in case the current environment doesn't support the flags it
// uses.
try {
return new RegExp(pattern, flags);
} catch (exception) {
return null;
}
}
function scanRegExpBody() {
var ch, str, classMarker, terminated, body;
ch = source[index];
assert(ch === '/', 'Regular expression literal must start with a slash');
str = source[index++];
classMarker = false;
terminated = false;
while (index < length) {
ch = source[index++];
str += ch;
if (ch === '\\') {
ch = source[index++];
// ECMA-262 7.8.5
if (isLineTerminator(ch.charCodeAt(0))) {
throwError({}, Messages.UnterminatedRegExp);
}
str += ch;
} else if (isLineTerminator(ch.charCodeAt(0))) {
throwError({}, Messages.UnterminatedRegExp);
} else if (classMarker) {
if (ch === ']') {
classMarker = false;
}
} else {
if (ch === '/') {
terminated = true;
break;
} else if (ch === '[') {
classMarker = true;
}
}
}
if (!terminated) {
throwError({}, Messages.UnterminatedRegExp);
}
// Exclude leading and trailing slash.
body = str.substr(1, str.length - 2);
return {
value: body,
literal: str
};
}
function scanRegExpFlags() {
var ch, str, flags, restore;
str = '';
flags = '';
while (index < length) {
ch = source[index];
if (!isIdentifierPart(ch.charCodeAt(0))) {
break;
}
++index;
if (ch === '\\' && index < length) {
ch = source[index];
if (ch === 'u') {
++index;
restore = index;
ch = scanHexEscape('u');
if (ch) {
flags += ch;
for (str += '\\u'; restore < index; ++restore) {
str += source[restore];
}
} else {
index = restore;
flags += 'u';
str += '\\u';
}
throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL');
} else {
str += '\\';
throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL');
}
} else {
flags += ch;
str += ch;
}
}
return {
value: flags,
literal: str
};
}
function scanRegExp() {
var start, body, flags, value;
lookahead = null;
skipComment();
start = index;
body = scanRegExpBody();
flags = scanRegExpFlags();
value = testRegExp(body.value, flags.value);
if (extra.tokenize) {
return {
type: Token.RegularExpression,
value: value,
regex: {
pattern: body.value,
flags: flags.value
},
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
return {
literal: body.literal + flags.literal,
value: value,
regex: {
pattern: body.value,
flags: flags.value
},
range: [start, index]
};
}
function isIdentifierName(token) {
return token.type === Token.Identifier ||
token.type === Token.Keyword ||
token.type === Token.BooleanLiteral ||
token.type === Token.NullLiteral;
}
function advanceSlash() {
var prevToken,
checkToken;
// Using the following algorithm:
// https://github.com/mozilla/sweet.js/wiki/design
prevToken = extra.tokens[extra.tokens.length - 1];
if (!prevToken) {
// Nothing before that: it cannot be a division.
return scanRegExp();
}
if (prevToken.type === 'Punctuator') {
if (prevToken.value === ')') {
checkToken = extra.tokens[extra.openParenToken - 1];
if (checkToken &&
checkToken.type === 'Keyword' &&
(checkToken.value === 'if' ||
checkToken.value === 'while' ||
checkToken.value === 'for' ||
checkToken.value === 'with')) {
return scanRegExp();
}
return scanPunctuator();
}
if (prevToken.value === '}') {
// Dividing a function by anything makes little sense,
// but we have to check for that.
if (extra.tokens[extra.openCurlyToken - 3] &&
extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') {
// Anonymous function.
checkToken = extra.tokens[extra.openCurlyToken - 4];
if (!checkToken) {
return scanPunctuator();
}
} else if (extra.tokens[extra.openCurlyToken - 4] &&
extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') {
// Named function.
checkToken = extra.tokens[extra.openCurlyToken - 5];
if (!checkToken) {
return scanRegExp();
}
} else {
return scanPunctuator();
}
// checkToken determines whether the function is
// a declaration or an expression.
if (FnExprTokens.indexOf(checkToken.value) >= 0) {
// It is an expression.
return scanPunctuator();
}
// It is a declaration.
return scanRegExp();
}
return scanRegExp();
}
if (prevToken.type === 'Keyword' && prevToken.value !== 'this') {
return scanRegExp();
}
return scanPunctuator();
}
function advance() {
var ch;
if (!state.inJSXChild) {
skipComment();
}
if (index >= length) {
return {
type: Token.EOF,
lineNumber: lineNumber,
lineStart: lineStart,
range: [index, index]
};
}
if (state.inJSXChild) {
return advanceJSXChild();
}
ch = source.charCodeAt(index);
// Very common: ( and ) and ;
if (ch === 40 || ch === 41 || ch === 58) {
return scanPunctuator();
}
// String literal starts with single quote (#39) or double quote (#34).
if (ch === 39 || ch === 34) {
if (state.inJSXTag) {
return scanJSXStringLiteral();
}
return scanStringLiteral();
}
if (state.inJSXTag && isJSXIdentifierStart(ch)) {
return scanJSXIdentifier();
}
if (ch === 96) {
return scanTemplate();
}
if (isIdentifierStart(ch)) {
return scanIdentifier();
}
// Dot (.) char #46 can also start a floating-point number, hence the need
// to check the next character.
if (ch === 46) {
if (isDecimalDigit(source.charCodeAt(index + 1))) {
return scanNumericLiteral();
}
return scanPunctuator();
}
if (isDecimalDigit(ch)) {
return scanNumericLiteral();
}
// Slash (/) char #47 can also start a regex.
if (extra.tokenize && ch === 47) {
return advanceSlash();
}
return scanPunctuator();
}
function lex() {
var token;
token = lookahead;
index = token.range[1];
lineNumber = token.lineNumber;
lineStart = token.lineStart;
lookahead = advance();
index = token.range[1];
lineNumber = token.lineNumber;
lineStart = token.lineStart;
return token;
}
function peek() {
var pos, line, start;
pos = index;
line = lineNumber;
start = lineStart;
lookahead = advance();
index = pos;
lineNumber = line;
lineStart = start;
}
function lookahead2() {
var adv, pos, line, start, result;
// If we are collecting the tokens, don't grab the next one yet.
/* istanbul ignore next */
adv = (typeof extra.advance === 'function') ? extra.advance : advance;
pos = index;
line = lineNumber;
start = lineStart;
// Scan for the next immediate token.
/* istanbul ignore if */
if (lookahead === null) {
lookahead = adv();
}
index = lookahead.range[1];
lineNumber = lookahead.lineNumber;
lineStart = lookahead.lineStart;
// Grab the token right after.
result = adv();
index = pos;
lineNumber = line;
lineStart = start;
return result;
}
function rewind(token) {
index = token.range[0];
lineNumber = token.lineNumber;
lineStart = token.lineStart;
lookahead = token;
}
function markerCreate() {
if (!extra.loc && !extra.range) {
return undefined;
}
skipComment();
return {offset: index, line: lineNumber, col: index - lineStart};
}
function markerCreatePreserveWhitespace() {
if (!extra.loc && !extra.range) {
return undefined;
}
return {offset: index, line: lineNumber, col: index - lineStart};
}
function processComment(node) {
var lastChild,
trailingComments,
bottomRight = extra.bottomRightStack,
last = bottomRight[bottomRight.length - 1];
if (node.type === Syntax.Program) {
/* istanbul ignore else */
if (node.body.length > 0) {
return;
}
}
if (extra.trailingComments.length > 0) {
if (extra.trailingComments[0].range[0] >= node.range[1]) {
trailingComments = extra.trailingComments;
extra.trailingComments = [];
} else {
extra.trailingComments.length = 0;
}
} else {
if (last && last.trailingComments && last.trailingComments[0].range[0] >= node.range[1]) {
trailingComments = last.trailingComments;
delete last.trailingComments;
}
}
// Eating the stack.
if (last) {
while (last && last.range[0] >= node.range[0]) {
lastChild = last;
last = bottomRight.pop();
}
}
if (lastChild) {
if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) {
node.leadingComments = lastChild.leadingComments;
delete lastChild.leadingComments;
}
} else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) {
node.leadingComments = extra.leadingComments;
extra.leadingComments = [];
}
if (trailingComments) {
node.trailingComments = trailingComments;
}
bottomRight.push(node);
}
function markerApply(marker, node) {
if (extra.range) {
node.range = [marker.offset, index];
}
if (extra.loc) {
node.loc = {
start: {
line: marker.line,
column: marker.col
},
end: {
line: lineNumber,
column: index - lineStart
}
};
node = delegate.postProcess(node);
}
if (extra.attachComment) {
processComment(node);
}
return node;
}
SyntaxTreeDelegate = {
name: 'SyntaxTree',
postProcess: function (node) {
return node;
},
createArrayExpression: function (elements) {
return {
type: Syntax.ArrayExpression,
elements: elements
};
},
createAssignmentExpression: function (operator, left, right) {
return {
type: Syntax.AssignmentExpression,
operator: operator,
left: left,
right: right
};
},
createBinaryExpression: function (operator, left, right) {
var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression :
Syntax.BinaryExpression;
return {
type: type,
operator: operator,
left: left,
right: right
};
},
createBlockStatement: function (body) {
return {
type: Syntax.BlockStatement,
body: body
};
},
createBreakStatement: function (label) {
return {
type: Syntax.BreakStatement,
label: label
};
},
createCallExpression: function (callee, args) {
return {
type: Syntax.CallExpression,
callee: callee,
'arguments': args
};
},
createCatchClause: function (param, body) {
return {
type: Syntax.CatchClause,
param: param,
body: body
};
},
createConditionalExpression: function (test, consequent, alternate) {
return {
type: Syntax.ConditionalExpression,
test: test,
consequent: consequent,
alternate: alternate
};
},
createContinueStatement: function (label) {
return {
type: Syntax.ContinueStatement,
label: label
};
},
createDebuggerStatement: function () {
return {
type: Syntax.DebuggerStatement
};
},
createDoWhileStatement: function (body, test) {
return {
type: Syntax.DoWhileStatement,
body: body,
test: test
};
},
createEmptyStatement: function () {
return {
type: Syntax.EmptyStatement
};
},
createExpressionStatement: function (expression) {
return {
type: Syntax.ExpressionStatement,
expression: expression
};
},
createForStatement: function (init, test, update, body) {
return {
type: Syntax.ForStatement,
init: init,
test: test,
update: update,
body: body
};
},
createForInStatement: function (left, right, body) {
return {
type: Syntax.ForInStatement,
left: left,
right: right,
body: body,
each: false
};
},
createForOfStatement: function (left, right, body) {
return {
type: Syntax.ForOfStatement,
left: left,
right: right,
body: body
};
},
createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression,
isAsync, returnType, typeParameters) {
var funDecl = {
type: Syntax.FunctionDeclaration,
id: id,
params: params,
defaults: defaults,
body: body,
rest: rest,
generator: generator,
expression: expression,
returnType: returnType,
typeParameters: typeParameters
};
if (isAsync) {
funDecl.async = true;
}
return funDecl;
},
createFunctionExpression: function (id, params, defaults, body, rest, generator, expression,
isAsync, returnType, typeParameters) {
var funExpr = {
type: Syntax.FunctionExpression,
id: id,
params: params,
defaults: defaults,
body: body,
rest: rest,
generator: generator,
expression: expression,
returnType: returnType,
typeParameters: typeParameters
};
if (isAsync) {
funExpr.async = true;
}
return funExpr;
},
createIdentifier: function (name) {
return {
type: Syntax.Identifier,
name: name,
// Only here to initialize the shape of the object to ensure
// that the 'typeAnnotation' key is ordered before others that
// are added later (like 'loc' and 'range'). This just helps
// keep the shape of Identifier nodes consistent with everything
// else.
typeAnnotation: undefined,
optional: undefined
};
},
createTypeAnnotation: function (typeAnnotation) {
return {
type: Syntax.TypeAnnotation,
typeAnnotation: typeAnnotation
};
},
createTypeCast: function (expression, typeAnnotation) {
return {
type: Syntax.TypeCastExpression,
expression: expression,
typeAnnotation: typeAnnotation
};
},
createFunctionTypeAnnotation: function (params, returnType, rest, typeParameters) {
return {
type: Syntax.FunctionTypeAnnotation,
params: params,
returnType: returnType,
rest: rest,
typeParameters: typeParameters
};
},
createFunctionTypeParam: function (name, typeAnnotation, optional) {
return {
type: Syntax.FunctionTypeParam,
name: name,
typeAnnotation: typeAnnotation,
optional: optional
};
},
createNullableTypeAnnotation: function (typeAnnotation) {
return {
type: Syntax.NullableTypeAnnotation,
typeAnnotation: typeAnnotation
};
},
createArrayTypeAnnotation: function (elementType) {
return {
type: Syntax.ArrayTypeAnnotation,
elementType: elementType
};
},
createGenericTypeAnnotation: function (id, typeParameters) {
return {
type: Syntax.GenericTypeAnnotation,
id: id,
typeParameters: typeParameters
};
},
createQualifiedTypeIdentifier: function (qualification, id) {
return {
type: Syntax.QualifiedTypeIdentifier,
qualification: qualification,
id: id
};
},
createTypeParameterDeclaration: function (params) {
return {
type: Syntax.TypeParameterDeclaration,
params: params
};
},
createTypeParameterInstantiation: function (params) {
return {
type: Syntax.TypeParameterInstantiation,
params: params
};
},
createAnyTypeAnnotation: function () {
return {
type: Syntax.AnyTypeAnnotation
};
},
createBooleanTypeAnnotation: function () {
return {
type: Syntax.BooleanTypeAnnotation
};
},
createNumberTypeAnnotation: function () {
return {
type: Syntax.NumberTypeAnnotation
};
},
createStringTypeAnnotation: function () {
return {
type: Syntax.StringTypeAnnotation
};
},
createStringLiteralTypeAnnotation: function (token) {
return {
type: Syntax.StringLiteralTypeAnnotation,
value: token.value,
raw: source.slice(token.range[0], token.range[1])
};
},
createVoidTypeAnnotation: function () {
return {
type: Syntax.VoidTypeAnnotation
};
},
createTypeofTypeAnnotation: function (argument) {
return {
type: Syntax.TypeofTypeAnnotation,
argument: argument
};
},
createTupleTypeAnnotation: function (types) {
return {
type: Syntax.TupleTypeAnnotation,
types: types
};
},
createObjectTypeAnnotation: function (properties, indexers, callProperties) {
return {
type: Syntax.ObjectTypeAnnotation,
properties: properties,
indexers: indexers,
callProperties: callProperties
};
},
createObjectTypeIndexer: function (id, key, value, isStatic) {
return {
type: Syntax.ObjectTypeIndexer,
id: id,
key: key,
value: value,
"static": isStatic
};
},
createObjectTypeCallProperty: function (value, isStatic) {
return {
type: Syntax.ObjectTypeCallProperty,
value: value,
"static": isStatic
};
},
createObjectTypeProperty: function (key, value, optional, isStatic) {
return {
type: Syntax.ObjectTypeProperty,
key: key,
value: value,
optional: optional,
"static": isStatic
};
},
createUnionTypeAnnotation: function (types) {
return {
type: Syntax.UnionTypeAnnotation,
types: types
};
},
createIntersectionTypeAnnotation: function (types) {
return {
type: Syntax.IntersectionTypeAnnotation,
types: types
};
},
createTypeAlias: function (id, typeParameters, right) {
return {
type: Syntax.TypeAlias,
id: id,
typeParameters: typeParameters,
right: right
};
},
createInterface: function (id, typeParameters, body, extended) {
return {
type: Syntax.InterfaceDeclaration,
id: id,
typeParameters: typeParameters,
body: body,
"extends": extended
};
},
createInterfaceExtends: function (id, typeParameters) {
return {
type: Syntax.InterfaceExtends,
id: id,
typeParameters: typeParameters
};
},
createDeclareFunction: function (id) {
return {
type: Syntax.DeclareFunction,
id: id
};
},
createDeclareVariable: function (id) {
return {
type: Syntax.DeclareVariable,
id: id
};
},
createDeclareModule: function (id, body) {
return {
type: Syntax.DeclareModule,
id: id,
body: body
};
},
createJSXAttribute: function (name, value) {
return {
type: Syntax.JSXAttribute,
name: name,
value: value || null
};
},
createJSXSpreadAttribute: function (argument) {
return {
type: Syntax.JSXSpreadAttribute,
argument: argument
};
},
createJSXIdentifier: function (name) {
return {
type: Syntax.JSXIdentifier,
name: name
};
},
createJSXNamespacedName: function (namespace, name) {
return {
type: Syntax.JSXNamespacedName,
namespace: namespace,
name: name
};
},
createJSXMemberExpression: function (object, property) {
return {
type: Syntax.JSXMemberExpression,
object: object,
property: property
};
},
createJSXElement: function (openingElement, closingElement, children) {
return {
type: Syntax.JSXElement,
openingElement: openingElement,
closingElement: closingElement,
children: children
};
},
createJSXEmptyExpression: function () {
return {
type: Syntax.JSXEmptyExpression
};
},
createJSXExpressionContainer: function (expression) {
return {
type: Syntax.JSXExpressionContainer,
expression: expression
};
},
createJSXOpeningElement: function (name, attributes, selfClosing) {
return {
type: Syntax.JSXOpeningElement,
name: name,
selfClosing: selfClosing,
attributes: attributes
};
},
createJSXClosingElement: function (name) {
return {
type: Syntax.JSXClosingElement,
name: name
};
},
createIfStatement: function (test, consequent, alternate) {
return {
type: Syntax.IfStatement,
test: test,
consequent: consequent,
alternate: alternate
};
},
createLabeledStatement: function (label, body) {
return {
type: Syntax.LabeledStatement,
label: label,
body: body
};
},
createLiteral: function (token) {
var object = {
type: Syntax.Literal,
value: token.value,
raw: source.slice(token.range[0], token.range[1])
};
if (token.regex) {
object.regex = token.regex;
}
return object;
},
createMemberExpression: function (accessor, object, property) {
return {
type: Syntax.MemberExpression,
computed: accessor === '[',
object: object,
property: property
};
},
createNewExpression: function (callee, args) {
return {
type: Syntax.NewExpression,
callee: callee,
'arguments': args
};
},
createObjectExpression: function (properties) {
return {
type: Syntax.ObjectExpression,
properties: properties
};
},
createPostfixExpression: function (operator, argument) {
return {
type: Syntax.UpdateExpression,
operator: operator,
argument: argument,
prefix: false
};
},
createProgram: function (body) {
return {
type: Syntax.Program,
body: body
};
},
createProperty: function (kind, key, value, method, shorthand, computed) {
return {
type: Syntax.Property,
key: key,
value: value,
kind: kind,
method: method,
shorthand: shorthand,
computed: computed
};
},
createReturnStatement: function (argument) {
return {
type: Syntax.ReturnStatement,
argument: argument
};
},
createSequenceExpression: function (expressions) {
return {
type: Syntax.SequenceExpression,
expressions: expressions
};
},
createSwitchCase: function (test, consequent) {
return {
type: Syntax.SwitchCase,
test: test,
consequent: consequent
};
},
createSwitchStatement: function (discriminant, cases) {
return {
type: Syntax.SwitchStatement,
discriminant: discriminant,
cases: cases
};
},
createThisExpression: function () {
return {
type: Syntax.ThisExpression
};
},
createThrowStatement: function (argument) {
return {
type: Syntax.ThrowStatement,
argument: argument
};
},
createTryStatement: function (block, guardedHandlers, handlers, finalizer) {
return {
type: Syntax.TryStatement,
block: block,
guardedHandlers: guardedHandlers,
handlers: handlers,
finalizer: finalizer
};
},
createUnaryExpression: function (operator, argument) {
if (operator === '++' || operator === '--') {
return {
type: Syntax.UpdateExpression,
operator: operator,
argument: argument,
prefix: true
};
}
return {
type: Syntax.UnaryExpression,
operator: operator,
argument: argument,
prefix: true
};
},
createVariableDeclaration: function (declarations, kind) {
return {
type: Syntax.VariableDeclaration,
declarations: declarations,
kind: kind
};
},
createVariableDeclarator: function (id, init) {
return {
type: Syntax.VariableDeclarator,
id: id,
init: init
};
},
createWhileStatement: function (test, body) {
return {
type: Syntax.WhileStatement,
test: test,
body: body
};
},
createWithStatement: function (object, body) {
return {
type: Syntax.WithStatement,
object: object,
body: body
};
},
createTemplateElement: function (value, tail) {
return {
type: Syntax.TemplateElement,
value: value,
tail: tail
};
},
createTemplateLiteral: function (quasis, expressions) {
return {
type: Syntax.TemplateLiteral,
quasis: quasis,
expressions: expressions
};
},
createSpreadElement: function (argument) {
return {
type: Syntax.SpreadElement,
argument: argument
};
},
createSpreadProperty: function (argument) {
return {
type: Syntax.SpreadProperty,
argument: argument
};
},
createTaggedTemplateExpression: function (tag, quasi) {
return {
type: Syntax.TaggedTemplateExpression,
tag: tag,
quasi: quasi
};
},
createArrowFunctionExpression: function (params, defaults, body, rest, expression, isAsync) {
var arrowExpr = {
type: Syntax.ArrowFunctionExpression,
id: null,
params: params,
defaults: defaults,
body: body,
rest: rest,
generator: false,
expression: expression
};
if (isAsync) {
arrowExpr.async = true;
}
return arrowExpr;
},
createMethodDefinition: function (propertyType, kind, key, value, computed) {
return {
type: Syntax.MethodDefinition,
key: key,
value: value,
kind: kind,
'static': propertyType === ClassPropertyType["static"],
computed: computed
};
},
createClassProperty: function (key, typeAnnotation, computed, isStatic) {
return {
type: Syntax.ClassProperty,
key: key,
typeAnnotation: typeAnnotation,
computed: computed,
"static": isStatic
};
},
createClassBody: function (body) {
return {
type: Syntax.ClassBody,
body: body
};
},
createClassImplements: function (id, typeParameters) {
return {
type: Syntax.ClassImplements,
id: id,
typeParameters: typeParameters
};
},
createClassExpression: function (id, superClass, body, typeParameters, superTypeParameters, implemented) {
return {
type: Syntax.ClassExpression,
id: id,
superClass: superClass,
body: body,
typeParameters: typeParameters,
superTypeParameters: superTypeParameters,
"implements": implemented
};
},
createClassDeclaration: function (id, superClass, body, typeParameters, superTypeParameters, implemented) {
return {
type: Syntax.ClassDeclaration,
id: id,
superClass: superClass,
body: body,
typeParameters: typeParameters,
superTypeParameters: superTypeParameters,
"implements": implemented
};
},
createModuleSpecifier: function (token) {
return {
type: Syntax.ModuleSpecifier,
value: token.value,
raw: source.slice(token.range[0], token.range[1])
};
},
createExportSpecifier: function (id, name) {
return {
type: Syntax.ExportSpecifier,
id: id,
name: name
};
},
createExportBatchSpecifier: function () {
return {
type: Syntax.ExportBatchSpecifier
};
},
createImportDefaultSpecifier: function (id) {
return {
type: Syntax.ImportDefaultSpecifier,
id: id
};
},
createImportNamespaceSpecifier: function (id) {
return {
type: Syntax.ImportNamespaceSpecifier,
id: id
};
},
createExportDeclaration: function (isDefault, declaration, specifiers, src) {
return {
type: Syntax.ExportDeclaration,
'default': !!isDefault,
declaration: declaration,
specifiers: specifiers,
source: src
};
},
createImportSpecifier: function (id, name) {
return {
type: Syntax.ImportSpecifier,
id: id,
name: name
};
},
createImportDeclaration: function (specifiers, src, isType) {
return {
type: Syntax.ImportDeclaration,
specifiers: specifiers,
source: src,
isType: isType
};
},
createYieldExpression: function (argument, dlg) {
return {
type: Syntax.YieldExpression,
argument: argument,
delegate: dlg
};
},
createAwaitExpression: function (argument) {
return {
type: Syntax.AwaitExpression,
argument: argument
};
},
createComprehensionExpression: function (filter, blocks, body) {
return {
type: Syntax.ComprehensionExpression,
filter: filter,
blocks: blocks,
body: body
};
}
};
// Return true if there is a line terminator before the next token.
function peekLineTerminator() {
var pos, line, start, found;
pos = index;
line = lineNumber;
start = lineStart;
skipComment();
found = lineNumber !== line;
index = pos;
lineNumber = line;
lineStart = start;
return found;
}
// Throw an exception
function throwError(token, messageFormat) {
var error,
args = Array.prototype.slice.call(arguments, 2),
msg = messageFormat.replace(
/%(\d)/g,
function (whole, idx) {
assert(idx < args.length, 'Message reference must be in range');
return args[idx];
}
);
if (typeof token.lineNumber === 'number') {
error = new Error('Line ' + token.lineNumber + ': ' + msg);
error.index = token.range[0];
error.lineNumber = token.lineNumber;
error.column = token.range[0] - lineStart + 1;
} else {
error = new Error('Line ' + lineNumber + ': ' + msg);
error.index = index;
error.lineNumber = lineNumber;
error.column = index - lineStart + 1;
}
error.description = msg;
throw error;
}
function throwErrorTolerant() {
try {
throwError.apply(null, arguments);
} catch (e) {
if (extra.errors) {
extra.errors.push(e);
} else {
throw e;
}
}
}
// Throw an exception because of the token.
function throwUnexpected(token) {
if (token.type === Token.EOF) {
throwError(token, Messages.UnexpectedEOS);
}
if (token.type === Token.NumericLiteral) {
throwError(token, Messages.UnexpectedNumber);
}
if (token.type === Token.StringLiteral || token.type === Token.JSXText) {
throwError(token, Messages.UnexpectedString);
}
if (token.type === Token.Identifier) {
throwError(token, Messages.UnexpectedIdentifier);
}
if (token.type === Token.Keyword) {
if (isFutureReservedWord(token.value)) {
throwError(token, Messages.UnexpectedReserved);
} else if (strict && isStrictModeReservedWord(token.value)) {
throwErrorTolerant(token, Messages.StrictReservedWord);
return;
}
throwError(token, Messages.UnexpectedToken, token.value);
}
if (token.type === Token.Template) {
throwError(token, Messages.UnexpectedTemplate, token.value.raw);
}
// BooleanLiteral, NullLiteral, or Punctuator.
throwError(token, Messages.UnexpectedToken, token.value);
}
// Expect the next token to match the specified punctuator.
// If not, an exception will be thrown.
function expect(value) {
var token = lex();
if (token.type !== Token.Punctuator || token.value !== value) {
throwUnexpected(token);
}
}
// Expect the next token to match the specified keyword.
// If not, an exception will be thrown.
function expectKeyword(keyword, contextual) {
var token = lex();
if (token.type !== (contextual ? Token.Identifier : Token.Keyword) ||
token.value !== keyword) {
throwUnexpected(token);
}
}
// Expect the next token to match the specified contextual keyword.
// If not, an exception will be thrown.
function expectContextualKeyword(keyword) {
return expectKeyword(keyword, true);
}
// Return true if the next token matches the specified punctuator.
function match(value) {
return lookahead.type === Token.Punctuator && lookahead.value === value;
}
// Return true if the next token matches the specified keyword
function matchKeyword(keyword, contextual) {
var expectedType = contextual ? Token.Identifier : Token.Keyword;
return lookahead.type === expectedType && lookahead.value === keyword;
}
// Return true if the next token matches the specified contextual keyword
function matchContextualKeyword(keyword) {
return matchKeyword(keyword, true);
}
// Return true if the next token is an assignment operator
function matchAssign() {
var op;
if (lookahead.type !== Token.Punctuator) {
return false;
}
op = lookahead.value;
return op === '=' ||
op === '*=' ||
op === '/=' ||
op === '%=' ||
op === '+=' ||
op === '-=' ||
op === '<<=' ||
op === '>>=' ||
op === '>>>=' ||
op === '&=' ||
op === '^=' ||
op === '|=';
}
// Note that 'yield' is treated as a keyword in strict mode, but a
// contextual keyword (identifier) in non-strict mode, so we need to
// use matchKeyword('yield', false) and matchKeyword('yield', true)
// (i.e. matchContextualKeyword) appropriately.
function matchYield() {
return state.yieldAllowed && matchKeyword('yield', !strict);
}
function matchAsync() {
var backtrackToken = lookahead, matches = false;
if (matchContextualKeyword('async')) {
lex(); // Make sure peekLineTerminator() starts after 'async'.
matches = !peekLineTerminator();
rewind(backtrackToken); // Revert the lex().
}
return matches;
}
function matchAwait() {
return state.awaitAllowed && matchContextualKeyword('await');
}
function consumeSemicolon() {
var line, oldIndex = index, oldLineNumber = lineNumber,
oldLineStart = lineStart, oldLookahead = lookahead;
// Catch the very common case first: immediately a semicolon (char #59).
if (source.charCodeAt(index) === 59) {
lex();
return;
}
line = lineNumber;
skipComment();
if (lineNumber !== line) {
index = oldIndex;
lineNumber = oldLineNumber;
lineStart = oldLineStart;
lookahead = oldLookahead;
return;
}
if (match(';')) {
lex();
return;
}
if (lookahead.type !== Token.EOF && !match('}')) {
throwUnexpected(lookahead);
}
}
// Return true if provided expression is LeftHandSideExpression
function isLeftHandSide(expr) {
return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression;
}
function isAssignableLeftHandSide(expr) {
return isLeftHandSide(expr) || expr.type === Syntax.ObjectPattern || expr.type === Syntax.ArrayPattern;
}
// 11.1.4 Array Initialiser
function parseArrayInitialiser() {
var elements = [], blocks = [], filter = null, tmp, possiblecomprehension = true,
marker = markerCreate();
expect('[');
while (!match(']')) {
if (lookahead.value === 'for' &&
lookahead.type === Token.Keyword) {
if (!possiblecomprehension) {
throwError({}, Messages.ComprehensionError);
}
matchKeyword('for');
tmp = parseForStatement({ignoreBody: true});
tmp.of = tmp.type === Syntax.ForOfStatement;
tmp.type = Syntax.ComprehensionBlock;
if (tmp.left.kind) { // can't be let or const
throwError({}, Messages.ComprehensionError);
}
blocks.push(tmp);
} else if (lookahead.value === 'if' &&
lookahead.type === Token.Keyword) {
if (!possiblecomprehension) {
throwError({}, Messages.ComprehensionError);
}
expectKeyword('if');
expect('(');
filter = parseExpression();
expect(')');
} else if (lookahead.value === ',' &&
lookahead.type === Token.Punctuator) {
possiblecomprehension = false; // no longer allowed.
lex();
elements.push(null);
} else {
tmp = parseSpreadOrAssignmentExpression();
elements.push(tmp);
if (tmp && tmp.type === Syntax.SpreadElement) {
if (!match(']')) {
throwError({}, Messages.ElementAfterSpreadElement);
}
} else if (!(match(']') || matchKeyword('for') || matchKeyword('if'))) {
expect(','); // this lexes.
possiblecomprehension = false;
}
}
}
expect(']');
if (filter && !blocks.length) {
throwError({}, Messages.ComprehensionRequiresBlock);
}
if (blocks.length) {
if (elements.length !== 1) {
throwError({}, Messages.ComprehensionError);
}
return markerApply(marker, delegate.createComprehensionExpression(filter, blocks, elements[0]));
}
return markerApply(marker, delegate.createArrayExpression(elements));
}
// 11.1.5 Object Initialiser
function parsePropertyFunction(options) {
var previousStrict, previousYieldAllowed, previousAwaitAllowed,
params, defaults, body, marker = markerCreate();
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = options.generator;
previousAwaitAllowed = state.awaitAllowed;
state.awaitAllowed = options.async;
params = options.params || [];
defaults = options.defaults || [];
body = parseConciseBody();
if (options.name && strict && isRestrictedWord(params[0].name)) {
throwErrorTolerant(options.name, Messages.StrictParamName);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
state.awaitAllowed = previousAwaitAllowed;
return markerApply(marker, delegate.createFunctionExpression(
null,
params,
defaults,
body,
options.rest || null,
options.generator,
body.type !== Syntax.BlockStatement,
options.async,
options.returnType,
options.typeParameters
));
}
function parsePropertyMethodFunction(options) {
var previousStrict, tmp, method;
previousStrict = strict;
strict = true;
tmp = parseParams();
if (tmp.stricted) {
throwErrorTolerant(tmp.stricted, tmp.message);
}
method = parsePropertyFunction({
params: tmp.params,
defaults: tmp.defaults,
rest: tmp.rest,
generator: options.generator,
async: options.async,
returnType: tmp.returnType,
typeParameters: options.typeParameters
});
strict = previousStrict;
return method;
}
function parseObjectPropertyKey() {
var marker = markerCreate(),
token = lex(),
propertyKey,
result;
// Note: This function is called only from parseObjectProperty(), where
// EOF and Punctuator tokens are already filtered out.
if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {
if (strict && token.octal) {
throwErrorTolerant(token, Messages.StrictOctalLiteral);
}
return markerApply(marker, delegate.createLiteral(token));
}
if (token.type === Token.Punctuator && token.value === '[') {
// For computed properties we should skip the [ and ], and
// capture in marker only the assignment expression itself.
marker = markerCreate();
propertyKey = parseAssignmentExpression();
result = markerApply(marker, propertyKey);
expect(']');
return result;
}
return markerApply(marker, delegate.createIdentifier(token.value));
}
function parseObjectProperty() {
var token, key, id, param, computed,
marker = markerCreate(), returnType, typeParameters;
token = lookahead;
computed = (token.value === '[' && token.type === Token.Punctuator);
if (token.type === Token.Identifier || computed || matchAsync()) {
id = parseObjectPropertyKey();
if (match(':')) {
lex();
return markerApply(
marker,
delegate.createProperty(
'init',
id,
parseAssignmentExpression(),
false,
false,
computed
)
);
}
if (match('(') || match('<')) {
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
return markerApply(
marker,
delegate.createProperty(
'init',
id,
parsePropertyMethodFunction({
generator: false,
async: false,
typeParameters: typeParameters
}),
true,
false,
computed
)
);
}
// Property Assignment: Getter and Setter.
if (token.value === 'get') {
computed = (lookahead.value === '[');
key = parseObjectPropertyKey();
expect('(');
expect(')');
if (match(':')) {
returnType = parseTypeAnnotation();
}
return markerApply(
marker,
delegate.createProperty(
'get',
key,
parsePropertyFunction({
generator: false,
async: false,
returnType: returnType
}),
false,
false,
computed
)
);
}
if (token.value === 'set') {
computed = (lookahead.value === '[');
key = parseObjectPropertyKey();
expect('(');
token = lookahead;
param = [ parseTypeAnnotatableIdentifier() ];
expect(')');
if (match(':')) {
returnType = parseTypeAnnotation();
}
return markerApply(
marker,
delegate.createProperty(
'set',
key,
parsePropertyFunction({
params: param,
generator: false,
async: false,
name: token,
returnType: returnType
}),
false,
false,
computed
)
);
}
if (token.value === 'async') {
computed = (lookahead.value === '[');
key = parseObjectPropertyKey();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
return markerApply(
marker,
delegate.createProperty(
'init',
key,
parsePropertyMethodFunction({
generator: false,
async: true,
typeParameters: typeParameters
}),
true,
false,
computed
)
);
}
if (computed) {
// Computed properties can only be used with full notation.
throwUnexpected(lookahead);
}
return markerApply(
marker,
delegate.createProperty('init', id, id, false, true, false)
);
}
if (token.type === Token.EOF || token.type === Token.Punctuator) {
if (!match('*')) {
throwUnexpected(token);
}
lex();
computed = (lookahead.type === Token.Punctuator && lookahead.value === '[');
id = parseObjectPropertyKey();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
if (!match('(')) {
throwUnexpected(lex());
}
return markerApply(marker, delegate.createProperty(
'init',
id,
parsePropertyMethodFunction({
generator: true,
typeParameters: typeParameters
}),
true,
false,
computed
));
}
key = parseObjectPropertyKey();
if (match(':')) {
lex();
return markerApply(marker, delegate.createProperty('init', key, parseAssignmentExpression(), false, false, false));
}
if (match('(') || match('<')) {
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
return markerApply(marker, delegate.createProperty(
'init',
key,
parsePropertyMethodFunction({
generator: false,
typeParameters: typeParameters
}),
true,
false,
false
));
}
throwUnexpected(lex());
}
function parseObjectSpreadProperty() {
var marker = markerCreate();
expect('...');
return markerApply(marker, delegate.createSpreadProperty(parseAssignmentExpression()));
}
function getFieldName(key) {
var toString = String;
if (key.type === Syntax.Identifier) {
return key.name;
}
return toString(key.value);
}
function parseObjectInitialiser() {
var properties = [], property, name, kind, storedKind, map = new StringMap(),
marker = markerCreate(), toString = String;
expect('{');
while (!match('}')) {
if (match('...')) {
property = parseObjectSpreadProperty();
} else {
property = parseObjectProperty();
if (property.key.type === Syntax.Identifier) {
name = property.key.name;
} else {
name = toString(property.key.value);
}
kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set;
if (map.has(name)) {
storedKind = map.get(name);
if (storedKind === PropertyKind.Data) {
if (strict && kind === PropertyKind.Data) {
throwErrorTolerant({}, Messages.StrictDuplicateProperty);
} else if (kind !== PropertyKind.Data) {
throwErrorTolerant({}, Messages.AccessorDataProperty);
}
} else {
if (kind === PropertyKind.Data) {
throwErrorTolerant({}, Messages.AccessorDataProperty);
} else if (storedKind & kind) {
throwErrorTolerant({}, Messages.AccessorGetSet);
}
}
map.set(name, storedKind | kind);
} else {
map.set(name, kind);
}
}
properties.push(property);
if (!match('}')) {
expect(',');
}
}
expect('}');
return markerApply(marker, delegate.createObjectExpression(properties));
}
function parseTemplateElement(option) {
var marker = markerCreate(),
token = scanTemplateElement(option);
if (strict && token.octal) {
throwError(token, Messages.StrictOctalLiteral);
}
return markerApply(marker, delegate.createTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail));
}
function parseTemplateLiteral() {
var quasi, quasis, expressions, marker = markerCreate();
quasi = parseTemplateElement({ head: true });
quasis = [ quasi ];
expressions = [];
while (!quasi.tail) {
expressions.push(parseExpression());
quasi = parseTemplateElement({ head: false });
quasis.push(quasi);
}
return markerApply(marker, delegate.createTemplateLiteral(quasis, expressions));
}
// 11.1.6 The Grouping Operator
function parseGroupExpression() {
var expr, marker, typeAnnotation;
expect('(');
++state.parenthesizedCount;
marker = markerCreate();
expr = parseExpression();
if (match(':')) {
typeAnnotation = parseTypeAnnotation();
expr = markerApply(marker, delegate.createTypeCast(
expr,
typeAnnotation
));
}
expect(')');
return expr;
}
function matchAsyncFuncExprOrDecl() {
var token;
if (matchAsync()) {
token = lookahead2();
if (token.type === Token.Keyword && token.value === 'function') {
return true;
}
}
return false;
}
// 11.1 Primary Expressions
function parsePrimaryExpression() {
var marker, type, token, expr;
type = lookahead.type;
if (type === Token.Identifier) {
marker = markerCreate();
return markerApply(marker, delegate.createIdentifier(lex().value));
}
if (type === Token.StringLiteral || type === Token.NumericLiteral) {
if (strict && lookahead.octal) {
throwErrorTolerant(lookahead, Messages.StrictOctalLiteral);
}
marker = markerCreate();
return markerApply(marker, delegate.createLiteral(lex()));
}
if (type === Token.Keyword) {
if (matchKeyword('this')) {
marker = markerCreate();
lex();
return markerApply(marker, delegate.createThisExpression());
}
if (matchKeyword('function')) {
return parseFunctionExpression();
}
if (matchKeyword('class')) {
return parseClassExpression();
}
if (matchKeyword('super')) {
marker = markerCreate();
lex();
return markerApply(marker, delegate.createIdentifier('super'));
}
}
if (type === Token.BooleanLiteral) {
marker = markerCreate();
token = lex();
token.value = (token.value === 'true');
return markerApply(marker, delegate.createLiteral(token));
}
if (type === Token.NullLiteral) {
marker = markerCreate();
token = lex();
token.value = null;
return markerApply(marker, delegate.createLiteral(token));
}
if (match('[')) {
return parseArrayInitialiser();
}
if (match('{')) {
return parseObjectInitialiser();
}
if (match('(')) {
return parseGroupExpression();
}
if (match('/') || match('/=')) {
marker = markerCreate();
expr = delegate.createLiteral(scanRegExp());
peek();
return markerApply(marker, expr);
}
if (type === Token.Template) {
return parseTemplateLiteral();
}
if (match('<')) {
return parseJSXElement();
}
throwUnexpected(lex());
}
// 11.2 Left-Hand-Side Expressions
function parseArguments() {
var args = [], arg;
expect('(');
if (!match(')')) {
while (index < length) {
arg = parseSpreadOrAssignmentExpression();
args.push(arg);
if (match(')')) {
break;
} else if (arg.type === Syntax.SpreadElement) {
throwError({}, Messages.ElementAfterSpreadElement);
}
expect(',');
}
}
expect(')');
return args;
}
function parseSpreadOrAssignmentExpression() {
if (match('...')) {
var marker = markerCreate();
lex();
return markerApply(marker, delegate.createSpreadElement(parseAssignmentExpression()));
}
return parseAssignmentExpression();
}
function parseNonComputedProperty() {
var marker = markerCreate(),
token = lex();
if (!isIdentifierName(token)) {
throwUnexpected(token);
}
return markerApply(marker, delegate.createIdentifier(token.value));
}
function parseNonComputedMember() {
expect('.');
return parseNonComputedProperty();
}
function parseComputedMember() {
var expr;
expect('[');
expr = parseExpression();
expect(']');
return expr;
}
function parseNewExpression() {
var callee, args, marker = markerCreate();
expectKeyword('new');
callee = parseLeftHandSideExpression();
args = match('(') ? parseArguments() : [];
return markerApply(marker, delegate.createNewExpression(callee, args));
}
function parseLeftHandSideExpressionAllowCall() {
var expr, args, marker = markerCreate();
expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
while (match('.') || match('[') || match('(') || lookahead.type === Token.Template) {
if (match('(')) {
args = parseArguments();
expr = markerApply(marker, delegate.createCallExpression(expr, args));
} else if (match('[')) {
expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember()));
} else if (match('.')) {
expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember()));
} else {
expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral()));
}
}
return expr;
}
function parseLeftHandSideExpression() {
var expr, marker = markerCreate();
expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
while (match('.') || match('[') || lookahead.type === Token.Template) {
if (match('[')) {
expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember()));
} else if (match('.')) {
expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember()));
} else {
expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral()));
}
}
return expr;
}
// 11.3 Postfix Expressions
function parsePostfixExpression() {
var marker = markerCreate(),
expr = parseLeftHandSideExpressionAllowCall(),
token;
if (lookahead.type !== Token.Punctuator) {
return expr;
}
if ((match('++') || match('--')) && !peekLineTerminator()) {
// 11.3.1, 11.3.2
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
throwErrorTolerant({}, Messages.StrictLHSPostfix);
}
if (!isLeftHandSide(expr)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
token = lex();
expr = markerApply(marker, delegate.createPostfixExpression(token.value, expr));
}
return expr;
}
// 11.4 Unary Operators
function parseUnaryExpression() {
var marker, token, expr;
if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
return parsePostfixExpression();
}
if (match('++') || match('--')) {
marker = markerCreate();
token = lex();
expr = parseUnaryExpression();
// 11.4.4, 11.4.5
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
throwErrorTolerant({}, Messages.StrictLHSPrefix);
}
if (!isLeftHandSide(expr)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
return markerApply(marker, delegate.createUnaryExpression(token.value, expr));
}
if (match('+') || match('-') || match('~') || match('!')) {
marker = markerCreate();
token = lex();
expr = parseUnaryExpression();
return markerApply(marker, delegate.createUnaryExpression(token.value, expr));
}
if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
marker = markerCreate();
token = lex();
expr = parseUnaryExpression();
expr = markerApply(marker, delegate.createUnaryExpression(token.value, expr));
if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
throwErrorTolerant({}, Messages.StrictDelete);
}
return expr;
}
return parsePostfixExpression();
}
function binaryPrecedence(token, allowIn) {
var prec = 0;
if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
return 0;
}
switch (token.value) {
case '||':
prec = 1;
break;
case '&&':
prec = 2;
break;
case '|':
prec = 3;
break;
case '^':
prec = 4;
break;
case '&':
prec = 5;
break;
case '==':
case '!=':
case '===':
case '!==':
prec = 6;
break;
case '<':
case '>':
case '<=':
case '>=':
case 'instanceof':
prec = 7;
break;
case 'in':
prec = allowIn ? 7 : 0;
break;
case '<<':
case '>>':
case '>>>':
prec = 8;
break;
case '+':
case '-':
prec = 9;
break;
case '*':
case '/':
case '%':
prec = 11;
break;
default:
break;
}
return prec;
}
// 11.5 Multiplicative Operators
// 11.6 Additive Operators
// 11.7 Bitwise Shift Operators
// 11.8 Relational Operators
// 11.9 Equality Operators
// 11.10 Binary Bitwise Operators
// 11.11 Binary Logical Operators
function parseBinaryExpression() {
var expr, token, prec, previousAllowIn, stack, right, operator, left, i,
marker, markers;
previousAllowIn = state.allowIn;
state.allowIn = true;
marker = markerCreate();
left = parseUnaryExpression();
token = lookahead;
prec = binaryPrecedence(token, previousAllowIn);
if (prec === 0) {
return left;
}
token.prec = prec;
lex();
markers = [marker, markerCreate()];
right = parseUnaryExpression();
stack = [left, token, right];
while ((prec = binaryPrecedence(lookahead, previousAllowIn)) > 0) {
// Reduce: make a binary expression from the three topmost entries.
while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
right = stack.pop();
operator = stack.pop().value;
left = stack.pop();
expr = delegate.createBinaryExpression(operator, left, right);
markers.pop();
marker = markers.pop();
markerApply(marker, expr);
stack.push(expr);
markers.push(marker);
}
// Shift.
token = lex();
token.prec = prec;
stack.push(token);
markers.push(markerCreate());
expr = parseUnaryExpression();
stack.push(expr);
}
state.allowIn = previousAllowIn;
// Final reduce to clean-up the stack.
i = stack.length - 1;
expr = stack[i];
markers.pop();
while (i > 1) {
expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
i -= 2;
marker = markers.pop();
markerApply(marker, expr);
}
return expr;
}
// 11.12 Conditional Operator
function parseConditionalExpression() {
var expr, previousAllowIn, consequent, alternate, marker = markerCreate();
expr = parseBinaryExpression();
if (match('?')) {
lex();
previousAllowIn = state.allowIn;
state.allowIn = true;
consequent = parseAssignmentExpression();
state.allowIn = previousAllowIn;
expect(':');
alternate = parseAssignmentExpression();
expr = markerApply(marker, delegate.createConditionalExpression(expr, consequent, alternate));
}
return expr;
}
// 11.13 Assignment Operators
// 12.14.5 AssignmentPattern
function reinterpretAsAssignmentBindingPattern(expr) {
var i, len, property, element;
if (expr.type === Syntax.ObjectExpression) {
expr.type = Syntax.ObjectPattern;
for (i = 0, len = expr.properties.length; i < len; i += 1) {
property = expr.properties[i];
if (property.type === Syntax.SpreadProperty) {
if (i < len - 1) {
throwError({}, Messages.PropertyAfterSpreadProperty);
}
reinterpretAsAssignmentBindingPattern(property.argument);
} else {
if (property.kind !== 'init') {
throwError({}, Messages.InvalidLHSInAssignment);
}
reinterpretAsAssignmentBindingPattern(property.value);
}
}
} else if (expr.type === Syntax.ArrayExpression) {
expr.type = Syntax.ArrayPattern;
for (i = 0, len = expr.elements.length; i < len; i += 1) {
element = expr.elements[i];
/* istanbul ignore else */
if (element) {
reinterpretAsAssignmentBindingPattern(element);
}
}
} else if (expr.type === Syntax.Identifier) {
if (isRestrictedWord(expr.name)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
} else if (expr.type === Syntax.SpreadElement) {
reinterpretAsAssignmentBindingPattern(expr.argument);
if (expr.argument.type === Syntax.ObjectPattern) {
throwError({}, Messages.ObjectPatternAsSpread);
}
} else {
/* istanbul ignore else */
if (expr.type !== Syntax.MemberExpression && expr.type !== Syntax.CallExpression && expr.type !== Syntax.NewExpression) {
throwError({}, Messages.InvalidLHSInAssignment);
}
}
}
// 13.2.3 BindingPattern
function reinterpretAsDestructuredParameter(options, expr) {
var i, len, property, element;
if (expr.type === Syntax.ObjectExpression) {
expr.type = Syntax.ObjectPattern;
for (i = 0, len = expr.properties.length; i < len; i += 1) {
property = expr.properties[i];
if (property.type === Syntax.SpreadProperty) {
if (i < len - 1) {
throwError({}, Messages.PropertyAfterSpreadProperty);
}
reinterpretAsDestructuredParameter(options, property.argument);
} else {
if (property.kind !== 'init') {
throwError({}, Messages.InvalidLHSInFormalsList);
}
reinterpretAsDestructuredParameter(options, property.value);
}
}
} else if (expr.type === Syntax.ArrayExpression) {
expr.type = Syntax.ArrayPattern;
for (i = 0, len = expr.elements.length; i < len; i += 1) {
element = expr.elements[i];
if (element) {
reinterpretAsDestructuredParameter(options, element);
}
}
} else if (expr.type === Syntax.Identifier) {
validateParam(options, expr, expr.name);
} else if (expr.type === Syntax.SpreadElement) {
// BindingRestElement only allows BindingIdentifier
if (expr.argument.type !== Syntax.Identifier) {
throwError({}, Messages.InvalidLHSInFormalsList);
}
validateParam(options, expr.argument, expr.argument.name);
} else {
throwError({}, Messages.InvalidLHSInFormalsList);
}
}
function reinterpretAsCoverFormalsList(expressions) {
var i, len, param, params, defaults, defaultCount, options, rest;
params = [];
defaults = [];
defaultCount = 0;
rest = null;
options = {
paramSet: new StringMap()
};
for (i = 0, len = expressions.length; i < len; i += 1) {
param = expressions[i];
if (param.type === Syntax.Identifier) {
params.push(param);
defaults.push(null);
validateParam(options, param, param.name);
} else if (param.type === Syntax.ObjectExpression || param.type === Syntax.ArrayExpression) {
reinterpretAsDestructuredParameter(options, param);
params.push(param);
defaults.push(null);
} else if (param.type === Syntax.SpreadElement) {
assert(i === len - 1, 'It is guaranteed that SpreadElement is last element by parseExpression');
if (param.argument.type !== Syntax.Identifier) {
throwError({}, Messages.InvalidLHSInFormalsList);
}
reinterpretAsDestructuredParameter(options, param.argument);
rest = param.argument;
} else if (param.type === Syntax.AssignmentExpression) {
params.push(param.left);
defaults.push(param.right);
++defaultCount;
validateParam(options, param.left, param.left.name);
} else {
return null;
}
}
if (options.message === Messages.StrictParamDupe) {
throwError(
strict ? options.stricted : options.firstRestricted,
options.message
);
}
if (defaultCount === 0) {
defaults = [];
}
return {
params: params,
defaults: defaults,
rest: rest,
stricted: options.stricted,
firstRestricted: options.firstRestricted,
message: options.message
};
}
function parseArrowFunctionExpression(options, marker) {
var previousStrict, previousYieldAllowed, previousAwaitAllowed, body;
expect('=>');
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = false;
previousAwaitAllowed = state.awaitAllowed;
state.awaitAllowed = !!options.async;
body = parseConciseBody();
if (strict && options.firstRestricted) {
throwError(options.firstRestricted, options.message);
}
if (strict && options.stricted) {
throwErrorTolerant(options.stricted, options.message);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
state.awaitAllowed = previousAwaitAllowed;
return markerApply(marker, delegate.createArrowFunctionExpression(
options.params,
options.defaults,
body,
options.rest,
body.type !== Syntax.BlockStatement,
!!options.async
));
}
function parseAssignmentExpression() {
var marker, expr, token, params, oldParenthesizedCount,
startsWithParen = false, backtrackToken = lookahead,
possiblyAsync = false;
if (matchYield()) {
return parseYieldExpression();
}
if (matchAwait()) {
return parseAwaitExpression();
}
oldParenthesizedCount = state.parenthesizedCount;
marker = markerCreate();
if (matchAsyncFuncExprOrDecl()) {
return parseFunctionExpression();
}
if (matchAsync()) {
// We can't be completely sure that this 'async' token is
// actually a contextual keyword modifying a function
// expression, so we might have to un-lex() it later by
// calling rewind(backtrackToken).
possiblyAsync = true;
lex();
}
if (match('(')) {
token = lookahead2();
if ((token.type === Token.Punctuator && token.value === ')') || token.value === '...') {
params = parseParams();
if (!match('=>')) {
throwUnexpected(lex());
}
params.async = possiblyAsync;
return parseArrowFunctionExpression(params, marker);
}
startsWithParen = true;
}
token = lookahead;
// If the 'async' keyword is not followed by a '(' character or an
// identifier, then it can't be an arrow function modifier, and we
// should interpret it as a normal identifer.
if (possiblyAsync && !match('(') && token.type !== Token.Identifier) {
possiblyAsync = false;
rewind(backtrackToken);
}
expr = parseConditionalExpression();
if (match('=>') &&
(state.parenthesizedCount === oldParenthesizedCount ||
state.parenthesizedCount === (oldParenthesizedCount + 1))) {
if (expr.type === Syntax.Identifier) {
params = reinterpretAsCoverFormalsList([ expr ]);
} else if (expr.type === Syntax.AssignmentExpression ||
expr.type === Syntax.ArrayExpression ||
expr.type === Syntax.ObjectExpression) {
if (!startsWithParen) {
throwUnexpected(lex());
}
params = reinterpretAsCoverFormalsList([ expr ]);
} else if (expr.type === Syntax.SequenceExpression) {
params = reinterpretAsCoverFormalsList(expr.expressions);
}
if (params) {
params.async = possiblyAsync;
return parseArrowFunctionExpression(params, marker);
}
}
// If we haven't returned by now, then the 'async' keyword was not
// a function modifier, and we should rewind and interpret it as a
// normal identifier.
if (possiblyAsync) {
possiblyAsync = false;
rewind(backtrackToken);
expr = parseConditionalExpression();
}
if (matchAssign()) {
// 11.13.1
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
throwErrorTolerant(token, Messages.StrictLHSAssignment);
}
// ES.next draf 11.13 Runtime Semantics step 1
if (match('=') && (expr.type === Syntax.ObjectExpression || expr.type === Syntax.ArrayExpression)) {
reinterpretAsAssignmentBindingPattern(expr);
} else if (!isLeftHandSide(expr)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
expr = markerApply(marker, delegate.createAssignmentExpression(lex().value, expr, parseAssignmentExpression()));
}
return expr;
}
// 11.14 Comma Operator
function parseExpression() {
var marker, expr, expressions, sequence, spreadFound;
marker = markerCreate();
expr = parseAssignmentExpression();
expressions = [ expr ];
if (match(',')) {
while (index < length) {
if (!match(',')) {
break;
}
lex();
expr = parseSpreadOrAssignmentExpression();
expressions.push(expr);
if (expr.type === Syntax.SpreadElement) {
spreadFound = true;
if (!match(')')) {
throwError({}, Messages.ElementAfterSpreadElement);
}
break;
}
}
sequence = markerApply(marker, delegate.createSequenceExpression(expressions));
}
if (spreadFound && lookahead2().value !== '=>') {
throwError({}, Messages.IllegalSpread);
}
return sequence || expr;
}
// 12.1 Block
function parseStatementList() {
var list = [],
statement;
while (index < length) {
if (match('}')) {
break;
}
statement = parseSourceElement();
if (typeof statement === 'undefined') {
break;
}
list.push(statement);
}
return list;
}
function parseBlock() {
var block, marker = markerCreate();
expect('{');
block = parseStatementList();
expect('}');
return markerApply(marker, delegate.createBlockStatement(block));
}
// 12.2 Variable Statement
function parseTypeParameterDeclaration() {
var marker = markerCreate(), paramTypes = [];
expect('<');
while (!match('>')) {
paramTypes.push(parseTypeAnnotatableIdentifier());
if (!match('>')) {
expect(',');
}
}
expect('>');
return markerApply(marker, delegate.createTypeParameterDeclaration(
paramTypes
));
}
function parseTypeParameterInstantiation() {
var marker = markerCreate(), oldInType = state.inType, paramTypes = [];
state.inType = true;
expect('<');
while (!match('>')) {
paramTypes.push(parseType());
if (!match('>')) {
expect(',');
}
}
expect('>');
state.inType = oldInType;
return markerApply(marker, delegate.createTypeParameterInstantiation(
paramTypes
));
}
function parseObjectTypeIndexer(marker, isStatic) {
var id, key, value;
expect('[');
id = parseObjectPropertyKey();
expect(':');
key = parseType();
expect(']');
expect(':');
value = parseType();
return markerApply(marker, delegate.createObjectTypeIndexer(
id,
key,
value,
isStatic
));
}
function parseObjectTypeMethodish(marker) {
var params = [], rest = null, returnType, typeParameters = null;
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
expect('(');
while (lookahead.type === Token.Identifier) {
params.push(parseFunctionTypeParam());
if (!match(')')) {
expect(',');
}
}
if (match('...')) {
lex();
rest = parseFunctionTypeParam();
}
expect(')');
expect(':');
returnType = parseType();
return markerApply(marker, delegate.createFunctionTypeAnnotation(
params,
returnType,
rest,
typeParameters
));
}
function parseObjectTypeMethod(marker, isStatic, key) {
var optional = false, value;
value = parseObjectTypeMethodish(marker);
return markerApply(marker, delegate.createObjectTypeProperty(
key,
value,
optional,
isStatic
));
}
function parseObjectTypeCallProperty(marker, isStatic) {
var valueMarker = markerCreate();
return markerApply(marker, delegate.createObjectTypeCallProperty(
parseObjectTypeMethodish(valueMarker),
isStatic
));
}
function parseObjectType(allowStatic) {
var callProperties = [], indexers = [], marker, optional = false,
properties = [], propertyKey, propertyTypeAnnotation,
token, isStatic, matchStatic;
expect('{');
while (!match('}')) {
marker = markerCreate();
matchStatic =
strict
? matchKeyword('static')
: matchContextualKeyword('static');
if (allowStatic && matchStatic) {
token = lex();
isStatic = true;
}
if (match('[')) {
indexers.push(parseObjectTypeIndexer(marker, isStatic));
} else if (match('(') || match('<')) {
callProperties.push(parseObjectTypeCallProperty(marker, allowStatic));
} else {
if (isStatic && match(':')) {
propertyKey = markerApply(marker, delegate.createIdentifier(token));
throwErrorTolerant(token, Messages.StrictReservedWord);
} else {
propertyKey = parseObjectPropertyKey();
}
if (match('<') || match('(')) {
// This is a method property
properties.push(parseObjectTypeMethod(marker, isStatic, propertyKey));
} else {
if (match('?')) {
lex();
optional = true;
}
expect(':');
propertyTypeAnnotation = parseType();
properties.push(markerApply(marker, delegate.createObjectTypeProperty(
propertyKey,
propertyTypeAnnotation,
optional,
isStatic
)));
}
}
if (match(';')) {
lex();
} else if (!match('}')) {
throwUnexpected(lookahead);
}
}
expect('}');
return delegate.createObjectTypeAnnotation(
properties,
indexers,
callProperties
);
}
function parseGenericType() {
var marker = markerCreate(),
typeParameters = null, typeIdentifier;
typeIdentifier = parseVariableIdentifier();
while (match('.')) {
expect('.');
typeIdentifier = markerApply(marker, delegate.createQualifiedTypeIdentifier(
typeIdentifier,
parseVariableIdentifier()
));
}
if (match('<')) {
typeParameters = parseTypeParameterInstantiation();
}
return markerApply(marker, delegate.createGenericTypeAnnotation(
typeIdentifier,
typeParameters
));
}
function parseVoidType() {
var marker = markerCreate();
expectKeyword('void');
return markerApply(marker, delegate.createVoidTypeAnnotation());
}
function parseTypeofType() {
var argument, marker = markerCreate();
expectKeyword('typeof');
argument = parsePrimaryType();
return markerApply(marker, delegate.createTypeofTypeAnnotation(
argument
));
}
function parseTupleType() {
var marker = markerCreate(), types = [];
expect('[');
// We allow trailing commas
while (index < length && !match(']')) {
types.push(parseType());
if (match(']')) {
break;
}
expect(',');
}
expect(']');
return markerApply(marker, delegate.createTupleTypeAnnotation(
types
));
}
function parseFunctionTypeParam() {
var marker = markerCreate(), name, optional = false, typeAnnotation;
name = parseVariableIdentifier();
if (match('?')) {
lex();
optional = true;
}
expect(':');
typeAnnotation = parseType();
return markerApply(marker, delegate.createFunctionTypeParam(
name,
typeAnnotation,
optional
));
}
function parseFunctionTypeParams() {
var ret = { params: [], rest: null };
while (lookahead.type === Token.Identifier) {
ret.params.push(parseFunctionTypeParam());
if (!match(')')) {
expect(',');
}
}
if (match('...')) {
lex();
ret.rest = parseFunctionTypeParam();
}
return ret;
}
// The parsing of types roughly parallels the parsing of expressions, and
// primary types are kind of like primary expressions...they're the
// primitives with which other types are constructed.
function parsePrimaryType() {
var params = null, returnType = null,
marker = markerCreate(), rest = null, tmp,
typeParameters, token, type, isGroupedType = false;
switch (lookahead.type) {
case Token.Identifier:
switch (lookahead.value) {
case 'any':
lex();
return markerApply(marker, delegate.createAnyTypeAnnotation());
case 'bool': // fallthrough
case 'boolean':
lex();
return markerApply(marker, delegate.createBooleanTypeAnnotation());
case 'number':
lex();
return markerApply(marker, delegate.createNumberTypeAnnotation());
case 'string':
lex();
return markerApply(marker, delegate.createStringTypeAnnotation());
}
return markerApply(marker, parseGenericType());
case Token.Punctuator:
switch (lookahead.value) {
case '{':
return markerApply(marker, parseObjectType());
case '[':
return parseTupleType();
case '<':
typeParameters = parseTypeParameterDeclaration();
expect('(');
tmp = parseFunctionTypeParams();
params = tmp.params;
rest = tmp.rest;
expect(')');
expect('=>');
returnType = parseType();
return markerApply(marker, delegate.createFunctionTypeAnnotation(
params,
returnType,
rest,
typeParameters
));
case '(':
lex();
// Check to see if this is actually a grouped type
if (!match(')') && !match('...')) {
if (lookahead.type === Token.Identifier) {
token = lookahead2();
isGroupedType = token.value !== '?' && token.value !== ':';
} else {
isGroupedType = true;
}
}
if (isGroupedType) {
type = parseType();
expect(')');
// If we see a => next then someone was probably confused about
// function types, so we can provide a better error message
if (match('=>')) {
throwError({}, Messages.ConfusedAboutFunctionType);
}
return type;
}
tmp = parseFunctionTypeParams();
params = tmp.params;
rest = tmp.rest;
expect(')');
expect('=>');
returnType = parseType();
return markerApply(marker, delegate.createFunctionTypeAnnotation(
params,
returnType,
rest,
null /* typeParameters */
));
}
break;
case Token.Keyword:
switch (lookahead.value) {
case 'void':
return markerApply(marker, parseVoidType());
case 'typeof':
return markerApply(marker, parseTypeofType());
}
break;
case Token.StringLiteral:
token = lex();
if (token.octal) {
throwError(token, Messages.StrictOctalLiteral);
}
return markerApply(marker, delegate.createStringLiteralTypeAnnotation(
token
));
}
throwUnexpected(lookahead);
}
function parsePostfixType() {
var marker = markerCreate(), t = parsePrimaryType();
if (match('[')) {
expect('[');
expect(']');
return markerApply(marker, delegate.createArrayTypeAnnotation(t));
}
return t;
}
function parsePrefixType() {
var marker = markerCreate();
if (match('?')) {
lex();
return markerApply(marker, delegate.createNullableTypeAnnotation(
parsePrefixType()
));
}
return parsePostfixType();
}
function parseIntersectionType() {
var marker = markerCreate(), type, types;
type = parsePrefixType();
types = [type];
while (match('&')) {
lex();
types.push(parsePrefixType());
}
return types.length === 1 ?
type :
markerApply(marker, delegate.createIntersectionTypeAnnotation(
types
));
}
function parseUnionType() {
var marker = markerCreate(), type, types;
type = parseIntersectionType();
types = [type];
while (match('|')) {
lex();
types.push(parseIntersectionType());
}
return types.length === 1 ?
type :
markerApply(marker, delegate.createUnionTypeAnnotation(
types
));
}
function parseType() {
var oldInType = state.inType, type;
state.inType = true;
type = parseUnionType();
state.inType = oldInType;
return type;
}
function parseTypeAnnotation() {
var marker = markerCreate(), type;
expect(':');
type = parseType();
return markerApply(marker, delegate.createTypeAnnotation(type));
}
function parseVariableIdentifier() {
var marker = markerCreate(),
token = lex();
if (token.type !== Token.Identifier) {
throwUnexpected(token);
}
return markerApply(marker, delegate.createIdentifier(token.value));
}
function parseTypeAnnotatableIdentifier(requireTypeAnnotation, canBeOptionalParam) {
var marker = markerCreate(),
ident = parseVariableIdentifier(),
isOptionalParam = false;
if (canBeOptionalParam && match('?')) {
expect('?');
isOptionalParam = true;
}
if (requireTypeAnnotation || match(':')) {
ident.typeAnnotation = parseTypeAnnotation();
ident = markerApply(marker, ident);
}
if (isOptionalParam) {
ident.optional = true;
ident = markerApply(marker, ident);
}
return ident;
}
function parseVariableDeclaration(kind) {
var id,
marker = markerCreate(),
init = null,
typeAnnotationMarker = markerCreate();
if (match('{')) {
id = parseObjectInitialiser();
reinterpretAsAssignmentBindingPattern(id);
if (match(':')) {
id.typeAnnotation = parseTypeAnnotation();
markerApply(typeAnnotationMarker, id);
}
} else if (match('[')) {
id = parseArrayInitialiser();
reinterpretAsAssignmentBindingPattern(id);
if (match(':')) {
id.typeAnnotation = parseTypeAnnotation();
markerApply(typeAnnotationMarker, id);
}
} else {
/* istanbul ignore next */
id = state.allowKeyword ? parseNonComputedProperty() : parseTypeAnnotatableIdentifier();
// 12.2.1
if (strict && isRestrictedWord(id.name)) {
throwErrorTolerant({}, Messages.StrictVarName);
}
}
if (kind === 'const') {
if (!match('=')) {
throwError({}, Messages.NoUninitializedConst);
}
expect('=');
init = parseAssignmentExpression();
} else if (match('=')) {
lex();
init = parseAssignmentExpression();
}
return markerApply(marker, delegate.createVariableDeclarator(id, init));
}
function parseVariableDeclarationList(kind) {
var list = [];
do {
list.push(parseVariableDeclaration(kind));
if (!match(',')) {
break;
}
lex();
} while (index < length);
return list;
}
function parseVariableStatement() {
var declarations, marker = markerCreate();
expectKeyword('var');
declarations = parseVariableDeclarationList();
consumeSemicolon();
return markerApply(marker, delegate.createVariableDeclaration(declarations, 'var'));
}
// kind may be `const` or `let`
// Both are experimental and not in the specification yet.
// see http://wiki.ecmascript.org/doku.php?id=harmony:const
// and http://wiki.ecmascript.org/doku.php?id=harmony:let
function parseConstLetDeclaration(kind) {
var declarations, marker = markerCreate();
expectKeyword(kind);
declarations = parseVariableDeclarationList(kind);
consumeSemicolon();
return markerApply(marker, delegate.createVariableDeclaration(declarations, kind));
}
// people.mozilla.org/~jorendorff/es6-draft.html
function parseModuleSpecifier() {
var marker = markerCreate(),
specifier;
if (lookahead.type !== Token.StringLiteral) {
throwError({}, Messages.InvalidModuleSpecifier);
}
specifier = delegate.createModuleSpecifier(lookahead);
lex();
return markerApply(marker, specifier);
}
function parseExportBatchSpecifier() {
var marker = markerCreate();
expect('*');
return markerApply(marker, delegate.createExportBatchSpecifier());
}
function parseExportSpecifier() {
var id, name = null, marker = markerCreate(), from;
if (matchKeyword('default')) {
lex();
id = markerApply(marker, delegate.createIdentifier('default'));
// export {default} from "something";
} else {
id = parseVariableIdentifier();
}
if (matchContextualKeyword('as')) {
lex();
name = parseNonComputedProperty();
}
return markerApply(marker, delegate.createExportSpecifier(id, name));
}
function parseExportDeclaration() {
var declaration = null,
possibleIdentifierToken, sourceElement,
isExportFromIdentifier,
src = null, specifiers = [],
marker = markerCreate();
expectKeyword('export');
if (matchKeyword('default')) {
// covers:
// export default ...
lex();
if (matchKeyword('function') || matchKeyword('class')) {
possibleIdentifierToken = lookahead2();
if (isIdentifierName(possibleIdentifierToken)) {
// covers:
// export default function foo () {}
// export default class foo {}
sourceElement = parseSourceElement();
return markerApply(marker, delegate.createExportDeclaration(true, sourceElement, [sourceElement.id], null));
}
// covers:
// export default function () {}
// export default class {}
switch (lookahead.value) {
case 'class':
return markerApply(marker, delegate.createExportDeclaration(true, parseClassExpression(), [], null));
case 'function':
return markerApply(marker, delegate.createExportDeclaration(true, parseFunctionExpression(), [], null));
}
}
if (matchContextualKeyword('from')) {
throwError({}, Messages.UnexpectedToken, lookahead.value);
}
// covers:
// export default {};
// export default [];
if (match('{')) {
declaration = parseObjectInitialiser();
} else if (match('[')) {
declaration = parseArrayInitialiser();
} else {
declaration = parseAssignmentExpression();
}
consumeSemicolon();
return markerApply(marker, delegate.createExportDeclaration(true, declaration, [], null));
}
// non-default export
if (lookahead.type === Token.Keyword || matchContextualKeyword('type')) {
// covers:
// export var f = 1;
switch (lookahead.value) {
case 'type':
case 'let':
case 'const':
case 'var':
case 'class':
case 'function':
return markerApply(marker, delegate.createExportDeclaration(false, parseSourceElement(), specifiers, null));
}
}
if (match('*')) {
// covers:
// export * from "foo";
specifiers.push(parseExportBatchSpecifier());
if (!matchContextualKeyword('from')) {
throwError({}, lookahead.value ?
Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
}
lex();
src = parseModuleSpecifier();
consumeSemicolon();
return markerApply(marker, delegate.createExportDeclaration(false, null, specifiers, src));
}
expect('{');
if (!match('}')) {
do {
isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default');
specifiers.push(parseExportSpecifier());
} while (match(',') && lex());
}
expect('}');
if (matchContextualKeyword('from')) {
// covering:
// export {default} from "foo";
// export {foo} from "foo";
lex();
src = parseModuleSpecifier();
consumeSemicolon();
} else if (isExportFromIdentifier) {
// covering:
// export {default}; // missing fromClause
throwError({}, lookahead.value ?
Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
} else {
// cover
// export {foo};
consumeSemicolon();
}
return markerApply(marker, delegate.createExportDeclaration(false, declaration, specifiers, src));
}
function parseImportSpecifier() {
// import {<foo as bar>} ...;
var id, name = null, marker = markerCreate();
id = parseNonComputedProperty();
if (matchContextualKeyword('as')) {
lex();
name = parseVariableIdentifier();
}
return markerApply(marker, delegate.createImportSpecifier(id, name));
}
function parseNamedImports() {
var specifiers = [];
// {foo, bar as bas}
expect('{');
if (!match('}')) {
do {
specifiers.push(parseImportSpecifier());
} while (match(',') && lex());
}
expect('}');
return specifiers;
}
function parseImportDefaultSpecifier() {
// import <foo> ...;
var id, marker = markerCreate();
id = parseNonComputedProperty();
return markerApply(marker, delegate.createImportDefaultSpecifier(id));
}
function parseImportNamespaceSpecifier() {
// import <* as foo> ...;
var id, marker = markerCreate();
expect('*');
if (!matchContextualKeyword('as')) {
throwError({}, Messages.NoAsAfterImportNamespace);
}
lex();
id = parseNonComputedProperty();
return markerApply(marker, delegate.createImportNamespaceSpecifier(id));
}
function parseImportDeclaration() {
var specifiers, src, marker = markerCreate(), isType = false, token2;
expectKeyword('import');
if (matchContextualKeyword('type')) {
token2 = lookahead2();
if ((token2.type === Token.Identifier && token2.value !== 'from') ||
(token2.type === Token.Punctuator &&
(token2.value === '{' || token2.value === '*'))) {
isType = true;
lex();
}
}
specifiers = [];
if (lookahead.type === Token.StringLiteral) {
// covers:
// import "foo";
src = parseModuleSpecifier();
consumeSemicolon();
return markerApply(marker, delegate.createImportDeclaration(specifiers, src, isType));
}
if (!matchKeyword('default') && isIdentifierName(lookahead)) {
// covers:
// import foo
// import foo, ...
specifiers.push(parseImportDefaultSpecifier());
if (match(',')) {
lex();
}
}
if (match('*')) {
// covers:
// import foo, * as foo
// import * as foo
specifiers.push(parseImportNamespaceSpecifier());
} else if (match('{')) {
// covers:
// import foo, {bar}
// import {bar}
specifiers = specifiers.concat(parseNamedImports());
}
if (!matchContextualKeyword('from')) {
throwError({}, lookahead.value ?
Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
}
lex();
src = parseModuleSpecifier();
consumeSemicolon();
return markerApply(marker, delegate.createImportDeclaration(specifiers, src, isType));
}
// 12.3 Empty Statement
function parseEmptyStatement() {
var marker = markerCreate();
expect(';');
return markerApply(marker, delegate.createEmptyStatement());
}
// 12.4 Expression Statement
function parseExpressionStatement() {
var marker = markerCreate(), expr = parseExpression();
consumeSemicolon();
return markerApply(marker, delegate.createExpressionStatement(expr));
}
// 12.5 If statement
function parseIfStatement() {
var test, consequent, alternate, marker = markerCreate();
expectKeyword('if');
expect('(');
test = parseExpression();
expect(')');
consequent = parseStatement();
if (matchKeyword('else')) {
lex();
alternate = parseStatement();
} else {
alternate = null;
}
return markerApply(marker, delegate.createIfStatement(test, consequent, alternate));
}
// 12.6 Iteration Statements
function parseDoWhileStatement() {
var body, test, oldInIteration, marker = markerCreate();
expectKeyword('do');
oldInIteration = state.inIteration;
state.inIteration = true;
body = parseStatement();
state.inIteration = oldInIteration;
expectKeyword('while');
expect('(');
test = parseExpression();
expect(')');
if (match(';')) {
lex();
}
return markerApply(marker, delegate.createDoWhileStatement(body, test));
}
function parseWhileStatement() {
var test, body, oldInIteration, marker = markerCreate();
expectKeyword('while');
expect('(');
test = parseExpression();
expect(')');
oldInIteration = state.inIteration;
state.inIteration = true;
body = parseStatement();
state.inIteration = oldInIteration;
return markerApply(marker, delegate.createWhileStatement(test, body));
}
function parseForVariableDeclaration() {
var marker = markerCreate(),
token = lex(),
declarations = parseVariableDeclarationList();
return markerApply(marker, delegate.createVariableDeclaration(declarations, token.value));
}
function parseForStatement(opts) {
var init, test, update, left, right, body, operator, oldInIteration,
marker = markerCreate();
init = test = update = null;
expectKeyword('for');
// http://wiki.ecmascript.org/doku.php?id=proposals:iterators_and_generators&s=each
if (matchContextualKeyword('each')) {
throwError({}, Messages.EachNotAllowed);
}
expect('(');
if (match(';')) {
lex();
} else {
if (matchKeyword('var') || matchKeyword('let') || matchKeyword('const')) {
state.allowIn = false;
init = parseForVariableDeclaration();
state.allowIn = true;
if (init.declarations.length === 1) {
if (matchKeyword('in') || matchContextualKeyword('of')) {
operator = lookahead;
if (!((operator.value === 'in' || init.kind !== 'var') && init.declarations[0].init)) {
lex();
left = init;
right = parseExpression();
init = null;
}
}
}
} else {
state.allowIn = false;
init = parseExpression();
state.allowIn = true;
if (matchContextualKeyword('of')) {
operator = lex();
left = init;
right = parseExpression();
init = null;
} else if (matchKeyword('in')) {
// LeftHandSideExpression
if (!isAssignableLeftHandSide(init)) {
throwError({}, Messages.InvalidLHSInForIn);
}
operator = lex();
left = init;
right = parseExpression();
init = null;
}
}
if (typeof left === 'undefined') {
expect(';');
}
}
if (typeof left === 'undefined') {
if (!match(';')) {
test = parseExpression();
}
expect(';');
if (!match(')')) {
update = parseExpression();
}
}
expect(')');
oldInIteration = state.inIteration;
state.inIteration = true;
if (!(opts !== undefined && opts.ignoreBody)) {
body = parseStatement();
}
state.inIteration = oldInIteration;
if (typeof left === 'undefined') {
return markerApply(marker, delegate.createForStatement(init, test, update, body));
}
if (operator.value === 'in') {
return markerApply(marker, delegate.createForInStatement(left, right, body));
}
return markerApply(marker, delegate.createForOfStatement(left, right, body));
}
// 12.7 The continue statement
function parseContinueStatement() {
var label = null, marker = markerCreate();
expectKeyword('continue');
// Optimize the most common form: 'continue;'.
if (source.charCodeAt(index) === 59) {
lex();
if (!state.inIteration) {
throwError({}, Messages.IllegalContinue);
}
return markerApply(marker, delegate.createContinueStatement(null));
}
if (peekLineTerminator()) {
if (!state.inIteration) {
throwError({}, Messages.IllegalContinue);
}
return markerApply(marker, delegate.createContinueStatement(null));
}
if (lookahead.type === Token.Identifier) {
label = parseVariableIdentifier();
if (!state.labelSet.has(label.name)) {
throwError({}, Messages.UnknownLabel, label.name);
}
}
consumeSemicolon();
if (label === null && !state.inIteration) {
throwError({}, Messages.IllegalContinue);
}
return markerApply(marker, delegate.createContinueStatement(label));
}
// 12.8 The break statement
function parseBreakStatement() {
var label = null, marker = markerCreate();
expectKeyword('break');
// Catch the very common case first: immediately a semicolon (char #59).
if (source.charCodeAt(index) === 59) {
lex();
if (!(state.inIteration || state.inSwitch)) {
throwError({}, Messages.IllegalBreak);
}
return markerApply(marker, delegate.createBreakStatement(null));
}
if (peekLineTerminator()) {
if (!(state.inIteration || state.inSwitch)) {
throwError({}, Messages.IllegalBreak);
}
return markerApply(marker, delegate.createBreakStatement(null));
}
if (lookahead.type === Token.Identifier) {
label = parseVariableIdentifier();
if (!state.labelSet.has(label.name)) {
throwError({}, Messages.UnknownLabel, label.name);
}
}
consumeSemicolon();
if (label === null && !(state.inIteration || state.inSwitch)) {
throwError({}, Messages.IllegalBreak);
}
return markerApply(marker, delegate.createBreakStatement(label));
}
// 12.9 The return statement
function parseReturnStatement() {
var argument = null, marker = markerCreate();
expectKeyword('return');
if (!state.inFunctionBody) {
throwErrorTolerant({}, Messages.IllegalReturn);
}
// 'return' followed by a space and an identifier is very common.
if (source.charCodeAt(index) === 32) {
if (isIdentifierStart(source.charCodeAt(index + 1))) {
argument = parseExpression();
consumeSemicolon();
return markerApply(marker, delegate.createReturnStatement(argument));
}
}
if (peekLineTerminator()) {
return markerApply(marker, delegate.createReturnStatement(null));
}
if (!match(';')) {
if (!match('}') && lookahead.type !== Token.EOF) {
argument = parseExpression();
}
}
consumeSemicolon();
return markerApply(marker, delegate.createReturnStatement(argument));
}
// 12.10 The with statement
function parseWithStatement() {
var object, body, marker = markerCreate();
if (strict) {
throwErrorTolerant({}, Messages.StrictModeWith);
}
expectKeyword('with');
expect('(');
object = parseExpression();
expect(')');
body = parseStatement();
return markerApply(marker, delegate.createWithStatement(object, body));
}
// 12.10 The swith statement
function parseSwitchCase() {
var test,
consequent = [],
sourceElement,
marker = markerCreate();
if (matchKeyword('default')) {
lex();
test = null;
} else {
expectKeyword('case');
test = parseExpression();
}
expect(':');
while (index < length) {
if (match('}') || matchKeyword('default') || matchKeyword('case')) {
break;
}
sourceElement = parseSourceElement();
if (typeof sourceElement === 'undefined') {
break;
}
consequent.push(sourceElement);
}
return markerApply(marker, delegate.createSwitchCase(test, consequent));
}
function parseSwitchStatement() {
var discriminant, cases, clause, oldInSwitch, defaultFound, marker = markerCreate();
expectKeyword('switch');
expect('(');
discriminant = parseExpression();
expect(')');
expect('{');
cases = [];
if (match('}')) {
lex();
return markerApply(marker, delegate.createSwitchStatement(discriminant, cases));
}
oldInSwitch = state.inSwitch;
state.inSwitch = true;
defaultFound = false;
while (index < length) {
if (match('}')) {
break;
}
clause = parseSwitchCase();
if (clause.test === null) {
if (defaultFound) {
throwError({}, Messages.MultipleDefaultsInSwitch);
}
defaultFound = true;
}
cases.push(clause);
}
state.inSwitch = oldInSwitch;
expect('}');
return markerApply(marker, delegate.createSwitchStatement(discriminant, cases));
}
// 12.13 The throw statement
function parseThrowStatement() {
var argument, marker = markerCreate();
expectKeyword('throw');
if (peekLineTerminator()) {
throwError({}, Messages.NewlineAfterThrow);
}
argument = parseExpression();
consumeSemicolon();
return markerApply(marker, delegate.createThrowStatement(argument));
}
// 12.14 The try statement
function parseCatchClause() {
var param, body, marker = markerCreate();
expectKeyword('catch');
expect('(');
if (match(')')) {
throwUnexpected(lookahead);
}
param = parseExpression();
// 12.14.1
if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) {
throwErrorTolerant({}, Messages.StrictCatchVariable);
}
expect(')');
body = parseBlock();
return markerApply(marker, delegate.createCatchClause(param, body));
}
function parseTryStatement() {
var block, handlers = [], finalizer = null, marker = markerCreate();
expectKeyword('try');
block = parseBlock();
if (matchKeyword('catch')) {
handlers.push(parseCatchClause());
}
if (matchKeyword('finally')) {
lex();
finalizer = parseBlock();
}
if (handlers.length === 0 && !finalizer) {
throwError({}, Messages.NoCatchOrFinally);
}
return markerApply(marker, delegate.createTryStatement(block, [], handlers, finalizer));
}
// 12.15 The debugger statement
function parseDebuggerStatement() {
var marker = markerCreate();
expectKeyword('debugger');
consumeSemicolon();
return markerApply(marker, delegate.createDebuggerStatement());
}
// 12 Statements
function parseStatement() {
var type = lookahead.type,
marker,
expr,
labeledBody;
if (type === Token.EOF) {
throwUnexpected(lookahead);
}
if (type === Token.Punctuator) {
switch (lookahead.value) {
case ';':
return parseEmptyStatement();
case '{':
return parseBlock();
case '(':
return parseExpressionStatement();
default:
break;
}
}
if (type === Token.Keyword) {
switch (lookahead.value) {
case 'break':
return parseBreakStatement();
case 'continue':
return parseContinueStatement();
case 'debugger':
return parseDebuggerStatement();
case 'do':
return parseDoWhileStatement();
case 'for':
return parseForStatement();
case 'function':
return parseFunctionDeclaration();
case 'class':
return parseClassDeclaration();
case 'if':
return parseIfStatement();
case 'return':
return parseReturnStatement();
case 'switch':
return parseSwitchStatement();
case 'throw':
return parseThrowStatement();
case 'try':
return parseTryStatement();
case 'var':
return parseVariableStatement();
case 'while':
return parseWhileStatement();
case 'with':
return parseWithStatement();
default:
break;
}
}
if (matchAsyncFuncExprOrDecl()) {
return parseFunctionDeclaration();
}
marker = markerCreate();
expr = parseExpression();
// 12.12 Labelled Statements
if ((expr.type === Syntax.Identifier) && match(':')) {
lex();
if (state.labelSet.has(expr.name)) {
throwError({}, Messages.Redeclaration, 'Label', expr.name);
}
state.labelSet.set(expr.name, true);
labeledBody = parseStatement();
state.labelSet["delete"](expr.name);
return markerApply(marker, delegate.createLabeledStatement(expr, labeledBody));
}
consumeSemicolon();
return markerApply(marker, delegate.createExpressionStatement(expr));
}
// 13 Function Definition
function parseConciseBody() {
if (match('{')) {
return parseFunctionSourceElements();
}
return parseAssignmentExpression();
}
function parseFunctionSourceElements() {
var sourceElement, sourceElements = [], token, directive, firstRestricted,
oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesizedCount,
marker = markerCreate();
expect('{');
while (index < length) {
if (lookahead.type !== Token.StringLiteral) {
break;
}
token = lookahead;
sourceElement = parseSourceElement();
sourceElements.push(sourceElement);
if (sourceElement.expression.type !== Syntax.Literal) {
// this is not directive
break;
}
directive = source.slice(token.range[0] + 1, token.range[1] - 1);
if (directive === 'use strict') {
strict = true;
if (firstRestricted) {
throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
}
} else {
if (!firstRestricted && token.octal) {
firstRestricted = token;
}
}
}
oldLabelSet = state.labelSet;
oldInIteration = state.inIteration;
oldInSwitch = state.inSwitch;
oldInFunctionBody = state.inFunctionBody;
oldParenthesizedCount = state.parenthesizedCount;
state.labelSet = new StringMap();
state.inIteration = false;
state.inSwitch = false;
state.inFunctionBody = true;
state.parenthesizedCount = 0;
while (index < length) {
if (match('}')) {
break;
}
sourceElement = parseSourceElement();
if (typeof sourceElement === 'undefined') {
break;
}
sourceElements.push(sourceElement);
}
expect('}');
state.labelSet = oldLabelSet;
state.inIteration = oldInIteration;
state.inSwitch = oldInSwitch;
state.inFunctionBody = oldInFunctionBody;
state.parenthesizedCount = oldParenthesizedCount;
return markerApply(marker, delegate.createBlockStatement(sourceElements));
}
function validateParam(options, param, name) {
if (strict) {
if (isRestrictedWord(name)) {
options.stricted = param;
options.message = Messages.StrictParamName;
}
if (options.paramSet.has(name)) {
options.stricted = param;
options.message = Messages.StrictParamDupe;
}
} else if (!options.firstRestricted) {
if (isRestrictedWord(name)) {
options.firstRestricted = param;
options.message = Messages.StrictParamName;
} else if (isStrictModeReservedWord(name)) {
options.firstRestricted = param;
options.message = Messages.StrictReservedWord;
} else if (options.paramSet.has(name)) {
options.firstRestricted = param;
options.message = Messages.StrictParamDupe;
}
}
options.paramSet.set(name, true);
}
function parseParam(options) {
var marker, token, rest, param, def;
token = lookahead;
if (token.value === '...') {
token = lex();
rest = true;
}
if (match('[')) {
marker = markerCreate();
param = parseArrayInitialiser();
reinterpretAsDestructuredParameter(options, param);
if (match(':')) {
param.typeAnnotation = parseTypeAnnotation();
markerApply(marker, param);
}
} else if (match('{')) {
marker = markerCreate();
if (rest) {
throwError({}, Messages.ObjectPatternAsRestParameter);
}
param = parseObjectInitialiser();
reinterpretAsDestructuredParameter(options, param);
if (match(':')) {
param.typeAnnotation = parseTypeAnnotation();
markerApply(marker, param);
}
} else {
param =
rest
? parseTypeAnnotatableIdentifier(
false, /* requireTypeAnnotation */
false /* canBeOptionalParam */
)
: parseTypeAnnotatableIdentifier(
false, /* requireTypeAnnotation */
true /* canBeOptionalParam */
);
validateParam(options, token, token.value);
}
if (match('=')) {
if (rest) {
throwErrorTolerant(lookahead, Messages.DefaultRestParameter);
}
lex();
def = parseAssignmentExpression();
++options.defaultCount;
}
if (rest) {
if (!match(')')) {
throwError({}, Messages.ParameterAfterRestParameter);
}
options.rest = param;
return false;
}
options.params.push(param);
options.defaults.push(def);
return !match(')');
}
function parseParams(firstRestricted) {
var options, marker = markerCreate();
options = {
params: [],
defaultCount: 0,
defaults: [],
rest: null,
firstRestricted: firstRestricted
};
expect('(');
if (!match(')')) {
options.paramSet = new StringMap();
while (index < length) {
if (!parseParam(options)) {
break;
}
expect(',');
}
}
expect(')');
if (options.defaultCount === 0) {
options.defaults = [];
}
if (match(':')) {
options.returnType = parseTypeAnnotation();
}
return markerApply(marker, options);
}
function parseFunctionDeclaration() {
var id, body, token, tmp, firstRestricted, message, generator, isAsync,
previousStrict, previousYieldAllowed, previousAwaitAllowed,
marker = markerCreate(), typeParameters;
isAsync = false;
if (matchAsync()) {
lex();
isAsync = true;
}
expectKeyword('function');
generator = false;
if (match('*')) {
lex();
generator = true;
}
token = lookahead;
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
if (strict) {
if (isRestrictedWord(token.value)) {
throwErrorTolerant(token, Messages.StrictFunctionName);
}
} else {
if (isRestrictedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictFunctionName;
} else if (isStrictModeReservedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictReservedWord;
}
}
tmp = parseParams(firstRestricted);
firstRestricted = tmp.firstRestricted;
if (tmp.message) {
message = tmp.message;
}
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = generator;
previousAwaitAllowed = state.awaitAllowed;
state.awaitAllowed = isAsync;
body = parseFunctionSourceElements();
if (strict && firstRestricted) {
throwError(firstRestricted, message);
}
if (strict && tmp.stricted) {
throwErrorTolerant(tmp.stricted, message);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
state.awaitAllowed = previousAwaitAllowed;
return markerApply(
marker,
delegate.createFunctionDeclaration(
id,
tmp.params,
tmp.defaults,
body,
tmp.rest,
generator,
false,
isAsync,
tmp.returnType,
typeParameters
)
);
}
function parseFunctionExpression() {
var token, id = null, firstRestricted, message, tmp, body, generator, isAsync,
previousStrict, previousYieldAllowed, previousAwaitAllowed,
marker = markerCreate(), typeParameters;
isAsync = false;
if (matchAsync()) {
lex();
isAsync = true;
}
expectKeyword('function');
generator = false;
if (match('*')) {
lex();
generator = true;
}
if (!match('(')) {
if (!match('<')) {
token = lookahead;
id = parseVariableIdentifier();
if (strict) {
if (isRestrictedWord(token.value)) {
throwErrorTolerant(token, Messages.StrictFunctionName);
}
} else {
if (isRestrictedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictFunctionName;
} else if (isStrictModeReservedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictReservedWord;
}
}
}
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
}
tmp = parseParams(firstRestricted);
firstRestricted = tmp.firstRestricted;
if (tmp.message) {
message = tmp.message;
}
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = generator;
previousAwaitAllowed = state.awaitAllowed;
state.awaitAllowed = isAsync;
body = parseFunctionSourceElements();
if (strict && firstRestricted) {
throwError(firstRestricted, message);
}
if (strict && tmp.stricted) {
throwErrorTolerant(tmp.stricted, message);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
state.awaitAllowed = previousAwaitAllowed;
return markerApply(
marker,
delegate.createFunctionExpression(
id,
tmp.params,
tmp.defaults,
body,
tmp.rest,
generator,
false,
isAsync,
tmp.returnType,
typeParameters
)
);
}
function parseYieldExpression() {
var delegateFlag, expr, marker = markerCreate();
expectKeyword('yield', !strict);
delegateFlag = false;
if (match('*')) {
lex();
delegateFlag = true;
}
expr = parseAssignmentExpression();
return markerApply(marker, delegate.createYieldExpression(expr, delegateFlag));
}
function parseAwaitExpression() {
var expr, marker = markerCreate();
expectContextualKeyword('await');
expr = parseAssignmentExpression();
return markerApply(marker, delegate.createAwaitExpression(expr));
}
// 14 Functions and classes
// 14.1 Functions is defined above (13 in ES5)
// 14.2 Arrow Functions Definitions is defined in (7.3 assignments)
// 14.3 Method Definitions
// 14.3.7
function specialMethod(methodDefinition) {
return methodDefinition.kind === 'get' ||
methodDefinition.kind === 'set' ||
methodDefinition.value.generator;
}
function parseMethodDefinition(key, isStatic, generator, computed) {
var token, param, propType,
isAsync, typeParameters, tokenValue, returnType;
propType = isStatic ? ClassPropertyType["static"] : ClassPropertyType.prototype;
if (generator) {
return delegate.createMethodDefinition(
propType,
'',
key,
parsePropertyMethodFunction({ generator: true }),
computed
);
}
tokenValue = key.type === 'Identifier' && key.name;
if (tokenValue === 'get' && !match('(')) {
key = parseObjectPropertyKey();
expect('(');
expect(')');
if (match(':')) {
returnType = parseTypeAnnotation();
}
return delegate.createMethodDefinition(
propType,
'get',
key,
parsePropertyFunction({ generator: false, returnType: returnType }),
computed
);
}
if (tokenValue === 'set' && !match('(')) {
key = parseObjectPropertyKey();
expect('(');
token = lookahead;
param = [ parseTypeAnnotatableIdentifier() ];
expect(')');
if (match(':')) {
returnType = parseTypeAnnotation();
}
return delegate.createMethodDefinition(
propType,
'set',
key,
parsePropertyFunction({
params: param,
generator: false,
name: token,
returnType: returnType
}),
computed
);
}
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
isAsync = tokenValue === 'async' && !match('(');
if (isAsync) {
key = parseObjectPropertyKey();
}
return delegate.createMethodDefinition(
propType,
'',
key,
parsePropertyMethodFunction({
generator: false,
async: isAsync,
typeParameters: typeParameters
}),
computed
);
}
function parseClassProperty(key, computed, isStatic) {
var typeAnnotation;
typeAnnotation = parseTypeAnnotation();
expect(';');
return delegate.createClassProperty(
key,
typeAnnotation,
computed,
isStatic
);
}
function parseClassElement() {
var computed = false, generator = false, key, marker = markerCreate(),
isStatic = false, possiblyOpenBracketToken;
if (match(';')) {
lex();
return undefined;
}
if (lookahead.value === 'static') {
lex();
isStatic = true;
}
if (match('*')) {
lex();
generator = true;
}
possiblyOpenBracketToken = lookahead;
if (matchContextualKeyword('get') || matchContextualKeyword('set')) {
possiblyOpenBracketToken = lookahead2();
}
if (possiblyOpenBracketToken.type === Token.Punctuator
&& possiblyOpenBracketToken.value === '[') {
computed = true;
}
key = parseObjectPropertyKey();
if (!generator && lookahead.value === ':') {
return markerApply(marker, parseClassProperty(key, computed, isStatic));
}
return markerApply(marker, parseMethodDefinition(
key,
isStatic,
generator,
computed
));
}
function parseClassBody() {
var classElement, classElements = [], existingProps = {},
marker = markerCreate(), propName, propType;
existingProps[ClassPropertyType["static"]] = new StringMap();
existingProps[ClassPropertyType.prototype] = new StringMap();
expect('{');
while (index < length) {
if (match('}')) {
break;
}
classElement = parseClassElement(existingProps);
if (typeof classElement !== 'undefined') {
classElements.push(classElement);
propName = !classElement.computed && getFieldName(classElement.key);
if (propName !== false) {
propType = classElement["static"] ?
ClassPropertyType["static"] :
ClassPropertyType.prototype;
if (classElement.type === Syntax.MethodDefinition) {
if (propName === 'constructor' && !classElement["static"]) {
if (specialMethod(classElement)) {
throwError(classElement, Messages.IllegalClassConstructorProperty);
}
if (existingProps[ClassPropertyType.prototype].has('constructor')) {
throwError(classElement.key, Messages.IllegalDuplicateClassProperty);
}
}
existingProps[propType].set(propName, true);
}
}
}
}
expect('}');
return markerApply(marker, delegate.createClassBody(classElements));
}
function parseClassImplements() {
var id, implemented = [], marker, typeParameters;
if (strict) {
expectKeyword('implements');
} else {
expectContextualKeyword('implements');
}
while (index < length) {
marker = markerCreate();
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterInstantiation();
} else {
typeParameters = null;
}
implemented.push(markerApply(marker, delegate.createClassImplements(
id,
typeParameters
)));
if (!match(',')) {
break;
}
expect(',');
}
return implemented;
}
function parseClassExpression() {
var id, implemented, previousYieldAllowed, superClass = null,
superTypeParameters, marker = markerCreate(), typeParameters,
matchImplements;
expectKeyword('class');
matchImplements =
strict
? matchKeyword('implements')
: matchContextualKeyword('implements');
if (!matchKeyword('extends') && !matchImplements && !match('{')) {
id = parseVariableIdentifier();
}
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
if (matchKeyword('extends')) {
expectKeyword('extends');
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = false;
superClass = parseLeftHandSideExpressionAllowCall();
if (match('<')) {
superTypeParameters = parseTypeParameterInstantiation();
}
state.yieldAllowed = previousYieldAllowed;
}
if (strict ? matchKeyword('implements') : matchContextualKeyword('implements')) {
implemented = parseClassImplements();
}
return markerApply(marker, delegate.createClassExpression(
id,
superClass,
parseClassBody(),
typeParameters,
superTypeParameters,
implemented
));
}
function parseClassDeclaration() {
var id, implemented, previousYieldAllowed, superClass = null,
superTypeParameters, marker = markerCreate(), typeParameters;
expectKeyword('class');
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
if (matchKeyword('extends')) {
expectKeyword('extends');
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = false;
superClass = parseLeftHandSideExpressionAllowCall();
if (match('<')) {
superTypeParameters = parseTypeParameterInstantiation();
}
state.yieldAllowed = previousYieldAllowed;
}
if (strict ? matchKeyword('implements') : matchContextualKeyword('implements')) {
implemented = parseClassImplements();
}
return markerApply(marker, delegate.createClassDeclaration(
id,
superClass,
parseClassBody(),
typeParameters,
superTypeParameters,
implemented
));
}
// 15 Program
function parseSourceElement() {
var token;
if (lookahead.type === Token.Keyword) {
switch (lookahead.value) {
case 'const':
case 'let':
return parseConstLetDeclaration(lookahead.value);
case 'function':
return parseFunctionDeclaration();
case 'export':
throwErrorTolerant({}, Messages.IllegalExportDeclaration);
return parseExportDeclaration();
case 'import':
throwErrorTolerant({}, Messages.IllegalImportDeclaration);
return parseImportDeclaration();
case 'interface':
if (lookahead2().type === Token.Identifier) {
return parseInterface();
}
return parseStatement();
default:
return parseStatement();
}
}
if (matchContextualKeyword('type')
&& lookahead2().type === Token.Identifier) {
return parseTypeAlias();
}
if (matchContextualKeyword('interface')
&& lookahead2().type === Token.Identifier) {
return parseInterface();
}
if (matchContextualKeyword('declare')) {
token = lookahead2();
if (token.type === Token.Keyword) {
switch (token.value) {
case 'class':
return parseDeclareClass();
case 'function':
return parseDeclareFunction();
case 'var':
return parseDeclareVariable();
}
} else if (token.type === Token.Identifier
&& token.value === 'module') {
return parseDeclareModule();
}
}
if (lookahead.type !== Token.EOF) {
return parseStatement();
}
}
function parseProgramElement() {
var isModule = extra.sourceType === 'module' || extra.sourceType === 'nonStrictModule';
if (isModule && lookahead.type === Token.Keyword) {
switch (lookahead.value) {
case 'export':
return parseExportDeclaration();
case 'import':
return parseImportDeclaration();
}
}
return parseSourceElement();
}
function parseProgramElements() {
var sourceElement, sourceElements = [], token, directive, firstRestricted;
while (index < length) {
token = lookahead;
if (token.type !== Token.StringLiteral) {
break;
}
sourceElement = parseProgramElement();
sourceElements.push(sourceElement);
if (sourceElement.expression.type !== Syntax.Literal) {
// this is not directive
break;
}
directive = source.slice(token.range[0] + 1, token.range[1] - 1);
if (directive === 'use strict') {
strict = true;
if (firstRestricted) {
throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
}
} else {
if (!firstRestricted && token.octal) {
firstRestricted = token;
}
}
}
while (index < length) {
sourceElement = parseProgramElement();
if (typeof sourceElement === 'undefined') {
break;
}
sourceElements.push(sourceElement);
}
return sourceElements;
}
function parseProgram() {
var body, marker = markerCreate();
strict = extra.sourceType === 'module';
peek();
body = parseProgramElements();
return markerApply(marker, delegate.createProgram(body));
}
// 16 JSX
XHTMLEntities = {
quot: '\u0022',
amp: '&',
apos: '\u0027',
lt: '<',
gt: '>',
nbsp: '\u00A0',
iexcl: '\u00A1',
cent: '\u00A2',
pound: '\u00A3',
curren: '\u00A4',
yen: '\u00A5',
brvbar: '\u00A6',
sect: '\u00A7',
uml: '\u00A8',
copy: '\u00A9',
ordf: '\u00AA',
laquo: '\u00AB',
not: '\u00AC',
shy: '\u00AD',
reg: '\u00AE',
macr: '\u00AF',
deg: '\u00B0',
plusmn: '\u00B1',
sup2: '\u00B2',
sup3: '\u00B3',
acute: '\u00B4',
micro: '\u00B5',
para: '\u00B6',
middot: '\u00B7',
cedil: '\u00B8',
sup1: '\u00B9',
ordm: '\u00BA',
raquo: '\u00BB',
frac14: '\u00BC',
frac12: '\u00BD',
frac34: '\u00BE',
iquest: '\u00BF',
Agrave: '\u00C0',
Aacute: '\u00C1',
Acirc: '\u00C2',
Atilde: '\u00C3',
Auml: '\u00C4',
Aring: '\u00C5',
AElig: '\u00C6',
Ccedil: '\u00C7',
Egrave: '\u00C8',
Eacute: '\u00C9',
Ecirc: '\u00CA',
Euml: '\u00CB',
Igrave: '\u00CC',
Iacute: '\u00CD',
Icirc: '\u00CE',
Iuml: '\u00CF',
ETH: '\u00D0',
Ntilde: '\u00D1',
Ograve: '\u00D2',
Oacute: '\u00D3',
Ocirc: '\u00D4',
Otilde: '\u00D5',
Ouml: '\u00D6',
times: '\u00D7',
Oslash: '\u00D8',
Ugrave: '\u00D9',
Uacute: '\u00DA',
Ucirc: '\u00DB',
Uuml: '\u00DC',
Yacute: '\u00DD',
THORN: '\u00DE',
szlig: '\u00DF',
agrave: '\u00E0',
aacute: '\u00E1',
acirc: '\u00E2',
atilde: '\u00E3',
auml: '\u00E4',
aring: '\u00E5',
aelig: '\u00E6',
ccedil: '\u00E7',
egrave: '\u00E8',
eacute: '\u00E9',
ecirc: '\u00EA',
euml: '\u00EB',
igrave: '\u00EC',
iacute: '\u00ED',
icirc: '\u00EE',
iuml: '\u00EF',
eth: '\u00F0',
ntilde: '\u00F1',
ograve: '\u00F2',
oacute: '\u00F3',
ocirc: '\u00F4',
otilde: '\u00F5',
ouml: '\u00F6',
divide: '\u00F7',
oslash: '\u00F8',
ugrave: '\u00F9',
uacute: '\u00FA',
ucirc: '\u00FB',
uuml: '\u00FC',
yacute: '\u00FD',
thorn: '\u00FE',
yuml: '\u00FF',
OElig: '\u0152',
oelig: '\u0153',
Scaron: '\u0160',
scaron: '\u0161',
Yuml: '\u0178',
fnof: '\u0192',
circ: '\u02C6',
tilde: '\u02DC',
Alpha: '\u0391',
Beta: '\u0392',
Gamma: '\u0393',
Delta: '\u0394',
Epsilon: '\u0395',
Zeta: '\u0396',
Eta: '\u0397',
Theta: '\u0398',
Iota: '\u0399',
Kappa: '\u039A',
Lambda: '\u039B',
Mu: '\u039C',
Nu: '\u039D',
Xi: '\u039E',
Omicron: '\u039F',
Pi: '\u03A0',
Rho: '\u03A1',
Sigma: '\u03A3',
Tau: '\u03A4',
Upsilon: '\u03A5',
Phi: '\u03A6',
Chi: '\u03A7',
Psi: '\u03A8',
Omega: '\u03A9',
alpha: '\u03B1',
beta: '\u03B2',
gamma: '\u03B3',
delta: '\u03B4',
epsilon: '\u03B5',
zeta: '\u03B6',
eta: '\u03B7',
theta: '\u03B8',
iota: '\u03B9',
kappa: '\u03BA',
lambda: '\u03BB',
mu: '\u03BC',
nu: '\u03BD',
xi: '\u03BE',
omicron: '\u03BF',
pi: '\u03C0',
rho: '\u03C1',
sigmaf: '\u03C2',
sigma: '\u03C3',
tau: '\u03C4',
upsilon: '\u03C5',
phi: '\u03C6',
chi: '\u03C7',
psi: '\u03C8',
omega: '\u03C9',
thetasym: '\u03D1',
upsih: '\u03D2',
piv: '\u03D6',
ensp: '\u2002',
emsp: '\u2003',
thinsp: '\u2009',
zwnj: '\u200C',
zwj: '\u200D',
lrm: '\u200E',
rlm: '\u200F',
ndash: '\u2013',
mdash: '\u2014',
lsquo: '\u2018',
rsquo: '\u2019',
sbquo: '\u201A',
ldquo: '\u201C',
rdquo: '\u201D',
bdquo: '\u201E',
dagger: '\u2020',
Dagger: '\u2021',
bull: '\u2022',
hellip: '\u2026',
permil: '\u2030',
prime: '\u2032',
Prime: '\u2033',
lsaquo: '\u2039',
rsaquo: '\u203A',
oline: '\u203E',
frasl: '\u2044',
euro: '\u20AC',
image: '\u2111',
weierp: '\u2118',
real: '\u211C',
trade: '\u2122',
alefsym: '\u2135',
larr: '\u2190',
uarr: '\u2191',
rarr: '\u2192',
darr: '\u2193',
harr: '\u2194',
crarr: '\u21B5',
lArr: '\u21D0',
uArr: '\u21D1',
rArr: '\u21D2',
dArr: '\u21D3',
hArr: '\u21D4',
forall: '\u2200',
part: '\u2202',
exist: '\u2203',
empty: '\u2205',
nabla: '\u2207',
isin: '\u2208',
notin: '\u2209',
ni: '\u220B',
prod: '\u220F',
sum: '\u2211',
minus: '\u2212',
lowast: '\u2217',
radic: '\u221A',
prop: '\u221D',
infin: '\u221E',
ang: '\u2220',
and: '\u2227',
or: '\u2228',
cap: '\u2229',
cup: '\u222A',
'int': '\u222B',
there4: '\u2234',
sim: '\u223C',
cong: '\u2245',
asymp: '\u2248',
ne: '\u2260',
equiv: '\u2261',
le: '\u2264',
ge: '\u2265',
sub: '\u2282',
sup: '\u2283',
nsub: '\u2284',
sube: '\u2286',
supe: '\u2287',
oplus: '\u2295',
otimes: '\u2297',
perp: '\u22A5',
sdot: '\u22C5',
lceil: '\u2308',
rceil: '\u2309',
lfloor: '\u230A',
rfloor: '\u230B',
lang: '\u2329',
rang: '\u232A',
loz: '\u25CA',
spades: '\u2660',
clubs: '\u2663',
hearts: '\u2665',
diams: '\u2666'
};
function getQualifiedJSXName(object) {
if (object.type === Syntax.JSXIdentifier) {
return object.name;
}
if (object.type === Syntax.JSXNamespacedName) {
return object.namespace.name + ':' + object.name.name;
}
/* istanbul ignore else */
if (object.type === Syntax.JSXMemberExpression) {
return (
getQualifiedJSXName(object.object) + '.' +
getQualifiedJSXName(object.property)
);
}
/* istanbul ignore next */
throwUnexpected(object);
}
function isJSXIdentifierStart(ch) {
// exclude backslash (\)
return (ch !== 92) && isIdentifierStart(ch);
}
function isJSXIdentifierPart(ch) {
// exclude backslash (\) and add hyphen (-)
return (ch !== 92) && (ch === 45 || isIdentifierPart(ch));
}
function scanJSXIdentifier() {
var ch, start, value = '';
start = index;
while (index < length) {
ch = source.charCodeAt(index);
if (!isJSXIdentifierPart(ch)) {
break;
}
value += source[index++];
}
return {
type: Token.JSXIdentifier,
value: value,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanJSXEntity() {
var ch, str = '', start = index, count = 0, code;
ch = source[index];
assert(ch === '&', 'Entity must start with an ampersand');
index++;
while (index < length && count++ < 10) {
ch = source[index++];
if (ch === ';') {
break;
}
str += ch;
}
// Well-formed entity (ending was found).
if (ch === ';') {
// Numeric entity.
if (str[0] === '#') {
if (str[1] === 'x') {
code = +('0' + str.substr(1));
} else {
// Removing leading zeros in order to avoid treating as octal in old browsers.
code = +str.substr(1).replace(Regex.LeadingZeros, '');
}
if (!isNaN(code)) {
return String.fromCharCode(code);
}
/* istanbul ignore else */
} else if (XHTMLEntities[str]) {
return XHTMLEntities[str];
}
}
// Treat non-entity sequences as regular text.
index = start + 1;
return '&';
}
function scanJSXText(stopChars) {
var ch, str = '', start;
start = index;
while (index < length) {
ch = source[index];
if (stopChars.indexOf(ch) !== -1) {
break;
}
if (ch === '&') {
str += scanJSXEntity();
} else {
index++;
if (ch === '\r' && source[index] === '\n') {
str += ch;
ch = source[index];
index++;
}
if (isLineTerminator(ch.charCodeAt(0))) {
++lineNumber;
lineStart = index;
}
str += ch;
}
}
return {
type: Token.JSXText,
value: str,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanJSXStringLiteral() {
var innerToken, quote, start;
quote = source[index];
assert((quote === '\'' || quote === '"'),
'String literal must starts with a quote');
start = index;
++index;
innerToken = scanJSXText([quote]);
if (quote !== source[index]) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
++index;
innerToken.range = [start, index];
return innerToken;
}
/**
* Between JSX opening and closing tags (e.g. <foo>HERE</foo>), anything that
* is not another JSX tag and is not an expression wrapped by {} is text.
*/
function advanceJSXChild() {
var ch = source.charCodeAt(index);
// '<' 60, '>' 62, '{' 123, '}' 125
if (ch !== 60 && ch !== 62 && ch !== 123 && ch !== 125) {
return scanJSXText(['<', '>', '{', '}']);
}
return scanPunctuator();
}
function parseJSXIdentifier() {
var token, marker = markerCreate();
if (lookahead.type !== Token.JSXIdentifier) {
throwUnexpected(lookahead);
}
token = lex();
return markerApply(marker, delegate.createJSXIdentifier(token.value));
}
function parseJSXNamespacedName() {
var namespace, name, marker = markerCreate();
namespace = parseJSXIdentifier();
expect(':');
name = parseJSXIdentifier();
return markerApply(marker, delegate.createJSXNamespacedName(namespace, name));
}
function parseJSXMemberExpression() {
var marker = markerCreate(),
expr = parseJSXIdentifier();
while (match('.')) {
lex();
expr = markerApply(marker, delegate.createJSXMemberExpression(expr, parseJSXIdentifier()));
}
return expr;
}
function parseJSXElementName() {
if (lookahead2().value === ':') {
return parseJSXNamespacedName();
}
if (lookahead2().value === '.') {
return parseJSXMemberExpression();
}
return parseJSXIdentifier();
}
function parseJSXAttributeName() {
if (lookahead2().value === ':') {
return parseJSXNamespacedName();
}
return parseJSXIdentifier();
}
function parseJSXAttributeValue() {
var value, marker;
if (match('{')) {
value = parseJSXExpressionContainer();
if (value.expression.type === Syntax.JSXEmptyExpression) {
throwError(
value,
'JSX attributes must only be assigned a non-empty ' +
'expression'
);
}
} else if (match('<')) {
value = parseJSXElement();
} else if (lookahead.type === Token.JSXText) {
marker = markerCreate();
value = markerApply(marker, delegate.createLiteral(lex()));
} else {
throwError({}, Messages.InvalidJSXAttributeValue);
}
return value;
}
function parseJSXEmptyExpression() {
var marker = markerCreatePreserveWhitespace();
while (source.charAt(index) !== '}') {
index++;
}
return markerApply(marker, delegate.createJSXEmptyExpression());
}
function parseJSXExpressionContainer() {
var expression, origInJSXChild, origInJSXTag, marker = markerCreate();
origInJSXChild = state.inJSXChild;
origInJSXTag = state.inJSXTag;
state.inJSXChild = false;
state.inJSXTag = false;
expect('{');
if (match('}')) {
expression = parseJSXEmptyExpression();
} else {
expression = parseExpression();
}
state.inJSXChild = origInJSXChild;
state.inJSXTag = origInJSXTag;
expect('}');
return markerApply(marker, delegate.createJSXExpressionContainer(expression));
}
function parseJSXSpreadAttribute() {
var expression, origInJSXChild, origInJSXTag, marker = markerCreate();
origInJSXChild = state.inJSXChild;
origInJSXTag = state.inJSXTag;
state.inJSXChild = false;
state.inJSXTag = false;
expect('{');
expect('...');
expression = parseAssignmentExpression();
state.inJSXChild = origInJSXChild;
state.inJSXTag = origInJSXTag;
expect('}');
return markerApply(marker, delegate.createJSXSpreadAttribute(expression));
}
function parseJSXAttribute() {
var name, marker;
if (match('{')) {
return parseJSXSpreadAttribute();
}
marker = markerCreate();
name = parseJSXAttributeName();
// HTML empty attribute
if (match('=')) {
lex();
return markerApply(marker, delegate.createJSXAttribute(name, parseJSXAttributeValue()));
}
return markerApply(marker, delegate.createJSXAttribute(name));
}
function parseJSXChild() {
var token, marker;
if (match('{')) {
token = parseJSXExpressionContainer();
} else if (lookahead.type === Token.JSXText) {
marker = markerCreatePreserveWhitespace();
token = markerApply(marker, delegate.createLiteral(lex()));
} else if (match('<')) {
token = parseJSXElement();
} else {
throwUnexpected(lookahead);
}
return token;
}
function parseJSXClosingElement() {
var name, origInJSXChild, origInJSXTag, marker = markerCreate();
origInJSXChild = state.inJSXChild;
origInJSXTag = state.inJSXTag;
state.inJSXChild = false;
state.inJSXTag = true;
expect('<');
expect('/');
name = parseJSXElementName();
// Because advance() (called by lex() called by expect()) expects there
// to be a valid token after >, it needs to know whether to look for a
// standard JS token or an JSX text node
state.inJSXChild = origInJSXChild;
state.inJSXTag = origInJSXTag;
expect('>');
return markerApply(marker, delegate.createJSXClosingElement(name));
}
function parseJSXOpeningElement() {
var name, attributes = [], selfClosing = false, origInJSXChild, origInJSXTag, marker = markerCreate();
origInJSXChild = state.inJSXChild;
origInJSXTag = state.inJSXTag;
state.inJSXChild = false;
state.inJSXTag = true;
expect('<');
name = parseJSXElementName();
while (index < length &&
lookahead.value !== '/' &&
lookahead.value !== '>') {
attributes.push(parseJSXAttribute());
}
state.inJSXTag = origInJSXTag;
if (lookahead.value === '/') {
expect('/');
// Because advance() (called by lex() called by expect()) expects
// there to be a valid token after >, it needs to know whether to
// look for a standard JS token or an JSX text node
state.inJSXChild = origInJSXChild;
expect('>');
selfClosing = true;
} else {
state.inJSXChild = true;
expect('>');
}
return markerApply(marker, delegate.createJSXOpeningElement(name, attributes, selfClosing));
}
function parseJSXElement() {
var openingElement, closingElement = null, children = [], origInJSXChild, origInJSXTag, marker = markerCreate();
origInJSXChild = state.inJSXChild;
origInJSXTag = state.inJSXTag;
openingElement = parseJSXOpeningElement();
if (!openingElement.selfClosing) {
while (index < length) {
state.inJSXChild = false; // Call lookahead2() with inJSXChild = false because </ should not be considered in the child
if (lookahead.value === '<' && lookahead2().value === '/') {
break;
}
state.inJSXChild = true;
children.push(parseJSXChild());
}
state.inJSXChild = origInJSXChild;
state.inJSXTag = origInJSXTag;
closingElement = parseJSXClosingElement();
if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
throwError({}, Messages.ExpectedJSXClosingTag, getQualifiedJSXName(openingElement.name));
}
}
// When (erroneously) writing two adjacent tags like
//
// var x = <div>one</div><div>two</div>;
//
// the default error message is a bit incomprehensible. Since it's
// rarely (never?) useful to write a less-than sign after an JSX
// element, we disallow it here in the parser in order to provide a
// better error message. (In the rare case that the less-than operator
// was intended, the left tag can be wrapped in parentheses.)
if (!origInJSXChild && match('<')) {
throwError(lookahead, Messages.AdjacentJSXElements);
}
return markerApply(marker, delegate.createJSXElement(openingElement, closingElement, children));
}
function parseTypeAlias() {
var id, marker = markerCreate(), typeParameters = null, right;
expectContextualKeyword('type');
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
expect('=');
right = parseType();
consumeSemicolon();
return markerApply(marker, delegate.createTypeAlias(id, typeParameters, right));
}
function parseInterfaceExtends() {
var marker = markerCreate(), id, typeParameters = null;
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterInstantiation();
}
return markerApply(marker, delegate.createInterfaceExtends(
id,
typeParameters
));
}
function parseInterfaceish(marker, allowStatic) {
var body, bodyMarker, extended = [], id,
typeParameters = null;
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
if (matchKeyword('extends')) {
expectKeyword('extends');
while (index < length) {
extended.push(parseInterfaceExtends());
if (!match(',')) {
break;
}
expect(',');
}
}
bodyMarker = markerCreate();
body = markerApply(bodyMarker, parseObjectType(allowStatic));
return markerApply(marker, delegate.createInterface(
id,
typeParameters,
body,
extended
));
}
function parseInterface() {
var marker = markerCreate();
if (strict) {
expectKeyword('interface');
} else {
expectContextualKeyword('interface');
}
return parseInterfaceish(marker, /* allowStatic */false);
}
function parseDeclareClass() {
var marker = markerCreate(), ret;
expectContextualKeyword('declare');
expectKeyword('class');
ret = parseInterfaceish(marker, /* allowStatic */true);
ret.type = Syntax.DeclareClass;
return ret;
}
function parseDeclareFunction() {
var id, idMarker,
marker = markerCreate(), params, returnType, rest, tmp,
typeParameters = null, value, valueMarker;
expectContextualKeyword('declare');
expectKeyword('function');
idMarker = markerCreate();
id = parseVariableIdentifier();
valueMarker = markerCreate();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
expect('(');
tmp = parseFunctionTypeParams();
params = tmp.params;
rest = tmp.rest;
expect(')');
expect(':');
returnType = parseType();
value = markerApply(valueMarker, delegate.createFunctionTypeAnnotation(
params,
returnType,
rest,
typeParameters
));
id.typeAnnotation = markerApply(valueMarker, delegate.createTypeAnnotation(
value
));
markerApply(idMarker, id);
consumeSemicolon();
return markerApply(marker, delegate.createDeclareFunction(
id
));
}
function parseDeclareVariable() {
var id, marker = markerCreate();
expectContextualKeyword('declare');
expectKeyword('var');
id = parseTypeAnnotatableIdentifier();
consumeSemicolon();
return markerApply(marker, delegate.createDeclareVariable(
id
));
}
function parseDeclareModule() {
var body = [], bodyMarker, id, idMarker, marker = markerCreate(), token;
expectContextualKeyword('declare');
expectContextualKeyword('module');
if (lookahead.type === Token.StringLiteral) {
if (strict && lookahead.octal) {
throwErrorTolerant(lookahead, Messages.StrictOctalLiteral);
}
idMarker = markerCreate();
id = markerApply(idMarker, delegate.createLiteral(lex()));
} else {
id = parseVariableIdentifier();
}
bodyMarker = markerCreate();
expect('{');
while (index < length && !match('}')) {
token = lookahead2();
switch (token.value) {
case 'class':
body.push(parseDeclareClass());
break;
case 'function':
body.push(parseDeclareFunction());
break;
case 'var':
body.push(parseDeclareVariable());
break;
default:
throwUnexpected(lookahead);
}
}
expect('}');
return markerApply(marker, delegate.createDeclareModule(
id,
markerApply(bodyMarker, delegate.createBlockStatement(body))
));
}
function collectToken() {
var loc, token, range, value, entry;
/* istanbul ignore else */
if (!state.inJSXChild) {
skipComment();
}
loc = {
start: {
line: lineNumber,
column: index - lineStart
}
};
token = extra.advance();
loc.end = {
line: lineNumber,
column: index - lineStart
};
if (token.type !== Token.EOF) {
range = [token.range[0], token.range[1]];
value = source.slice(token.range[0], token.range[1]);
entry = {
type: TokenName[token.type],
value: value,
range: range,
loc: loc
};
if (token.regex) {
entry.regex = {
pattern: token.regex.pattern,
flags: token.regex.flags
};
}
extra.tokens.push(entry);
}
return token;
}
function collectRegex() {
var pos, loc, regex, token;
skipComment();
pos = index;
loc = {
start: {
line: lineNumber,
column: index - lineStart
}
};
regex = extra.scanRegExp();
loc.end = {
line: lineNumber,
column: index - lineStart
};
if (!extra.tokenize) {
/* istanbul ignore next */
// Pop the previous token, which is likely '/' or '/='
if (extra.tokens.length > 0) {
token = extra.tokens[extra.tokens.length - 1];
if (token.range[0] === pos && token.type === 'Punctuator') {
if (token.value === '/' || token.value === '/=') {
extra.tokens.pop();
}
}
}
extra.tokens.push({
type: 'RegularExpression',
value: regex.literal,
regex: regex.regex,
range: [pos, index],
loc: loc
});
}
return regex;
}
function filterTokenLocation() {
var i, entry, token, tokens = [];
for (i = 0; i < extra.tokens.length; ++i) {
entry = extra.tokens[i];
token = {
type: entry.type,
value: entry.value
};
if (entry.regex) {
token.regex = {
pattern: entry.regex.pattern,
flags: entry.regex.flags
};
}
if (extra.range) {
token.range = entry.range;
}
if (extra.loc) {
token.loc = entry.loc;
}
tokens.push(token);
}
extra.tokens = tokens;
}
function patch() {
if (typeof extra.tokens !== 'undefined') {
extra.advance = advance;
extra.scanRegExp = scanRegExp;
advance = collectToken;
scanRegExp = collectRegex;
}
}
function unpatch() {
if (typeof extra.scanRegExp === 'function') {
advance = extra.advance;
scanRegExp = extra.scanRegExp;
}
}
// This is used to modify the delegate.
function extend(object, properties) {
var entry, result = {};
for (entry in object) {
/* istanbul ignore else */
if (object.hasOwnProperty(entry)) {
result[entry] = object[entry];
}
}
for (entry in properties) {
/* istanbul ignore else */
if (properties.hasOwnProperty(entry)) {
result[entry] = properties[entry];
}
}
return result;
}
function tokenize(code, options) {
var toString,
token,
tokens;
toString = String;
if (typeof code !== 'string' && !(code instanceof String)) {
code = toString(code);
}
delegate = SyntaxTreeDelegate;
source = code;
index = 0;
lineNumber = (source.length > 0) ? 1 : 0;
lineStart = 0;
length = source.length;
lookahead = null;
state = {
allowKeyword: true,
allowIn: true,
labelSet: new StringMap(),
inFunctionBody: false,
inIteration: false,
inSwitch: false,
lastCommentStart: -1
};
extra = {};
// Options matching.
options = options || {};
// Of course we collect tokens here.
options.tokens = true;
extra.tokens = [];
extra.tokenize = true;
// The following two fields are necessary to compute the Regex tokens.
extra.openParenToken = -1;
extra.openCurlyToken = -1;
extra.range = (typeof options.range === 'boolean') && options.range;
extra.loc = (typeof options.loc === 'boolean') && options.loc;
if (typeof options.comment === 'boolean' && options.comment) {
extra.comments = [];
}
if (typeof options.tolerant === 'boolean' && options.tolerant) {
extra.errors = [];
}
patch();
try {
peek();
if (lookahead.type === Token.EOF) {
return extra.tokens;
}
token = lex();
while (lookahead.type !== Token.EOF) {
try {
token = lex();
} catch (lexError) {
token = lookahead;
if (extra.errors) {
extra.errors.push(lexError);
// We have to break on the first error
// to avoid infinite loops.
break;
} else {
throw lexError;
}
}
}
filterTokenLocation();
tokens = extra.tokens;
if (typeof extra.comments !== 'undefined') {
tokens.comments = extra.comments;
}
if (typeof extra.errors !== 'undefined') {
tokens.errors = extra.errors;
}
} catch (e) {
throw e;
} finally {
unpatch();
extra = {};
}
return tokens;
}
function parse(code, options) {
var program, toString;
toString = String;
if (typeof code !== 'string' && !(code instanceof String)) {
code = toString(code);
}
delegate = SyntaxTreeDelegate;
source = code;
index = 0;
lineNumber = (source.length > 0) ? 1 : 0;
lineStart = 0;
length = source.length;
lookahead = null;
state = {
allowKeyword: false,
allowIn: true,
labelSet: new StringMap(),
parenthesizedCount: 0,
inFunctionBody: false,
inIteration: false,
inSwitch: false,
inJSXChild: false,
inJSXTag: false,
inType: false,
lastCommentStart: -1,
yieldAllowed: false,
awaitAllowed: false
};
extra = {};
if (typeof options !== 'undefined') {
extra.range = (typeof options.range === 'boolean') && options.range;
extra.loc = (typeof options.loc === 'boolean') && options.loc;
extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment;
if (extra.loc && options.source !== null && options.source !== undefined) {
delegate = extend(delegate, {
'postProcess': function (node) {
node.loc.source = toString(options.source);
return node;
}
});
}
extra.sourceType = options.sourceType;
if (typeof options.tokens === 'boolean' && options.tokens) {
extra.tokens = [];
}
if (typeof options.comment === 'boolean' && options.comment) {
extra.comments = [];
}
if (typeof options.tolerant === 'boolean' && options.tolerant) {
extra.errors = [];
}
if (extra.attachComment) {
extra.range = true;
extra.comments = [];
extra.bottomRightStack = [];
extra.trailingComments = [];
extra.leadingComments = [];
}
}
patch();
try {
program = parseProgram();
if (typeof extra.comments !== 'undefined') {
program.comments = extra.comments;
}
if (typeof extra.tokens !== 'undefined') {
filterTokenLocation();
program.tokens = extra.tokens;
}
if (typeof extra.errors !== 'undefined') {
program.errors = extra.errors;
}
} catch (e) {
throw e;
} finally {
unpatch();
extra = {};
}
return program;
}
// Sync with *.json manifests.
exports.version = '13001.1001.0-dev-harmony-fb';
exports.tokenize = tokenize;
exports.parse = parse;
// Deep copy.
/* istanbul ignore next */
exports.Syntax = (function () {
var name, types = {};
if (typeof Object.create === 'function') {
types = Object.create(null);
}
for (name in Syntax) {
if (Syntax.hasOwnProperty(name)) {
types[name] = Syntax[name];
}
}
if (typeof Object.freeze === 'function') {
Object.freeze(types);
}
return types;
}());
}));
/* vim: set sw=4 ts=4 et tw=80 : */
},{}],10:[function(_dereq_,module,exports){
var Base62 = (function (my) {
my.chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
my.encode = function(i){
if (i === 0) {return '0'}
var s = ''
while (i > 0) {
s = this.chars[i % 62] + s
i = Math.floor(i/62)
}
return s
};
my.decode = function(a,b,c,d){
for (
b = c = (
a === (/\W|_|^$/.test(a += "") || a)
) - 1;
d = a.charCodeAt(c++);
)
b = b * 62 + d - [, 48, 29, 87][d >> 5];
return b
};
return my;
}({}));
module.exports = Base62
},{}],11:[function(_dereq_,module,exports){
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = _dereq_('./source-map/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer = _dereq_('./source-map/source-map-consumer').SourceMapConsumer;
exports.SourceNode = _dereq_('./source-map/source-node').SourceNode;
},{"./source-map/source-map-consumer":16,"./source-map/source-map-generator":17,"./source-map/source-node":18}],12:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var util = _dereq_('./util');
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
*/
function ArraySet() {
this._array = [];
this._set = {};
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
var set = new ArraySet();
for (var i = 0, len = aArray.length; i < len; i++) {
set.add(aArray[i], aAllowDuplicates);
}
return set;
};
/**
* Add the given string to this set.
*
* @param String aStr
*/
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
var isDuplicate = this.has(aStr);
var idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
this._set[util.toSetString(aStr)] = idx;
}
};
/**
* Is the given string a member of this set?
*
* @param String aStr
*/
ArraySet.prototype.has = function ArraySet_has(aStr) {
return Object.prototype.hasOwnProperty.call(this._set,
util.toSetString(aStr));
};
/**
* What is the index of the given string in the array?
*
* @param String aStr
*/
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
if (this.has(aStr)) {
return this._set[util.toSetString(aStr)];
}
throw new Error('"' + aStr + '" is not in the set.');
};
/**
* What is the element at the given index?
*
* @param Number aIdx
*/
ArraySet.prototype.at = function ArraySet_at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error('No element indexed by ' + aIdx);
};
/**
* Returns the array representation of this set (which has the proper indices
* indicated by indexOf). Note that this is a copy of the internal array used
* for storing the members so that no one can mess with internal state.
*/
ArraySet.prototype.toArray = function ArraySet_toArray() {
return this._array.slice();
};
exports.ArraySet = ArraySet;
});
},{"./util":19,"amdefine":20}],13:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*
* Based on the Base 64 VLQ implementation in Closure Compiler:
* https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
*
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var base64 = _dereq_('./base64');
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
// Continuation
// | Sign
// | |
// V V
// 101011
var VLQ_BASE_SHIFT = 5;
// binary: 100000
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
var VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
var VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(aValue) {
return aValue < 0
? ((-aValue) << 1) + 1
: (aValue << 1) + 0;
}
/**
* Converts to a two-complement value from a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
*/
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative
? -shifted
: shifted;
}
/**
* Returns the base 64 VLQ encoded value.
*/
exports.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var digit;
var vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};
/**
* Decodes the next base 64 VLQ value from the given string and returns the
* value and the rest of the string.
*/
exports.decode = function base64VLQ_decode(aStr) {
var i = 0;
var strLen = aStr.length;
var result = 0;
var shift = 0;
var continuation, digit;
do {
if (i >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = base64.decode(aStr.charAt(i++));
continuation = !!(digit & VLQ_CONTINUATION_BIT);
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
return {
value: fromVLQSigned(result),
rest: aStr.slice(i)
};
};
});
},{"./base64":14,"amdefine":20}],14:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var charToIntMap = {};
var intToCharMap = {};
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
.split('')
.forEach(function (ch, index) {
charToIntMap[ch] = index;
intToCharMap[index] = ch;
});
/**
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
*/
exports.encode = function base64_encode(aNumber) {
if (aNumber in intToCharMap) {
return intToCharMap[aNumber];
}
throw new TypeError("Must be between 0 and 63: " + aNumber);
};
/**
* Decode a single base 64 digit to an integer.
*/
exports.decode = function base64_decode(aChar) {
if (aChar in charToIntMap) {
return charToIntMap[aChar];
}
throw new TypeError("Not a valid base 64 digit: " + aChar);
};
});
},{"amdefine":20}],15:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
/**
* Recursive implementation of binary search.
*
* @param aLow Indices here and lower do not contain the needle.
* @param aHigh Indices here and higher do not contain the needle.
* @param aNeedle The element being searched for.
* @param aHaystack The non-empty array being searched.
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
*/
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the next
// closest element that is less than that element.
//
// 3. We did not find the exact element, and there is no next-closest
// element which is less than the one we are searching for, so we
// return null.
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return aHaystack[mid];
}
else if (cmp > 0) {
// aHaystack[mid] is greater than our needle.
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
}
// We did not find an exact match, return the next closest one
// (termination case 2).
return aHaystack[mid];
}
else {
// aHaystack[mid] is less than our needle.
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (2) or (3) and return the appropriate thing.
return aLow < 0
? null
: aHaystack[aLow];
}
}
/**
* This is an implementation of binary search which will always try and return
* the next lowest value checked if there is no exact hit. This is because
* mappings between original and generated line/col pairs are single points,
* and there is an implicit region between each of them, so a miss just means
* that you aren't on the very start of a region.
*
* @param aNeedle The element you are looking for.
* @param aHaystack The array that is being searched.
* @param aCompare A function which takes the needle and an element in the
* array and returns -1, 0, or 1 depending on whether the needle is less
* than, equal to, or greater than the element, respectively.
*/
exports.search = function search(aNeedle, aHaystack, aCompare) {
return aHaystack.length > 0
? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)
: null;
};
});
},{"amdefine":20}],16:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var util = _dereq_('./util');
var binarySearch = _dereq_('./binary-search');
var ArraySet = _dereq_('./array-set').ArraySet;
var base64VLQ = _dereq_('./base64-vlq');
/**
* A SourceMapConsumer instance represents a parsed source map which we can
* query for information about the original file positions by giving it a file
* position in the generated source.
*
* The only parameter is the raw source map (either as a JSON string, or
* already parsed to an object). According to the spec, source maps have the
* following attributes:
*
* - version: Which version of the source map spec this map is following.
* - sources: An array of URLs to the original source files.
* - names: An array of identifiers which can be referrenced by individual mappings.
* - sourceRoot: Optional. The URL root from which all sources are relative.
* - sourcesContent: Optional. An array of contents of the original source files.
* - mappings: A string of base64 VLQs which contain the actual mappings.
* - file: The generated file this source map is associated with.
*
* Here is an example source map, taken from the source map spec[0]:
*
* {
* version : 3,
* file: "out.js",
* sourceRoot : "",
* sources: ["foo.js", "bar.js"],
* names: ["src", "maps", "are", "fun"],
* mappings: "AA,AB;;ABCDE;"
* }
*
* [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
*/
function SourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
var version = util.getArg(sourceMap, 'version');
var sources = util.getArg(sourceMap, 'sources');
// Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
// requires the array) to play nice here.
var names = util.getArg(sourceMap, 'names', []);
var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
var mappings = util.getArg(sourceMap, 'mappings');
var file = util.getArg(sourceMap, 'file', null);
// Once again, Sass deviates from the spec and supplies the version as a
// string rather than a number, so we use loose equality checking here.
if (version != this._version) {
throw new Error('Unsupported version: ' + version);
}
// Pass `true` below to allow duplicate names and sources. While source maps
// are intended to be compressed and deduplicated, the TypeScript compiler
// sometimes generates source maps with duplicates in them. See Github issue
// #72 and bugzil.la/889492.
this._names = ArraySet.fromArray(names, true);
this._sources = ArraySet.fromArray(sources, true);
this.sourceRoot = sourceRoot;
this.sourcesContent = sourcesContent;
this._mappings = mappings;
this.file = file;
}
/**
* Create a SourceMapConsumer from a SourceMapGenerator.
*
* @param SourceMapGenerator aSourceMap
* The source map that will be consumed.
* @returns SourceMapConsumer
*/
SourceMapConsumer.fromSourceMap =
function SourceMapConsumer_fromSourceMap(aSourceMap) {
var smc = Object.create(SourceMapConsumer.prototype);
smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
smc.sourceRoot = aSourceMap._sourceRoot;
smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
smc.sourceRoot);
smc.file = aSourceMap._file;
smc.__generatedMappings = aSourceMap._mappings.slice()
.sort(util.compareByGeneratedPositions);
smc.__originalMappings = aSourceMap._mappings.slice()
.sort(util.compareByOriginalPositions);
return smc;
};
/**
* The version of the source mapping spec that we are consuming.
*/
SourceMapConsumer.prototype._version = 3;
/**
* The list of original sources.
*/
Object.defineProperty(SourceMapConsumer.prototype, 'sources', {
get: function () {
return this._sources.toArray().map(function (s) {
return this.sourceRoot ? util.join(this.sourceRoot, s) : s;
}, this);
}
});
// `__generatedMappings` and `__originalMappings` are arrays that hold the
// parsed mapping coordinates from the source map's "mappings" attribute. They
// are lazily instantiated, accessed via the `_generatedMappings` and
// `_originalMappings` getters respectively, and we only parse the mappings
// and create these arrays once queried for a source location. We jump through
// these hoops because there can be many thousands of mappings, and parsing
// them is expensive, so we only want to do it if we must.
//
// Each object in the arrays is of the form:
//
// {
// generatedLine: The line number in the generated code,
// generatedColumn: The column number in the generated code,
// source: The path to the original source file that generated this
// chunk of code,
// originalLine: The line number in the original source that
// corresponds to this chunk of generated code,
// originalColumn: The column number in the original source that
// corresponds to this chunk of generated code,
// name: The name of the original symbol which generated this chunk of
// code.
// }
//
// All properties except for `generatedLine` and `generatedColumn` can be
// `null`.
//
// `_generatedMappings` is ordered by the generated positions.
//
// `_originalMappings` is ordered by the original positions.
SourceMapConsumer.prototype.__generatedMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
get: function () {
if (!this.__generatedMappings) {
this.__generatedMappings = [];
this.__originalMappings = [];
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__generatedMappings;
}
});
SourceMapConsumer.prototype.__originalMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
get: function () {
if (!this.__originalMappings) {
this.__generatedMappings = [];
this.__originalMappings = [];
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__originalMappings;
}
});
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (the ordered arrays in the `this.__generatedMappings` and
* `this.__originalMappings` properties).
*/
SourceMapConsumer.prototype._parseMappings =
function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
var generatedLine = 1;
var previousGeneratedColumn = 0;
var previousOriginalLine = 0;
var previousOriginalColumn = 0;
var previousSource = 0;
var previousName = 0;
var mappingSeparator = /^[,;]/;
var str = aStr;
var mapping;
var temp;
while (str.length > 0) {
if (str.charAt(0) === ';') {
generatedLine++;
str = str.slice(1);
previousGeneratedColumn = 0;
}
else if (str.charAt(0) === ',') {
str = str.slice(1);
}
else {
mapping = {};
mapping.generatedLine = generatedLine;
// Generated column.
temp = base64VLQ.decode(str);
mapping.generatedColumn = previousGeneratedColumn + temp.value;
previousGeneratedColumn = mapping.generatedColumn;
str = temp.rest;
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
// Original source.
temp = base64VLQ.decode(str);
mapping.source = this._sources.at(previousSource + temp.value);
previousSource += temp.value;
str = temp.rest;
if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
throw new Error('Found a source, but no line and column');
}
// Original line.
temp = base64VLQ.decode(str);
mapping.originalLine = previousOriginalLine + temp.value;
previousOriginalLine = mapping.originalLine;
// Lines are stored 0-based
mapping.originalLine += 1;
str = temp.rest;
if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
throw new Error('Found a source and line, but no column');
}
// Original column.
temp = base64VLQ.decode(str);
mapping.originalColumn = previousOriginalColumn + temp.value;
previousOriginalColumn = mapping.originalColumn;
str = temp.rest;
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
// Original name.
temp = base64VLQ.decode(str);
mapping.name = this._names.at(previousName + temp.value);
previousName += temp.value;
str = temp.rest;
}
}
this.__generatedMappings.push(mapping);
if (typeof mapping.originalLine === 'number') {
this.__originalMappings.push(mapping);
}
}
}
this.__originalMappings.sort(util.compareByOriginalPositions);
};
/**
* Find the mapping that best matches the hypothetical "needle" mapping that
* we are searching for in the given "haystack" of mappings.
*/
SourceMapConsumer.prototype._findMapping =
function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
aColumnName, aComparator) {
// To return the position we are searching for, we must first find the
// mapping for the given position and then return the opposite position it
// points to. Because the mappings are sorted, we can use binary search to
// find the best mapping.
if (aNeedle[aLineName] <= 0) {
throw new TypeError('Line must be greater than or equal to 1, got '
+ aNeedle[aLineName]);
}
if (aNeedle[aColumnName] < 0) {
throw new TypeError('Column must be greater than or equal to 0, got '
+ aNeedle[aColumnName]);
}
return binarySearch.search(aNeedle, aMappings, aComparator);
};
/**
* Returns the original source, line, and column information for the generated
* source's line and column positions provided. The only argument is an object
* with the following properties:
*
* - line: The line number in the generated source.
* - column: The column number in the generated source.
*
* and an object is returned with the following properties:
*
* - source: The original source file, or null.
* - line: The line number in the original source, or null.
* - column: The column number in the original source, or null.
* - name: The original identifier, or null.
*/
SourceMapConsumer.prototype.originalPositionFor =
function SourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util.getArg(aArgs, 'line'),
generatedColumn: util.getArg(aArgs, 'column')
};
var mapping = this._findMapping(needle,
this._generatedMappings,
"generatedLine",
"generatedColumn",
util.compareByGeneratedPositions);
if (mapping) {
var source = util.getArg(mapping, 'source', null);
if (source && this.sourceRoot) {
source = util.join(this.sourceRoot, source);
}
return {
source: source,
line: util.getArg(mapping, 'originalLine', null),
column: util.getArg(mapping, 'originalColumn', null),
name: util.getArg(mapping, 'name', null)
};
}
return {
source: null,
line: null,
column: null,
name: null
};
};
/**
* Returns the original source content. The only argument is the url of the
* original source file. Returns null if no original source content is
* availible.
*/
SourceMapConsumer.prototype.sourceContentFor =
function SourceMapConsumer_sourceContentFor(aSource) {
if (!this.sourcesContent) {
return null;
}
if (this.sourceRoot) {
aSource = util.relative(this.sourceRoot, aSource);
}
if (this._sources.has(aSource)) {
return this.sourcesContent[this._sources.indexOf(aSource)];
}
var url;
if (this.sourceRoot
&& (url = util.urlParse(this.sourceRoot))) {
// XXX: file:// URIs and absolute paths lead to unexpected behavior for
// many users. We can help them out when they expect file:// URIs to
// behave like it would if they were running a local HTTP server. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
if (url.scheme == "file"
&& this._sources.has(fileUriAbsPath)) {
return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
}
if ((!url.path || url.path == "/")
&& this._sources.has("/" + aSource)) {
return this.sourcesContent[this._sources.indexOf("/" + aSource)];
}
}
throw new Error('"' + aSource + '" is not in the SourceMap.');
};
/**
* Returns the generated line and column information for the original source,
* line, and column positions provided. The only argument is an object with
* the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: The column number in the original source.
*
* and an object is returned with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
SourceMapConsumer.prototype.generatedPositionFor =
function SourceMapConsumer_generatedPositionFor(aArgs) {
var needle = {
source: util.getArg(aArgs, 'source'),
originalLine: util.getArg(aArgs, 'line'),
originalColumn: util.getArg(aArgs, 'column')
};
if (this.sourceRoot) {
needle.source = util.relative(this.sourceRoot, needle.source);
}
var mapping = this._findMapping(needle,
this._originalMappings,
"originalLine",
"originalColumn",
util.compareByOriginalPositions);
if (mapping) {
return {
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null)
};
}
return {
line: null,
column: null
};
};
SourceMapConsumer.GENERATED_ORDER = 1;
SourceMapConsumer.ORIGINAL_ORDER = 2;
/**
* Iterate over each mapping between an original source/line/column and a
* generated line/column in this source map.
*
* @param Function aCallback
* The function that is called with each mapping.
* @param Object aContext
* Optional. If specified, this object will be the value of `this` every
* time that `aCallback` is called.
* @param aOrder
* Either `SourceMapConsumer.GENERATED_ORDER` or
* `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
* iterate over the mappings sorted by the generated file's line/column
* order or the original's source/line/column order, respectively. Defaults to
* `SourceMapConsumer.GENERATED_ORDER`.
*/
SourceMapConsumer.prototype.eachMapping =
function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
var context = aContext || null;
var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
var mappings;
switch (order) {
case SourceMapConsumer.GENERATED_ORDER:
mappings = this._generatedMappings;
break;
case SourceMapConsumer.ORIGINAL_ORDER:
mappings = this._originalMappings;
break;
default:
throw new Error("Unknown order of iteration.");
}
var sourceRoot = this.sourceRoot;
mappings.map(function (mapping) {
var source = mapping.source;
if (source && sourceRoot) {
source = util.join(sourceRoot, source);
}
return {
source: source,
generatedLine: mapping.generatedLine,
generatedColumn: mapping.generatedColumn,
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name: mapping.name
};
}).forEach(aCallback, context);
};
exports.SourceMapConsumer = SourceMapConsumer;
});
},{"./array-set":12,"./base64-vlq":13,"./binary-search":15,"./util":19,"amdefine":20}],17:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var base64VLQ = _dereq_('./base64-vlq');
var util = _dereq_('./util');
var ArraySet = _dereq_('./array-set').ArraySet;
/**
* An instance of the SourceMapGenerator represents a source map which is
* being built incrementally. To create a new one, you must pass an object
* with the following properties:
*
* - file: The filename of the generated source.
* - sourceRoot: An optional root for all URLs in this source map.
*/
function SourceMapGenerator(aArgs) {
this._file = util.getArg(aArgs, 'file');
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = [];
this._sourcesContents = null;
}
SourceMapGenerator.prototype._version = 3;
/**
* Creates a new SourceMapGenerator based on a SourceMapConsumer
*
* @param aSourceMapConsumer The SourceMap.
*/
SourceMapGenerator.fromSourceMap =
function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
var sourceRoot = aSourceMapConsumer.sourceRoot;
var generator = new SourceMapGenerator({
file: aSourceMapConsumer.file,
sourceRoot: sourceRoot
});
aSourceMapConsumer.eachMapping(function (mapping) {
var newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
}
};
if (mapping.source) {
newMapping.source = mapping.source;
if (sourceRoot) {
newMapping.source = util.relative(sourceRoot, newMapping.source);
}
newMapping.original = {
line: mapping.originalLine,
column: mapping.originalColumn
};
if (mapping.name) {
newMapping.name = mapping.name;
}
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
};
/**
* Add a single mapping from original source line and column to the generated
* source's line and column for this source map being created. The mapping
* object should have the following properties:
*
* - generated: An object with the generated line and column positions.
* - original: An object with the original line and column positions.
* - source: The original source file (relative to the sourceRoot).
* - name: An optional original token name for this mapping.
*/
SourceMapGenerator.prototype.addMapping =
function SourceMapGenerator_addMapping(aArgs) {
var generated = util.getArg(aArgs, 'generated');
var original = util.getArg(aArgs, 'original', null);
var source = util.getArg(aArgs, 'source', null);
var name = util.getArg(aArgs, 'name', null);
this._validateMapping(generated, original, source, name);
if (source && !this._sources.has(source)) {
this._sources.add(source);
}
if (name && !this._names.has(name)) {
this._names.add(name);
}
this._mappings.push({
generatedLine: generated.line,
generatedColumn: generated.column,
originalLine: original != null && original.line,
originalColumn: original != null && original.column,
source: source,
name: name
});
};
/**
* Set the source content for a source file.
*/
SourceMapGenerator.prototype.setSourceContent =
function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
var source = aSourceFile;
if (this._sourceRoot) {
source = util.relative(this._sourceRoot, source);
}
if (aSourceContent !== null) {
// Add the source content to the _sourcesContents map.
// Create a new _sourcesContents map if the property is null.
if (!this._sourcesContents) {
this._sourcesContents = {};
}
this._sourcesContents[util.toSetString(source)] = aSourceContent;
} else {
// Remove the source file from the _sourcesContents map.
// If the _sourcesContents map is empty, set the property to null.
delete this._sourcesContents[util.toSetString(source)];
if (Object.keys(this._sourcesContents).length === 0) {
this._sourcesContents = null;
}
}
};
/**
* Applies the mappings of a sub-source-map for a specific source file to the
* source map being generated. Each mapping to the supplied source file is
* rewritten using the supplied source map. Note: The resolution for the
* resulting mappings is the minimium of this map and the supplied map.
*
* @param aSourceMapConsumer The source map to be applied.
* @param aSourceFile Optional. The filename of the source file.
* If omitted, SourceMapConsumer's file property will be used.
*/
SourceMapGenerator.prototype.applySourceMap =
function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) {
// If aSourceFile is omitted, we will use the file property of the SourceMap
if (!aSourceFile) {
aSourceFile = aSourceMapConsumer.file;
}
var sourceRoot = this._sourceRoot;
// Make "aSourceFile" relative if an absolute Url is passed.
if (sourceRoot) {
aSourceFile = util.relative(sourceRoot, aSourceFile);
}
// Applying the SourceMap can add and remove items from the sources and
// the names array.
var newSources = new ArraySet();
var newNames = new ArraySet();
// Find mappings for the "aSourceFile"
this._mappings.forEach(function (mapping) {
if (mapping.source === aSourceFile && mapping.originalLine) {
// Check if it can be mapped by the source map, then update the mapping.
var original = aSourceMapConsumer.originalPositionFor({
line: mapping.originalLine,
column: mapping.originalColumn
});
if (original.source !== null) {
// Copy mapping
if (sourceRoot) {
mapping.source = util.relative(sourceRoot, original.source);
} else {
mapping.source = original.source;
}
mapping.originalLine = original.line;
mapping.originalColumn = original.column;
if (original.name !== null && mapping.name !== null) {
// Only use the identifier name if it's an identifier
// in both SourceMaps
mapping.name = original.name;
}
}
}
var source = mapping.source;
if (source && !newSources.has(source)) {
newSources.add(source);
}
var name = mapping.name;
if (name && !newNames.has(name)) {
newNames.add(name);
}
}, this);
this._sources = newSources;
this._names = newNames;
// Copy sourcesContents of applied map.
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
if (sourceRoot) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
this.setSourceContent(sourceFile, content);
}
}, this);
};
/**
* A mapping can have one of the three levels of data:
*
* 1. Just the generated position.
* 2. The Generated position, original position, and original source.
* 3. Generated and original position, original source, as well as a name
* token.
*
* To maintain consistency, we validate that any new mapping being added falls
* in to one of these categories.
*/
SourceMapGenerator.prototype._validateMapping =
function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
aName) {
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aGenerated.line > 0 && aGenerated.column >= 0
&& !aOriginal && !aSource && !aName) {
// Case 1.
return;
}
else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aOriginal && 'line' in aOriginal && 'column' in aOriginal
&& aGenerated.line > 0 && aGenerated.column >= 0
&& aOriginal.line > 0 && aOriginal.column >= 0
&& aSource) {
// Cases 2 and 3.
return;
}
else {
throw new Error('Invalid mapping: ' + JSON.stringify({
generated: aGenerated,
source: aSource,
orginal: aOriginal,
name: aName
}));
}
};
/**
* Serialize the accumulated mappings in to the stream of base 64 VLQs
* specified by the source map format.
*/
SourceMapGenerator.prototype._serializeMappings =
function SourceMapGenerator_serializeMappings() {
var previousGeneratedColumn = 0;
var previousGeneratedLine = 1;
var previousOriginalColumn = 0;
var previousOriginalLine = 0;
var previousName = 0;
var previousSource = 0;
var result = '';
var mapping;
// The mappings must be guaranteed to be in sorted order before we start
// serializing them or else the generated line numbers (which are defined
// via the ';' separators) will be all messed up. Note: it might be more
// performant to maintain the sorting as we insert them, rather than as we
// serialize them, but the big O is the same either way.
this._mappings.sort(util.compareByGeneratedPositions);
for (var i = 0, len = this._mappings.length; i < len; i++) {
mapping = this._mappings[i];
if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generatedLine !== previousGeneratedLine) {
result += ';';
previousGeneratedLine++;
}
}
else {
if (i > 0) {
if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) {
continue;
}
result += ',';
}
}
result += base64VLQ.encode(mapping.generatedColumn
- previousGeneratedColumn);
previousGeneratedColumn = mapping.generatedColumn;
if (mapping.source) {
result += base64VLQ.encode(this._sources.indexOf(mapping.source)
- previousSource);
previousSource = this._sources.indexOf(mapping.source);
// lines are stored 0-based in SourceMap spec version 3
result += base64VLQ.encode(mapping.originalLine - 1
- previousOriginalLine);
previousOriginalLine = mapping.originalLine - 1;
result += base64VLQ.encode(mapping.originalColumn
- previousOriginalColumn);
previousOriginalColumn = mapping.originalColumn;
if (mapping.name) {
result += base64VLQ.encode(this._names.indexOf(mapping.name)
- previousName);
previousName = this._names.indexOf(mapping.name);
}
}
}
return result;
};
SourceMapGenerator.prototype._generateSourcesContent =
function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
return aSources.map(function (source) {
if (!this._sourcesContents) {
return null;
}
if (aSourceRoot) {
source = util.relative(aSourceRoot, source);
}
var key = util.toSetString(source);
return Object.prototype.hasOwnProperty.call(this._sourcesContents,
key)
? this._sourcesContents[key]
: null;
}, this);
};
/**
* Externalize the source map.
*/
SourceMapGenerator.prototype.toJSON =
function SourceMapGenerator_toJSON() {
var map = {
version: this._version,
file: this._file,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings()
};
if (this._sourceRoot) {
map.sourceRoot = this._sourceRoot;
}
if (this._sourcesContents) {
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
}
return map;
};
/**
* Render the source map being generated to a string.
*/
SourceMapGenerator.prototype.toString =
function SourceMapGenerator_toString() {
return JSON.stringify(this);
};
exports.SourceMapGenerator = SourceMapGenerator;
});
},{"./array-set":12,"./base64-vlq":13,"./util":19,"amdefine":20}],18:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var SourceMapGenerator = _dereq_('./source-map-generator').SourceMapGenerator;
var util = _dereq_('./util');
/**
* SourceNodes provide a way to abstract over interpolating/concatenating
* snippets of generated JavaScript source code while maintaining the line and
* column information associated with the original source code.
*
* @param aLine The original line number.
* @param aColumn The original column number.
* @param aSource The original source's filename.
* @param aChunks Optional. An array of strings which are snippets of
* generated JS, or other SourceNodes.
* @param aName The original identifier.
*/
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
this.children = [];
this.sourceContents = {};
this.line = aLine === undefined ? null : aLine;
this.column = aColumn === undefined ? null : aColumn;
this.source = aSource === undefined ? null : aSource;
this.name = aName === undefined ? null : aName;
if (aChunks != null) this.add(aChunks);
}
/**
* Creates a SourceNode from generated code and a SourceMapConsumer.
*
* @param aGeneratedCode The generated code
* @param aSourceMapConsumer The SourceMap for the generated code
*/
SourceNode.fromStringWithSourceMap =
function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
var node = new SourceNode();
// The generated code
// Processed fragments are removed from this array.
var remainingLines = aGeneratedCode.split('\n');
// We need to remember the position of "remainingLines"
var lastGeneratedLine = 1, lastGeneratedColumn = 0;
// The generate SourceNodes we need a code range.
// To extract it current and last mapping is used.
// Here we store the last mapping.
var lastMapping = null;
aSourceMapConsumer.eachMapping(function (mapping) {
if (lastMapping === null) {
// We add the generated code until the first mapping
// to the SourceNode without any mapping.
// Each line is added as separate string.
while (lastGeneratedLine < mapping.generatedLine) {
node.add(remainingLines.shift() + "\n");
lastGeneratedLine++;
}
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[0];
node.add(nextLine.substr(0, mapping.generatedColumn));
remainingLines[0] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
} else {
// We add the code from "lastMapping" to "mapping":
// First check if there is a new line in between.
if (lastGeneratedLine < mapping.generatedLine) {
var code = "";
// Associate full lines with "lastMapping"
do {
code += remainingLines.shift() + "\n";
lastGeneratedLine++;
lastGeneratedColumn = 0;
} while (lastGeneratedLine < mapping.generatedLine);
// When we reached the correct line, we add code until we
// reach the correct column too.
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[0];
code += nextLine.substr(0, mapping.generatedColumn);
remainingLines[0] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
// Create the SourceNode.
addMappingWithCode(lastMapping, code);
} else {
// There is no new line in between.
// Associate the code between "lastGeneratedColumn" and
// "mapping.generatedColumn" with "lastMapping"
var nextLine = remainingLines[0];
var code = nextLine.substr(0, mapping.generatedColumn -
lastGeneratedColumn);
remainingLines[0] = nextLine.substr(mapping.generatedColumn -
lastGeneratedColumn);
lastGeneratedColumn = mapping.generatedColumn;
addMappingWithCode(lastMapping, code);
}
}
lastMapping = mapping;
}, this);
// We have processed all mappings.
// Associate the remaining code in the current line with "lastMapping"
// and add the remaining lines without any mapping
addMappingWithCode(lastMapping, remainingLines.join("\n"));
// Copy sourcesContent into SourceNode
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
node.setSourceContent(sourceFile, content);
}
});
return node;
function addMappingWithCode(mapping, code) {
if (mapping === null || mapping.source === undefined) {
node.add(code);
} else {
node.add(new SourceNode(mapping.originalLine,
mapping.originalColumn,
mapping.source,
code,
mapping.name));
}
}
};
/**
* Add a chunk of generated JS to this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.add = function SourceNode_add(aChunk) {
if (Array.isArray(aChunk)) {
aChunk.forEach(function (chunk) {
this.add(chunk);
}, this);
}
else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
if (aChunk) {
this.children.push(aChunk);
}
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Add a chunk of generated JS to the beginning of this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (var i = aChunk.length-1; i >= 0; i--) {
this.prepend(aChunk[i]);
}
}
else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
this.children.unshift(aChunk);
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Walk over the tree of JS snippets in this node and its children. The
* walking function is called once for each snippet of JS and is passed that
* snippet and the its original associated source's line/column location.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
var chunk;
for (var i = 0, len = this.children.length; i < len; i++) {
chunk = this.children[i];
if (chunk instanceof SourceNode) {
chunk.walk(aFn);
}
else {
if (chunk !== '') {
aFn(chunk, { source: this.source,
line: this.line,
column: this.column,
name: this.name });
}
}
}
};
/**
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
* each of `this.children`.
*
* @param aSep The separator.
*/
SourceNode.prototype.join = function SourceNode_join(aSep) {
var newChildren;
var i;
var len = this.children.length;
if (len > 0) {
newChildren = [];
for (i = 0; i < len-1; i++) {
newChildren.push(this.children[i]);
newChildren.push(aSep);
}
newChildren.push(this.children[i]);
this.children = newChildren;
}
return this;
};
/**
* Call String.prototype.replace on the very right-most source snippet. Useful
* for trimming whitespace from the end of a source node, etc.
*
* @param aPattern The pattern to replace.
* @param aReplacement The thing to replace the pattern with.
*/
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
var lastChild = this.children[this.children.length - 1];
if (lastChild instanceof SourceNode) {
lastChild.replaceRight(aPattern, aReplacement);
}
else if (typeof lastChild === 'string') {
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
}
else {
this.children.push(''.replace(aPattern, aReplacement));
}
return this;
};
/**
* Set the source content for a source file. This will be added to the SourceMapGenerator
* in the sourcesContent field.
*
* @param aSourceFile The filename of the source file
* @param aSourceContent The content of the source file
*/
SourceNode.prototype.setSourceContent =
function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
};
/**
* Walk over the tree of SourceNodes. The walking function is called for each
* source file content and is passed the filename and source content.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walkSourceContents =
function SourceNode_walkSourceContents(aFn) {
for (var i = 0, len = this.children.length; i < len; i++) {
if (this.children[i] instanceof SourceNode) {
this.children[i].walkSourceContents(aFn);
}
}
var sources = Object.keys(this.sourceContents);
for (var i = 0, len = sources.length; i < len; i++) {
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
}
};
/**
* Return the string representation of this source node. Walks over the tree
* and concatenates all the various snippets together to one string.
*/
SourceNode.prototype.toString = function SourceNode_toString() {
var str = "";
this.walk(function (chunk) {
str += chunk;
});
return str;
};
/**
* Returns the string representation of this source node along with a source
* map.
*/
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
var generated = {
code: "",
line: 1,
column: 0
};
var map = new SourceMapGenerator(aArgs);
var sourceMappingActive = false;
var lastOriginalSource = null;
var lastOriginalLine = null;
var lastOriginalColumn = null;
var lastOriginalName = null;
this.walk(function (chunk, original) {
generated.code += chunk;
if (original.source !== null
&& original.line !== null
&& original.column !== null) {
if(lastOriginalSource !== original.source
|| lastOriginalLine !== original.line
|| lastOriginalColumn !== original.column
|| lastOriginalName !== original.name) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
lastOriginalSource = original.source;
lastOriginalLine = original.line;
lastOriginalColumn = original.column;
lastOriginalName = original.name;
sourceMappingActive = true;
} else if (sourceMappingActive) {
map.addMapping({
generated: {
line: generated.line,
column: generated.column
}
});
lastOriginalSource = null;
sourceMappingActive = false;
}
chunk.split('').forEach(function (ch) {
if (ch === '\n') {
generated.line++;
generated.column = 0;
} else {
generated.column++;
}
});
});
this.walkSourceContents(function (sourceFile, sourceContent) {
map.setSourceContent(sourceFile, sourceContent);
});
return { code: generated.code, map: map };
};
exports.SourceNode = SourceNode;
});
},{"./source-map-generator":17,"./util":19,"amdefine":20}],19:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/;
var dataUrlRegexp = /^data:.+\,.+/;
function urlParse(aUrl) {
var match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[3],
host: match[4],
port: match[6],
path: match[7]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = aParsedUrl.scheme + "://";
if (aParsedUrl.auth) {
url += aParsedUrl.auth + "@"
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
function join(aRoot, aPath) {
var url;
if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) {
return aPath;
}
if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) {
url.path = aPath;
return urlGenerate(url);
}
return aRoot.replace(/\/$/, '') + '/' + aPath;
}
exports.join = join;
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See https://github.com/mozilla/source-map/pull/31 and
* https://github.com/mozilla/source-map/issues/30
*
* @param String aStr
*/
function toSetString(aStr) {
return '$' + aStr;
}
exports.toSetString = toSetString;
function fromSetString(aStr) {
return aStr.substr(1);
}
exports.fromSetString = fromSetString;
function relative(aRoot, aPath) {
aRoot = aRoot.replace(/\/$/, '');
var url = urlParse(aRoot);
if (aPath.charAt(0) == "/" && url && url.path == "/") {
return aPath.slice(1);
}
return aPath.indexOf(aRoot + '/') === 0
? aPath.substr(aRoot.length + 1)
: aPath;
}
exports.relative = relative;
function strcmp(aStr1, aStr2) {
var s1 = aStr1 || "";
var s2 = aStr2 || "";
return (s1 > s2) - (s1 < s2);
}
/**
* Comparator between two mappings where the original positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same original source/line/column, but different generated
* line and column the same. Useful when searching for a mapping with a
* stubbed out mapping.
*/
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
var cmp;
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp || onlyCompareOriginal) {
return cmp;
}
cmp = strcmp(mappingA.name, mappingB.name);
if (cmp) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
return mappingA.generatedColumn - mappingB.generatedColumn;
};
exports.compareByOriginalPositions = compareByOriginalPositions;
/**
* Comparator between two mappings where the generated positions are
* compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same generated line and column, but different
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {
var cmp;
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp || onlyCompareGenerated) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
};
exports.compareByGeneratedPositions = compareByGeneratedPositions;
});
},{"amdefine":20}],20:[function(_dereq_,module,exports){
(function (process,__filename){
/** vim: et:ts=4:sw=4:sts=4
* @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/amdefine for details
*/
/*jslint node: true */
/*global module, process */
'use strict';
/**
* Creates a define for node.
* @param {Object} module the "module" object that is defined by Node for the
* current module.
* @param {Function} [requireFn]. Node's require function for the current module.
* It only needs to be passed in Node versions before 0.5, when module.require
* did not exist.
* @returns {Function} a define function that is usable for the current node
* module.
*/
function amdefine(module, requireFn) {
'use strict';
var defineCache = {},
loaderCache = {},
alreadyCalled = false,
path = _dereq_('path'),
makeRequire, stringRequire;
/**
* Trims the . and .. from an array of path segments.
* It will keep a leading path segment if a .. will become
* the first path segment, to help with module name lookups,
* which act like paths, but can be remapped. But the end result,
* all paths that use this function should look normalized.
* NOTE: this method MODIFIES the input array.
* @param {Array} ary the array of path segments.
*/
function trimDots(ary) {
var i, part;
for (i = 0; ary[i]; i+= 1) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
function normalize(name, baseName) {
var baseParts;
//Adjust any relative paths.
if (name && name.charAt(0) === '.') {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
baseParts = baseName.split('/');
baseParts = baseParts.slice(0, baseParts.length - 1);
baseParts = baseParts.concat(name.split('/'));
trimDots(baseParts);
name = baseParts.join('/');
}
}
return name;
}
/**
* Create the normalize() function passed to a loader plugin's
* normalize method.
*/
function makeNormalize(relName) {
return function (name) {
return normalize(name, relName);
};
}
function makeLoad(id) {
function load(value) {
loaderCache[id] = value;
}
load.fromText = function (id, text) {
//This one is difficult because the text can/probably uses
//define, and any relative paths and requires should be relative
//to that id was it would be found on disk. But this would require
//bootstrapping a module/require fairly deeply from node core.
//Not sure how best to go about that yet.
throw new Error('amdefine does not implement load.fromText');
};
return load;
}
makeRequire = function (systemRequire, exports, module, relId) {
function amdRequire(deps, callback) {
if (typeof deps === 'string') {
//Synchronous, single module require('')
return stringRequire(systemRequire, exports, module, deps, relId);
} else {
//Array of dependencies with a callback.
//Convert the dependencies to modules.
deps = deps.map(function (depName) {
return stringRequire(systemRequire, exports, module, depName, relId);
});
//Wait for next tick to call back the require call.
process.nextTick(function () {
callback.apply(null, deps);
});
}
}
amdRequire.toUrl = function (filePath) {
if (filePath.indexOf('.') === 0) {
return normalize(filePath, path.dirname(module.filename));
} else {
return filePath;
}
};
return amdRequire;
};
//Favor explicit value, passed in if the module wants to support Node 0.4.
requireFn = requireFn || function req() {
return module.require.apply(module, arguments);
};
function runFactory(id, deps, factory) {
var r, e, m, result;
if (id) {
e = loaderCache[id] = {};
m = {
id: id,
uri: __filename,
exports: e
};
r = makeRequire(requireFn, e, m, id);
} else {
//Only support one define call per file
if (alreadyCalled) {
throw new Error('amdefine with no module ID cannot be called more than once per file.');
}
alreadyCalled = true;
//Use the real variables from node
//Use module.exports for exports, since
//the exports in here is amdefine exports.
e = module.exports;
m = module;
r = makeRequire(requireFn, e, m, module.id);
}
//If there are dependencies, they are strings, so need
//to convert them to dependency values.
if (deps) {
deps = deps.map(function (depName) {
return r(depName);
});
}
//Call the factory with the right dependencies.
if (typeof factory === 'function') {
result = factory.apply(m.exports, deps);
} else {
result = factory;
}
if (result !== undefined) {
m.exports = result;
if (id) {
loaderCache[id] = m.exports;
}
}
}
stringRequire = function (systemRequire, exports, module, id, relId) {
//Split the ID by a ! so that
var index = id.indexOf('!'),
originalId = id,
prefix, plugin;
if (index === -1) {
id = normalize(id, relId);
//Straight module lookup. If it is one of the special dependencies,
//deal with it, otherwise, delegate to node.
if (id === 'require') {
return makeRequire(systemRequire, exports, module, relId);
} else if (id === 'exports') {
return exports;
} else if (id === 'module') {
return module;
} else if (loaderCache.hasOwnProperty(id)) {
return loaderCache[id];
} else if (defineCache[id]) {
runFactory.apply(null, defineCache[id]);
return loaderCache[id];
} else {
if(systemRequire) {
return systemRequire(originalId);
} else {
throw new Error('No module with ID: ' + id);
}
}
} else {
//There is a plugin in play.
prefix = id.substring(0, index);
id = id.substring(index + 1, id.length);
plugin = stringRequire(systemRequire, exports, module, prefix, relId);
if (plugin.normalize) {
id = plugin.normalize(id, makeNormalize(relId));
} else {
//Normalize the ID normally.
id = normalize(id, relId);
}
if (loaderCache[id]) {
return loaderCache[id];
} else {
plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {});
return loaderCache[id];
}
}
};
//Create a define function specific to the module asking for amdefine.
function define(id, deps, factory) {
if (Array.isArray(id)) {
factory = deps;
deps = id;
id = undefined;
} else if (typeof id !== 'string') {
factory = id;
id = deps = undefined;
}
if (deps && !Array.isArray(deps)) {
factory = deps;
deps = undefined;
}
if (!deps) {
deps = ['require', 'exports', 'module'];
}
//Set up properties for this module. If an ID, then use
//internal cache. If no ID, then use the external variables
//for this node module.
if (id) {
//Put the module in deep freeze until there is a
//require call for it.
defineCache[id] = [id, deps, factory];
} else {
runFactory(id, deps, factory);
}
}
//define.require, which has access to all the values in the
//cache. Useful for AMD modules that all have IDs in the file,
//but need to finally export a value to node based on one of those
//IDs.
define.require = function (id) {
if (loaderCache[id]) {
return loaderCache[id];
}
if (defineCache[id]) {
runFactory.apply(null, defineCache[id]);
return loaderCache[id];
}
};
define.amd = {};
return define;
}
module.exports = amdefine;
}).call(this,_dereq_('_process'),"/node_modules/jstransform/node_modules/source-map/node_modules/amdefine/amdefine.js")
},{"_process":8,"path":7}],21:[function(_dereq_,module,exports){
/**
* Copyright 2013 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.
*/
var docblockRe = /^\s*(\/\*\*(.|\r?\n)*?\*\/)/;
var ltrimRe = /^\s*/;
/**
* @param {String} contents
* @return {String}
*/
function extract(contents) {
var match = contents.match(docblockRe);
if (match) {
return match[0].replace(ltrimRe, '') || '';
}
return '';
}
var commentStartRe = /^\/\*\*?/;
var commentEndRe = /\*+\/$/;
var wsRe = /[\t ]+/g;
var stringStartRe = /(\r?\n|^) *\*/g;
var multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *([^@\r\n\s][^@\r\n]+?) *\r?\n/g;
var propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;
/**
* @param {String} contents
* @return {Array}
*/
function parse(docblock) {
docblock = docblock
.replace(commentStartRe, '')
.replace(commentEndRe, '')
.replace(wsRe, ' ')
.replace(stringStartRe, '$1');
// Normalize multi-line directives
var prev = '';
while (prev != docblock) {
prev = docblock;
docblock = docblock.replace(multilineRe, "\n$1 $2\n");
}
docblock = docblock.trim();
var result = [];
var match;
while (match = propertyRe.exec(docblock)) {
result.push([match[1], match[2]]);
}
return result;
}
/**
* Same as parse but returns an object of prop: value instead of array of paris
* If a property appers more than once the last one will be returned
*
* @param {String} contents
* @return {Object}
*/
function parseAsObject(docblock) {
var pairs = parse(docblock);
var result = {};
for (var i = 0; i < pairs.length; i++) {
result[pairs[i][0]] = pairs[i][1];
}
return result;
}
exports.extract = extract;
exports.parse = parse;
exports.parseAsObject = parseAsObject;
},{}],22:[function(_dereq_,module,exports){
/**
* Copyright 2013 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.
*/
/*jslint node: true*/
"use strict";
var esprima = _dereq_('esprima-fb');
var utils = _dereq_('./utils');
var getBoundaryNode = utils.getBoundaryNode;
var declareIdentInScope = utils.declareIdentInLocalScope;
var initScopeMetadata = utils.initScopeMetadata;
var Syntax = esprima.Syntax;
/**
* @param {object} node
* @param {object} parentNode
* @return {boolean}
*/
function _nodeIsClosureScopeBoundary(node, parentNode) {
if (node.type === Syntax.Program) {
return true;
}
var parentIsFunction =
parentNode.type === Syntax.FunctionDeclaration
|| parentNode.type === Syntax.FunctionExpression
|| parentNode.type === Syntax.ArrowFunctionExpression;
var parentIsCurlylessArrowFunc =
parentNode.type === Syntax.ArrowFunctionExpression
&& node === parentNode.body;
return parentIsFunction
&& (node.type === Syntax.BlockStatement || parentIsCurlylessArrowFunc);
}
function _nodeIsBlockScopeBoundary(node, parentNode) {
if (node.type === Syntax.Program) {
return false;
}
return node.type === Syntax.BlockStatement
&& parentNode.type === Syntax.CatchClause;
}
/**
* @param {object} node
* @param {array} path
* @param {object} state
*/
function traverse(node, path, state) {
/*jshint -W004*/
// Create a scope stack entry if this is the first node we've encountered in
// its local scope
var startIndex = null;
var parentNode = path[0];
if (!Array.isArray(node) && state.localScope.parentNode !== parentNode) {
if (_nodeIsClosureScopeBoundary(node, parentNode)) {
var scopeIsStrict = state.scopeIsStrict;
if (!scopeIsStrict
&& (node.type === Syntax.BlockStatement
|| node.type === Syntax.Program)) {
scopeIsStrict =
node.body.length > 0
&& node.body[0].type === Syntax.ExpressionStatement
&& node.body[0].expression.type === Syntax.Literal
&& node.body[0].expression.value === 'use strict';
}
if (node.type === Syntax.Program) {
startIndex = state.g.buffer.length;
state = utils.updateState(state, {
scopeIsStrict: scopeIsStrict
});
} else {
startIndex = state.g.buffer.length + 1;
state = utils.updateState(state, {
localScope: {
parentNode: parentNode,
parentScope: state.localScope,
identifiers: {},
tempVarIndex: 0,
tempVars: []
},
scopeIsStrict: scopeIsStrict
});
// All functions have an implicit 'arguments' object in scope
declareIdentInScope('arguments', initScopeMetadata(node), state);
// Include function arg identifiers in the scope boundaries of the
// function
if (parentNode.params.length > 0) {
var param;
var metadata = initScopeMetadata(parentNode, path.slice(1), path[0]);
for (var i = 0; i < parentNode.params.length; i++) {
param = parentNode.params[i];
if (param.type === Syntax.Identifier) {
declareIdentInScope(param.name, metadata, state);
}
}
}
// Include rest arg identifiers in the scope boundaries of their
// functions
if (parentNode.rest) {
var metadata = initScopeMetadata(
parentNode,
path.slice(1),
path[0]
);
declareIdentInScope(parentNode.rest.name, metadata, state);
}
// Named FunctionExpressions scope their name within the body block of
// themselves only
if (parentNode.type === Syntax.FunctionExpression && parentNode.id) {
var metaData =
initScopeMetadata(parentNode, path.parentNodeslice, parentNode);
declareIdentInScope(parentNode.id.name, metaData, state);
}
}
// Traverse and find all local identifiers in this closure first to
// account for function/variable declaration hoisting
collectClosureIdentsAndTraverse(node, path, state);
}
if (_nodeIsBlockScopeBoundary(node, parentNode)) {
startIndex = state.g.buffer.length;
state = utils.updateState(state, {
localScope: {
parentNode: parentNode,
parentScope: state.localScope,
identifiers: {},
tempVarIndex: 0,
tempVars: []
}
});
if (parentNode.type === Syntax.CatchClause) {
var metadata = initScopeMetadata(
parentNode,
path.slice(1),
parentNode
);
declareIdentInScope(parentNode.param.name, metadata, state);
}
collectBlockIdentsAndTraverse(node, path, state);
}
}
// Only catchup() before and after traversing a child node
function traverser(node, path, state) {
node.range && utils.catchup(node.range[0], state);
traverse(node, path, state);
node.range && utils.catchup(node.range[1], state);
}
utils.analyzeAndTraverse(walker, traverser, node, path, state);
// Inject temp variables into the scope.
if (startIndex !== null) {
utils.injectTempVarDeclarations(state, startIndex);
}
}
function collectClosureIdentsAndTraverse(node, path, state) {
utils.analyzeAndTraverse(
visitLocalClosureIdentifiers,
collectClosureIdentsAndTraverse,
node,
path,
state
);
}
function collectBlockIdentsAndTraverse(node, path, state) {
utils.analyzeAndTraverse(
visitLocalBlockIdentifiers,
collectBlockIdentsAndTraverse,
node,
path,
state
);
}
function visitLocalClosureIdentifiers(node, path, state) {
var metaData;
switch (node.type) {
case Syntax.ArrowFunctionExpression:
case Syntax.FunctionExpression:
// Function expressions don't get their names (if there is one) added to
// the closure scope they're defined in
return false;
case Syntax.ClassDeclaration:
case Syntax.ClassExpression:
case Syntax.FunctionDeclaration:
if (node.id) {
metaData = initScopeMetadata(getBoundaryNode(path), path.slice(), node);
declareIdentInScope(node.id.name, metaData, state);
}
return false;
case Syntax.VariableDeclarator:
// Variables have function-local scope
if (path[0].kind === 'var') {
metaData = initScopeMetadata(getBoundaryNode(path), path.slice(), node);
declareIdentInScope(node.id.name, metaData, state);
}
break;
}
}
function visitLocalBlockIdentifiers(node, path, state) {
// TODO: Support 'let' here...maybe...one day...or something...
if (node.type === Syntax.CatchClause) {
return false;
}
}
function walker(node, path, state) {
var visitors = state.g.visitors;
for (var i = 0; i < visitors.length; i++) {
if (visitors[i].test(node, path, state)) {
return visitors[i](traverse, node, path, state);
}
}
}
var _astCache = {};
function getAstForSource(source, options) {
if (_astCache[source] && !options.disableAstCache) {
return _astCache[source];
}
var ast = esprima.parse(source, {
comment: true,
loc: true,
range: true,
sourceType: options.sourceType
});
if (!options.disableAstCache) {
_astCache[source] = ast;
}
return ast;
}
/**
* Applies all available transformations to the source
* @param {array} visitors
* @param {string} source
* @param {?object} options
* @return {object}
*/
function transform(visitors, source, options) {
options = options || {};
var ast;
try {
ast = getAstForSource(source, options);
} catch (e) {
e.message = 'Parse Error: ' + e.message;
throw e;
}
var state = utils.createState(source, ast, options);
state.g.visitors = visitors;
if (options.sourceMap) {
var SourceMapGenerator = _dereq_('source-map').SourceMapGenerator;
state.g.sourceMap = new SourceMapGenerator({file: options.filename || 'transformed.js'});
}
traverse(ast, [], state);
utils.catchup(source.length, state);
var ret = {code: state.g.buffer, extra: state.g.extra};
if (options.sourceMap) {
ret.sourceMap = state.g.sourceMap;
ret.sourceMapFilename = options.filename || 'source.js';
}
return ret;
}
exports.transform = transform;
exports.Syntax = Syntax;
},{"./utils":23,"esprima-fb":9,"source-map":11}],23:[function(_dereq_,module,exports){
/**
* Copyright 2013 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.
*/
/*jslint node: true*/
var Syntax = _dereq_('esprima-fb').Syntax;
var leadingIndentRegexp = /(^|\n)( {2}|\t)/g;
var nonWhiteRegexp = /(\S)/g;
/**
* A `state` object represents the state of the parser. It has "local" and
* "global" parts. Global contains parser position, source, etc. Local contains
* scope based properties like current class name. State should contain all the
* info required for transformation. It's the only mandatory object that is
* being passed to every function in transform chain.
*
* @param {string} source
* @param {object} transformOptions
* @return {object}
*/
function createState(source, rootNode, transformOptions) {
return {
/**
* A tree representing the current local scope (and its lexical scope chain)
* Useful for tracking identifiers from parent scopes, etc.
* @type {Object}
*/
localScope: {
parentNode: rootNode,
parentScope: null,
identifiers: {},
tempVarIndex: 0,
tempVars: []
},
/**
* The name (and, if applicable, expression) of the super class
* @type {Object}
*/
superClass: null,
/**
* The namespace to use when munging identifiers
* @type {String}
*/
mungeNamespace: '',
/**
* Ref to the node for the current MethodDefinition
* @type {Object}
*/
methodNode: null,
/**
* Ref to the node for the FunctionExpression of the enclosing
* MethodDefinition
* @type {Object}
*/
methodFuncNode: null,
/**
* Name of the enclosing class
* @type {String}
*/
className: null,
/**
* Whether we're currently within a `strict` scope
* @type {Bool}
*/
scopeIsStrict: null,
/**
* Indentation offset
* @type {Number}
*/
indentBy: 0,
/**
* Global state (not affected by updateState)
* @type {Object}
*/
g: {
/**
* A set of general options that transformations can consider while doing
* a transformation:
*
* - minify
* Specifies that transformation steps should do their best to minify
* the output source when possible. This is useful for places where
* minification optimizations are possible with higher-level context
* info than what jsxmin can provide.
*
* For example, the ES6 class transform will minify munged private
* variables if this flag is set.
*/
opts: transformOptions,
/**
* Current position in the source code
* @type {Number}
*/
position: 0,
/**
* Auxiliary data to be returned by transforms
* @type {Object}
*/
extra: {},
/**
* Buffer containing the result
* @type {String}
*/
buffer: '',
/**
* Source that is being transformed
* @type {String}
*/
source: source,
/**
* Cached parsed docblock (see getDocblock)
* @type {object}
*/
docblock: null,
/**
* Whether the thing was used
* @type {Boolean}
*/
tagNamespaceUsed: false,
/**
* If using bolt xjs transformation
* @type {Boolean}
*/
isBolt: undefined,
/**
* Whether to record source map (expensive) or not
* @type {SourceMapGenerator|null}
*/
sourceMap: null,
/**
* Filename of the file being processed. Will be returned as a source
* attribute in the source map
*/
sourceMapFilename: 'source.js',
/**
* Only when source map is used: last line in the source for which
* source map was generated
* @type {Number}
*/
sourceLine: 1,
/**
* Only when source map is used: last line in the buffer for which
* source map was generated
* @type {Number}
*/
bufferLine: 1,
/**
* The top-level Program AST for the original file.
*/
originalProgramAST: null,
sourceColumn: 0,
bufferColumn: 0
}
};
}
/**
* Updates a copy of a given state with "update" and returns an updated state.
*
* @param {object} state
* @param {object} update
* @return {object}
*/
function updateState(state, update) {
var ret = Object.create(state);
Object.keys(update).forEach(function(updatedKey) {
ret[updatedKey] = update[updatedKey];
});
return ret;
}
/**
* Given a state fill the resulting buffer from the original source up to
* the end
*
* @param {number} end
* @param {object} state
* @param {?function} contentTransformer Optional callback to transform newly
* added content.
*/
function catchup(end, state, contentTransformer) {
if (end < state.g.position) {
// cannot move backwards
return;
}
var source = state.g.source.substring(state.g.position, end);
var transformed = updateIndent(source, state);
if (state.g.sourceMap && transformed) {
// record where we are
state.g.sourceMap.addMapping({
generated: { line: state.g.bufferLine, column: state.g.bufferColumn },
original: { line: state.g.sourceLine, column: state.g.sourceColumn },
source: state.g.sourceMapFilename
});
// record line breaks in transformed source
var sourceLines = source.split('\n');
var transformedLines = transformed.split('\n');
// Add line break mappings between last known mapping and the end of the
// added piece. So for the code piece
// (foo, bar);
// > var x = 2;
// > var b = 3;
// var c =
// only add lines marked with ">": 2, 3.
for (var i = 1; i < sourceLines.length - 1; i++) {
state.g.sourceMap.addMapping({
generated: { line: state.g.bufferLine, column: 0 },
original: { line: state.g.sourceLine, column: 0 },
source: state.g.sourceMapFilename
});
state.g.sourceLine++;
state.g.bufferLine++;
}
// offset for the last piece
if (sourceLines.length > 1) {
state.g.sourceLine++;
state.g.bufferLine++;
state.g.sourceColumn = 0;
state.g.bufferColumn = 0;
}
state.g.sourceColumn += sourceLines[sourceLines.length - 1].length;
state.g.bufferColumn +=
transformedLines[transformedLines.length - 1].length;
}
state.g.buffer +=
contentTransformer ? contentTransformer(transformed) : transformed;
state.g.position = end;
}
/**
* Returns original source for an AST node.
* @param {object} node
* @param {object} state
* @return {string}
*/
function getNodeSourceText(node, state) {
return state.g.source.substring(node.range[0], node.range[1]);
}
function _replaceNonWhite(value) {
return value.replace(nonWhiteRegexp, ' ');
}
/**
* Removes all non-whitespace characters
*/
function _stripNonWhite(value) {
return value.replace(nonWhiteRegexp, '');
}
/**
* Finds the position of the next instance of the specified syntactic char in
* the pending source.
*
* NOTE: This will skip instances of the specified char if they sit inside a
* comment body.
*
* NOTE: This function also assumes that the buffer's current position is not
* already within a comment or a string. This is rarely the case since all
* of the buffer-advancement utility methods tend to be used on syntactic
* nodes' range values -- but it's a small gotcha that's worth mentioning.
*/
function getNextSyntacticCharOffset(char, state) {
var pendingSource = state.g.source.substring(state.g.position);
var pendingSourceLines = pendingSource.split('\n');
var charOffset = 0;
var line;
var withinBlockComment = false;
var withinString = false;
lineLoop: while ((line = pendingSourceLines.shift()) !== undefined) {
var lineEndPos = charOffset + line.length;
charLoop: for (; charOffset < lineEndPos; charOffset++) {
var currChar = pendingSource[charOffset];
if (currChar === '"' || currChar === '\'') {
withinString = !withinString;
continue charLoop;
} else if (withinString) {
continue charLoop;
} else if (charOffset + 1 < lineEndPos) {
var nextTwoChars = currChar + line[charOffset + 1];
if (nextTwoChars === '//') {
charOffset = lineEndPos + 1;
continue lineLoop;
} else if (nextTwoChars === '/*') {
withinBlockComment = true;
charOffset += 1;
continue charLoop;
} else if (nextTwoChars === '*/') {
withinBlockComment = false;
charOffset += 1;
continue charLoop;
}
}
if (!withinBlockComment && currChar === char) {
return charOffset + state.g.position;
}
}
// Account for '\n'
charOffset++;
withinString = false;
}
throw new Error('`' + char + '` not found!');
}
/**
* Catches up as `catchup` but replaces non-whitespace chars with spaces.
*/
function catchupWhiteOut(end, state) {
catchup(end, state, _replaceNonWhite);
}
/**
* Catches up as `catchup` but removes all non-whitespace characters.
*/
function catchupWhiteSpace(end, state) {
catchup(end, state, _stripNonWhite);
}
/**
* Removes all non-newline characters
*/
var reNonNewline = /[^\n]/g;
function stripNonNewline(value) {
return value.replace(reNonNewline, function() {
return '';
});
}
/**
* Catches up as `catchup` but removes all non-newline characters.
*
* Equivalent to appending as many newlines as there are in the original source
* between the current position and `end`.
*/
function catchupNewlines(end, state) {
catchup(end, state, stripNonNewline);
}
/**
* Same as catchup but does not touch the buffer
*
* @param {number} end
* @param {object} state
*/
function move(end, state) {
// move the internal cursors
if (state.g.sourceMap) {
if (end < state.g.position) {
state.g.position = 0;
state.g.sourceLine = 1;
state.g.sourceColumn = 0;
}
var source = state.g.source.substring(state.g.position, end);
var sourceLines = source.split('\n');
if (sourceLines.length > 1) {
state.g.sourceLine += sourceLines.length - 1;
state.g.sourceColumn = 0;
}
state.g.sourceColumn += sourceLines[sourceLines.length - 1].length;
}
state.g.position = end;
}
/**
* Appends a string of text to the buffer
*
* @param {string} str
* @param {object} state
*/
function append(str, state) {
if (state.g.sourceMap && str) {
state.g.sourceMap.addMapping({
generated: { line: state.g.bufferLine, column: state.g.bufferColumn },
original: { line: state.g.sourceLine, column: state.g.sourceColumn },
source: state.g.sourceMapFilename
});
var transformedLines = str.split('\n');
if (transformedLines.length > 1) {
state.g.bufferLine += transformedLines.length - 1;
state.g.bufferColumn = 0;
}
state.g.bufferColumn +=
transformedLines[transformedLines.length - 1].length;
}
state.g.buffer += str;
}
/**
* Update indent using state.indentBy property. Indent is measured in
* double spaces. Updates a single line only.
*
* @param {string} str
* @param {object} state
* @return {string}
*/
function updateIndent(str, state) {
/*jshint -W004*/
var indentBy = state.indentBy;
if (indentBy < 0) {
for (var i = 0; i < -indentBy; i++) {
str = str.replace(leadingIndentRegexp, '$1');
}
} else {
for (var i = 0; i < indentBy; i++) {
str = str.replace(leadingIndentRegexp, '$1$2$2');
}
}
return str;
}
/**
* Calculates indent from the beginning of the line until "start" or the first
* character before start.
* @example
* " foo.bar()"
* ^
* start
* indent will be " "
*
* @param {number} start
* @param {object} state
* @return {string}
*/
function indentBefore(start, state) {
var end = start;
start = start - 1;
while (start > 0 && state.g.source[start] != '\n') {
if (!state.g.source[start].match(/[ \t]/)) {
end = start;
}
start--;
}
return state.g.source.substring(start + 1, end);
}
function getDocblock(state) {
if (!state.g.docblock) {
var docblock = _dereq_('./docblock');
state.g.docblock =
docblock.parseAsObject(docblock.extract(state.g.source));
}
return state.g.docblock;
}
function identWithinLexicalScope(identName, state, stopBeforeNode) {
var currScope = state.localScope;
while (currScope) {
if (currScope.identifiers[identName] !== undefined) {
return true;
}
if (stopBeforeNode && currScope.parentNode === stopBeforeNode) {
break;
}
currScope = currScope.parentScope;
}
return false;
}
function identInLocalScope(identName, state) {
return state.localScope.identifiers[identName] !== undefined;
}
/**
* @param {object} boundaryNode
* @param {?array} path
* @return {?object} node
*/
function initScopeMetadata(boundaryNode, path, node) {
return {
boundaryNode: boundaryNode,
bindingPath: path,
bindingNode: node
};
}
function declareIdentInLocalScope(identName, metaData, state) {
state.localScope.identifiers[identName] = {
boundaryNode: metaData.boundaryNode,
path: metaData.bindingPath,
node: metaData.bindingNode,
state: Object.create(state)
};
}
function getLexicalBindingMetadata(identName, state) {
var currScope = state.localScope;
while (currScope) {
if (currScope.identifiers[identName] !== undefined) {
return currScope.identifiers[identName];
}
currScope = currScope.parentScope;
}
}
function getLocalBindingMetadata(identName, state) {
return state.localScope.identifiers[identName];
}
/**
* Apply the given analyzer function to the current node. If the analyzer
* doesn't return false, traverse each child of the current node using the given
* traverser function.
*
* @param {function} analyzer
* @param {function} traverser
* @param {object} node
* @param {array} path
* @param {object} state
*/
function analyzeAndTraverse(analyzer, traverser, node, path, state) {
if (node.type) {
if (analyzer(node, path, state) === false) {
return;
}
path.unshift(node);
}
getOrderedChildren(node).forEach(function(child) {
traverser(child, path, state);
});
node.type && path.shift();
}
/**
* It is crucial that we traverse in order, or else catchup() on a later
* node that is processed out of order can move the buffer past a node
* that we haven't handled yet, preventing us from modifying that node.
*
* This can happen when a node has multiple properties containing children.
* For example, XJSElement nodes have `openingElement`, `closingElement` and
* `children`. If we traverse `openingElement`, then `closingElement`, then
* when we get to `children`, the buffer has already caught up to the end of
* the closing element, after the children.
*
* This is basically a Schwartzian transform. Collects an array of children,
* each one represented as [child, startIndex]; sorts the array by start
* index; then traverses the children in that order.
*/
function getOrderedChildren(node) {
var queue = [];
for (var key in node) {
if (node.hasOwnProperty(key)) {
enqueueNodeWithStartIndex(queue, node[key]);
}
}
queue.sort(function(a, b) { return a[1] - b[1]; });
return queue.map(function(pair) { return pair[0]; });
}
/**
* Helper function for analyzeAndTraverse which queues up all of the children
* of the given node.
*
* Children can also be found in arrays, so we basically want to merge all of
* those arrays together so we can sort them and then traverse the children
* in order.
*
* One example is the Program node. It contains `body` and `comments`, both
* arrays. Lexographically, comments are interspersed throughout the body
* nodes, but esprima's AST groups them together.
*/
function enqueueNodeWithStartIndex(queue, node) {
if (typeof node !== 'object' || node === null) {
return;
}
if (node.range) {
queue.push([node, node.range[0]]);
} else if (Array.isArray(node)) {
for (var ii = 0; ii < node.length; ii++) {
enqueueNodeWithStartIndex(queue, node[ii]);
}
}
}
/**
* Checks whether a node or any of its sub-nodes contains
* a syntactic construct of the passed type.
* @param {object} node - AST node to test.
* @param {string} type - node type to lookup.
*/
function containsChildOfType(node, type) {
return containsChildMatching(node, function(node) {
return node.type === type;
});
}
function containsChildMatching(node, matcher) {
var foundMatchingChild = false;
function nodeTypeAnalyzer(node) {
if (matcher(node) === true) {
foundMatchingChild = true;
return false;
}
}
function nodeTypeTraverser(child, path, state) {
if (!foundMatchingChild) {
foundMatchingChild = containsChildMatching(child, matcher);
}
}
analyzeAndTraverse(
nodeTypeAnalyzer,
nodeTypeTraverser,
node,
[]
);
return foundMatchingChild;
}
var scopeTypes = {};
scopeTypes[Syntax.ArrowFunctionExpression] = true;
scopeTypes[Syntax.FunctionExpression] = true;
scopeTypes[Syntax.FunctionDeclaration] = true;
scopeTypes[Syntax.Program] = true;
function getBoundaryNode(path) {
for (var ii = 0; ii < path.length; ++ii) {
if (scopeTypes[path[ii].type]) {
return path[ii];
}
}
throw new Error(
'Expected to find a node with one of the following types in path:\n' +
JSON.stringify(Object.keys(scopeTypes))
);
}
function getTempVar(tempVarIndex) {
return '$__' + tempVarIndex;
}
function injectTempVar(state) {
var tempVar = '$__' + (state.localScope.tempVarIndex++);
state.localScope.tempVars.push(tempVar);
return tempVar;
}
function injectTempVarDeclarations(state, index) {
if (state.localScope.tempVars.length) {
state.g.buffer =
state.g.buffer.slice(0, index) +
'var ' + state.localScope.tempVars.join(', ') + ';' +
state.g.buffer.slice(index);
state.localScope.tempVars = [];
}
}
exports.analyzeAndTraverse = analyzeAndTraverse;
exports.append = append;
exports.catchup = catchup;
exports.catchupNewlines = catchupNewlines;
exports.catchupWhiteOut = catchupWhiteOut;
exports.catchupWhiteSpace = catchupWhiteSpace;
exports.containsChildMatching = containsChildMatching;
exports.containsChildOfType = containsChildOfType;
exports.createState = createState;
exports.declareIdentInLocalScope = declareIdentInLocalScope;
exports.getBoundaryNode = getBoundaryNode;
exports.getDocblock = getDocblock;
exports.getLexicalBindingMetadata = getLexicalBindingMetadata;
exports.getLocalBindingMetadata = getLocalBindingMetadata;
exports.getNextSyntacticCharOffset = getNextSyntacticCharOffset;
exports.getNodeSourceText = getNodeSourceText;
exports.getOrderedChildren = getOrderedChildren;
exports.getTempVar = getTempVar;
exports.identInLocalScope = identInLocalScope;
exports.identWithinLexicalScope = identWithinLexicalScope;
exports.indentBefore = indentBefore;
exports.initScopeMetadata = initScopeMetadata;
exports.injectTempVar = injectTempVar;
exports.injectTempVarDeclarations = injectTempVarDeclarations;
exports.move = move;
exports.scopeTypes = scopeTypes;
exports.updateIndent = updateIndent;
exports.updateState = updateState;
},{"./docblock":21,"esprima-fb":9}],24:[function(_dereq_,module,exports){
/**
* Copyright 2013 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.
*/
/*global exports:true*/
/**
* Desugars ES6 Arrow functions to ES3 function expressions.
* If the function contains `this` expression -- automatically
* binds the function to current value of `this`.
*
* Single parameter, simple expression:
*
* [1, 2, 3].map(x => x * x);
*
* [1, 2, 3].map(function(x) { return x * x; });
*
* Several parameters, complex block:
*
* this.users.forEach((user, idx) => {
* return this.isActive(idx) && this.send(user);
* });
*
* this.users.forEach(function(user, idx) {
* return this.isActive(idx) && this.send(user);
* }.bind(this));
*
*/
var restParamVisitors = _dereq_('./es6-rest-param-visitors');
var destructuringVisitors = _dereq_('./es6-destructuring-visitors');
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
/**
* @public
*/
function visitArrowFunction(traverse, node, path, state) {
var notInExpression = (path[0].type === Syntax.ExpressionStatement);
// Wrap a function into a grouping operator, if it's not
// in the expression position.
if (notInExpression) {
utils.append('(', state);
}
utils.append('function', state);
renderParams(traverse, node, path, state);
// Skip arrow.
utils.catchupWhiteSpace(node.body.range[0], state);
var renderBody = node.body.type == Syntax.BlockStatement
? renderStatementBody
: renderExpressionBody;
path.unshift(node);
renderBody(traverse, node, path, state);
path.shift();
// Bind the function only if `this` value is used
// inside it or inside any sub-expression.
var containsBindingSyntax =
utils.containsChildMatching(node.body, function(node) {
return node.type === Syntax.ThisExpression
|| (node.type === Syntax.Identifier
&& node.name === "super");
});
if (containsBindingSyntax) {
utils.append('.bind(this)', state);
}
utils.catchupWhiteSpace(node.range[1], state);
// Close wrapper if not in the expression.
if (notInExpression) {
utils.append(')', state);
}
return false;
}
function renderParams(traverse, node, path, state) {
// To preserve inline typechecking directives, we
// distinguish between parens-free and paranthesized single param.
if (isParensFreeSingleParam(node, state) || !node.params.length) {
utils.append('(', state);
}
if (node.params.length !== 0) {
path.unshift(node);
traverse(node.params, path, state);
path.unshift();
}
utils.append(')', state);
}
function isParensFreeSingleParam(node, state) {
return node.params.length === 1 &&
state.g.source[state.g.position] !== '(';
}
function renderExpressionBody(traverse, node, path, state) {
// Wrap simple expression bodies into a block
// with explicit return statement.
utils.append('{', state);
// Special handling of rest param.
if (node.rest) {
utils.append(
restParamVisitors.renderRestParamSetup(node, state),
state
);
}
// Special handling of destructured params.
destructuringVisitors.renderDestructuredComponents(
node,
utils.updateState(state, {
localScope: {
parentNode: state.parentNode,
parentScope: state.parentScope,
identifiers: state.identifiers,
tempVarIndex: 0
}
})
);
utils.append('return ', state);
renderStatementBody(traverse, node, path, state);
utils.append(';}', state);
}
function renderStatementBody(traverse, node, path, state) {
traverse(node.body, path, state);
utils.catchup(node.body.range[1], state);
}
visitArrowFunction.test = function(node, path, state) {
return node.type === Syntax.ArrowFunctionExpression;
};
exports.visitorList = [
visitArrowFunction
];
},{"../src/utils":23,"./es6-destructuring-visitors":27,"./es6-rest-param-visitors":30,"esprima-fb":9}],25:[function(_dereq_,module,exports){
/**
* Copyright 2004-present Facebook. All Rights Reserved.
*/
/*global exports:true*/
/**
* Implements ES6 call spread.
*
* instance.method(a, b, c, ...d)
*
* instance.method.apply(instance, [a, b, c].concat(d))
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
function process(traverse, node, path, state) {
utils.move(node.range[0], state);
traverse(node, path, state);
utils.catchup(node.range[1], state);
}
function visitCallSpread(traverse, node, path, state) {
utils.catchup(node.range[0], state);
if (node.type === Syntax.NewExpression) {
// Input = new Set(1, 2, ...list)
// Output = new (Function.prototype.bind.apply(Set, [null, 1, 2].concat(list)))
utils.append('new (Function.prototype.bind.apply(', state);
process(traverse, node.callee, path, state);
} else if (node.callee.type === Syntax.MemberExpression) {
// Input = get().fn(1, 2, ...more)
// Output = (_ = get()).fn.apply(_, [1, 2].apply(more))
var tempVar = utils.injectTempVar(state);
utils.append('(' + tempVar + ' = ', state);
process(traverse, node.callee.object, path, state);
utils.append(')', state);
if (node.callee.property.type === Syntax.Identifier) {
utils.append('.', state);
process(traverse, node.callee.property, path, state);
} else {
utils.append('[', state);
process(traverse, node.callee.property, path, state);
utils.append(']', state);
}
utils.append('.apply(' + tempVar, state);
} else {
// Input = max(1, 2, ...list)
// Output = max.apply(null, [1, 2].concat(list))
var needsToBeWrappedInParenthesis =
node.callee.type === Syntax.FunctionDeclaration ||
node.callee.type === Syntax.FunctionExpression;
if (needsToBeWrappedInParenthesis) {
utils.append('(', state);
}
process(traverse, node.callee, path, state);
if (needsToBeWrappedInParenthesis) {
utils.append(')', state);
}
utils.append('.apply(null', state);
}
utils.append(', ', state);
var args = node.arguments.slice();
var spread = args.pop();
if (args.length || node.type === Syntax.NewExpression) {
utils.append('[', state);
if (node.type === Syntax.NewExpression) {
utils.append('null' + (args.length ? ', ' : ''), state);
}
while (args.length) {
var arg = args.shift();
utils.move(arg.range[0], state);
traverse(arg, path, state);
if (args.length) {
utils.catchup(args[0].range[0], state);
} else {
utils.catchup(arg.range[1], state);
}
}
utils.append('].concat(', state);
process(traverse, spread.argument, path, state);
utils.append(')', state);
} else {
process(traverse, spread.argument, path, state);
}
utils.append(node.type === Syntax.NewExpression ? '))' : ')', state);
utils.move(node.range[1], state);
return false;
}
visitCallSpread.test = function(node, path, state) {
return (
(
node.type === Syntax.CallExpression ||
node.type === Syntax.NewExpression
) &&
node.arguments.length > 0 &&
node.arguments[node.arguments.length - 1].type === Syntax.SpreadElement
);
};
exports.visitorList = [
visitCallSpread
];
},{"../src/utils":23,"esprima-fb":9}],26:[function(_dereq_,module,exports){
/**
* Copyright 2013 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.
*/
/*jslint node:true*/
/**
* @typechecks
*/
'use strict';
var base62 = _dereq_('base62');
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
var reservedWordsHelper = _dereq_('./reserved-words-helper');
var declareIdentInLocalScope = utils.declareIdentInLocalScope;
var initScopeMetadata = utils.initScopeMetadata;
var SUPER_PROTO_IDENT_PREFIX = '____SuperProtoOf';
var _anonClassUUIDCounter = 0;
var _mungedSymbolMaps = {};
function resetSymbols() {
_anonClassUUIDCounter = 0;
_mungedSymbolMaps = {};
}
/**
* Used to generate a unique class for use with code-gens for anonymous class
* expressions.
*
* @param {object} state
* @return {string}
*/
function _generateAnonymousClassName(state) {
var mungeNamespace = state.mungeNamespace || '';
return '____Class' + mungeNamespace + base62.encode(_anonClassUUIDCounter++);
}
/**
* Given an identifier name, munge it using the current state's mungeNamespace.
*
* @param {string} identName
* @param {object} state
* @return {string}
*/
function _getMungedName(identName, state) {
var mungeNamespace = state.mungeNamespace;
var shouldMinify = state.g.opts.minify;
if (shouldMinify) {
if (!_mungedSymbolMaps[mungeNamespace]) {
_mungedSymbolMaps[mungeNamespace] = {
symbolMap: {},
identUUIDCounter: 0
};
}
var symbolMap = _mungedSymbolMaps[mungeNamespace].symbolMap;
if (!symbolMap[identName]) {
symbolMap[identName] =
base62.encode(_mungedSymbolMaps[mungeNamespace].identUUIDCounter++);
}
identName = symbolMap[identName];
}
return '$' + mungeNamespace + identName;
}
/**
* Extracts super class information from a class node.
*
* Information includes name of the super class and/or the expression string
* (if extending from an expression)
*
* @param {object} node
* @param {object} state
* @return {object}
*/
function _getSuperClassInfo(node, state) {
var ret = {
name: null,
expression: null
};
if (node.superClass) {
if (node.superClass.type === Syntax.Identifier) {
ret.name = node.superClass.name;
} else {
// Extension from an expression
ret.name = _generateAnonymousClassName(state);
ret.expression = state.g.source.substring(
node.superClass.range[0],
node.superClass.range[1]
);
}
}
return ret;
}
/**
* Used with .filter() to find the constructor method in a list of
* MethodDefinition nodes.
*
* @param {object} classElement
* @return {boolean}
*/
function _isConstructorMethod(classElement) {
return classElement.type === Syntax.MethodDefinition &&
classElement.key.type === Syntax.Identifier &&
classElement.key.name === 'constructor';
}
/**
* @param {object} node
* @param {object} state
* @return {boolean}
*/
function _shouldMungeIdentifier(node, state) {
return (
!!state.methodFuncNode &&
!utils.getDocblock(state).hasOwnProperty('preventMunge') &&
/^_(?!_)/.test(node.name)
);
}
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassMethod(traverse, node, path, state) {
if (!state.g.opts.es5 && (node.kind === 'get' || node.kind === 'set')) {
throw new Error(
'This transform does not support ' + node.kind + 'ter methods for ES6 ' +
'classes. (line: ' + node.loc.start.line + ', col: ' +
node.loc.start.column + ')'
);
}
state = utils.updateState(state, {
methodNode: node
});
utils.catchup(node.range[0], state);
path.unshift(node);
traverse(node.value, path, state);
path.shift();
return false;
}
visitClassMethod.test = function(node, path, state) {
return node.type === Syntax.MethodDefinition;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassFunctionExpression(traverse, node, path, state) {
var methodNode = path[0];
var isGetter = methodNode.kind === 'get';
var isSetter = methodNode.kind === 'set';
state = utils.updateState(state, {
methodFuncNode: node
});
if (methodNode.key.name === 'constructor') {
utils.append('function ' + state.className, state);
} else {
var methodAccessorComputed = false;
var methodAccessor;
var prototypeOrStatic = methodNode["static"] ? '' : '.prototype';
var objectAccessor = state.className + prototypeOrStatic;
if (methodNode.key.type === Syntax.Identifier) {
// foo() {}
methodAccessor = methodNode.key.name;
if (_shouldMungeIdentifier(methodNode.key, state)) {
methodAccessor = _getMungedName(methodAccessor, state);
}
if (isGetter || isSetter) {
methodAccessor = JSON.stringify(methodAccessor);
} else if (reservedWordsHelper.isReservedWord(methodAccessor)) {
methodAccessorComputed = true;
methodAccessor = JSON.stringify(methodAccessor);
}
} else if (methodNode.key.type === Syntax.Literal) {
// 'foo bar'() {} | get 'foo bar'() {} | set 'foo bar'() {}
methodAccessor = JSON.stringify(methodNode.key.value);
methodAccessorComputed = true;
}
if (isSetter || isGetter) {
utils.append(
'Object.defineProperty(' +
objectAccessor + ',' +
methodAccessor + ',' +
'{configurable:true,' +
methodNode.kind + ':function',
state
);
} else {
if (state.g.opts.es3) {
if (methodAccessorComputed) {
methodAccessor = '[' + methodAccessor + ']';
} else {
methodAccessor = '.' + methodAccessor;
}
utils.append(
objectAccessor +
methodAccessor + '=function' + (node.generator ? '*' : ''),
state
);
} else {
if (!methodAccessorComputed) {
methodAccessor = JSON.stringify(methodAccessor);
}
utils.append(
'Object.defineProperty(' +
objectAccessor + ',' +
methodAccessor + ',' +
'{writable:true,configurable:true,' +
'value:function' + (node.generator ? '*' : ''),
state
);
}
}
}
utils.move(methodNode.key.range[1], state);
utils.append('(', state);
var params = node.params;
if (params.length > 0) {
utils.catchupNewlines(params[0].range[0], state);
for (var i = 0; i < params.length; i++) {
utils.catchup(node.params[i].range[0], state);
path.unshift(node);
traverse(params[i], path, state);
path.shift();
}
}
var closingParenPosition = utils.getNextSyntacticCharOffset(')', state);
utils.catchupWhiteSpace(closingParenPosition, state);
var openingBracketPosition = utils.getNextSyntacticCharOffset('{', state);
utils.catchup(openingBracketPosition + 1, state);
if (!state.scopeIsStrict) {
utils.append('"use strict";', state);
state = utils.updateState(state, {
scopeIsStrict: true
});
}
utils.move(node.body.range[0] + '{'.length, state);
path.unshift(node);
traverse(node.body, path, state);
path.shift();
utils.catchup(node.body.range[1], state);
if (methodNode.key.name !== 'constructor') {
if (isGetter || isSetter || !state.g.opts.es3) {
utils.append('})', state);
}
utils.append(';', state);
}
return false;
}
visitClassFunctionExpression.test = function(node, path, state) {
return node.type === Syntax.FunctionExpression
&& path[0].type === Syntax.MethodDefinition;
};
function visitClassMethodParam(traverse, node, path, state) {
var paramName = node.name;
if (_shouldMungeIdentifier(node, state)) {
paramName = _getMungedName(node.name, state);
}
utils.append(paramName, state);
utils.move(node.range[1], state);
}
visitClassMethodParam.test = function(node, path, state) {
if (!path[0] || !path[1]) {
return;
}
var parentFuncExpr = path[0];
var parentClassMethod = path[1];
return parentFuncExpr.type === Syntax.FunctionExpression
&& parentClassMethod.type === Syntax.MethodDefinition
&& node.type === Syntax.Identifier;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function _renderClassBody(traverse, node, path, state) {
var className = state.className;
var superClass = state.superClass;
// Set up prototype of constructor on same line as `extends` for line-number
// preservation. This relies on function-hoisting if a constructor function is
// defined in the class body.
if (superClass.name) {
// If the super class is an expression, we need to memoize the output of the
// expression into the generated class name variable and use that to refer
// to the super class going forward. Example:
//
// class Foo extends mixin(Bar, Baz) {}
// --transforms to--
// function Foo() {} var ____Class0Blah = mixin(Bar, Baz);
if (superClass.expression !== null) {
utils.append(
'var ' + superClass.name + '=' + superClass.expression + ';',
state
);
}
var keyName = superClass.name + '____Key';
var keyNameDeclarator = '';
if (!utils.identWithinLexicalScope(keyName, state)) {
keyNameDeclarator = 'var ';
declareIdentInLocalScope(keyName, initScopeMetadata(node), state);
}
utils.append(
'for(' + keyNameDeclarator + keyName + ' in ' + superClass.name + '){' +
'if(' + superClass.name + '.hasOwnProperty(' + keyName + ')){' +
className + '[' + keyName + ']=' +
superClass.name + '[' + keyName + '];' +
'}' +
'}',
state
);
var superProtoIdentStr = SUPER_PROTO_IDENT_PREFIX + superClass.name;
if (!utils.identWithinLexicalScope(superProtoIdentStr, state)) {
utils.append(
'var ' + superProtoIdentStr + '=' + superClass.name + '===null?' +
'null:' + superClass.name + '.prototype;',
state
);
declareIdentInLocalScope(superProtoIdentStr, initScopeMetadata(node), state);
}
utils.append(
className + '.prototype=Object.create(' + superProtoIdentStr + ');',
state
);
utils.append(
className + '.prototype.constructor=' + className + ';',
state
);
utils.append(
className + '.__superConstructor__=' + superClass.name + ';',
state
);
}
// If there's no constructor method specified in the class body, create an
// empty constructor function at the top (same line as the class keyword)
if (!node.body.body.filter(_isConstructorMethod).pop()) {
utils.append('function ' + className + '(){', state);
if (!state.scopeIsStrict) {
utils.append('"use strict";', state);
}
if (superClass.name) {
utils.append(
'if(' + superClass.name + '!==null){' +
superClass.name + '.apply(this,arguments);}',
state
);
}
utils.append('}', state);
}
utils.move(node.body.range[0] + '{'.length, state);
traverse(node.body, path, state);
utils.catchupWhiteSpace(node.range[1], state);
}
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassDeclaration(traverse, node, path, state) {
var className = node.id.name;
var superClass = _getSuperClassInfo(node, state);
state = utils.updateState(state, {
mungeNamespace: className,
className: className,
superClass: superClass
});
_renderClassBody(traverse, node, path, state);
return false;
}
visitClassDeclaration.test = function(node, path, state) {
return node.type === Syntax.ClassDeclaration;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassExpression(traverse, node, path, state) {
var className = node.id && node.id.name || _generateAnonymousClassName(state);
var superClass = _getSuperClassInfo(node, state);
utils.append('(function(){', state);
state = utils.updateState(state, {
mungeNamespace: className,
className: className,
superClass: superClass
});
_renderClassBody(traverse, node, path, state);
utils.append('return ' + className + ';})()', state);
return false;
}
visitClassExpression.test = function(node, path, state) {
return node.type === Syntax.ClassExpression;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitPrivateIdentifier(traverse, node, path, state) {
utils.append(_getMungedName(node.name, state), state);
utils.move(node.range[1], state);
}
visitPrivateIdentifier.test = function(node, path, state) {
if (node.type === Syntax.Identifier && _shouldMungeIdentifier(node, state)) {
// Always munge non-computed properties of MemberExpressions
// (a la preventing access of properties of unowned objects)
if (path[0].type === Syntax.MemberExpression && path[0].object !== node
&& path[0].computed === false) {
return true;
}
// Always munge identifiers that were declared within the method function
// scope
if (utils.identWithinLexicalScope(node.name, state, state.methodFuncNode)) {
return true;
}
// Always munge private keys on object literals defined within a method's
// scope.
if (path[0].type === Syntax.Property
&& path[1].type === Syntax.ObjectExpression) {
return true;
}
// Always munge function parameters
if (path[0].type === Syntax.FunctionExpression
|| path[0].type === Syntax.FunctionDeclaration
|| path[0].type === Syntax.ArrowFunctionExpression) {
for (var i = 0; i < path[0].params.length; i++) {
if (path[0].params[i] === node) {
return true;
}
}
}
}
return false;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitSuperCallExpression(traverse, node, path, state) {
var superClassName = state.superClass.name;
if (node.callee.type === Syntax.Identifier) {
if (_isConstructorMethod(state.methodNode)) {
utils.append(superClassName + '.call(', state);
} else {
var protoProp = SUPER_PROTO_IDENT_PREFIX + superClassName;
if (state.methodNode.key.type === Syntax.Identifier) {
protoProp += '.' + state.methodNode.key.name;
} else if (state.methodNode.key.type === Syntax.Literal) {
protoProp += '[' + JSON.stringify(state.methodNode.key.value) + ']';
}
utils.append(protoProp + ".call(", state);
}
utils.move(node.callee.range[1], state);
} else if (node.callee.type === Syntax.MemberExpression) {
utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state);
utils.move(node.callee.object.range[1], state);
if (node.callee.computed) {
// ["a" + "b"]
utils.catchup(node.callee.property.range[1] + ']'.length, state);
} else {
// .ab
utils.append('.' + node.callee.property.name, state);
}
utils.append('.call(', state);
utils.move(node.callee.range[1], state);
}
utils.append('this', state);
if (node.arguments.length > 0) {
utils.append(',', state);
utils.catchupWhiteSpace(node.arguments[0].range[0], state);
traverse(node.arguments, path, state);
}
utils.catchupWhiteSpace(node.range[1], state);
utils.append(')', state);
return false;
}
visitSuperCallExpression.test = function(node, path, state) {
if (state.superClass && node.type === Syntax.CallExpression) {
var callee = node.callee;
if (callee.type === Syntax.Identifier && callee.name === 'super'
|| callee.type == Syntax.MemberExpression
&& callee.object.name === 'super') {
return true;
}
}
return false;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitSuperMemberExpression(traverse, node, path, state) {
var superClassName = state.superClass.name;
utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state);
utils.move(node.object.range[1], state);
}
visitSuperMemberExpression.test = function(node, path, state) {
return state.superClass
&& node.type === Syntax.MemberExpression
&& node.object.type === Syntax.Identifier
&& node.object.name === 'super';
};
exports.resetSymbols = resetSymbols;
exports.visitorList = [
visitClassDeclaration,
visitClassExpression,
visitClassFunctionExpression,
visitClassMethod,
visitClassMethodParam,
visitPrivateIdentifier,
visitSuperCallExpression,
visitSuperMemberExpression
];
},{"../src/utils":23,"./reserved-words-helper":34,"base62":10,"esprima-fb":9}],27:[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.
*/
/*global exports:true*/
/**
* Implements ES6 destructuring assignment and pattern matchng.
*
* function init({port, ip, coords: [x, y]}) {
* return (x && y) ? {id, port} : {ip};
* };
*
* function init($__0) {
* var
* port = $__0.port,
* ip = $__0.ip,
* $__1 = $__0.coords,
* x = $__1[0],
* y = $__1[1];
* return (x && y) ? {id, port} : {ip};
* }
*
* var x, {ip, port} = init({ip, port});
*
* var x, $__0 = init({ip, port}), ip = $__0.ip, port = $__0.port;
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
var reservedWordsHelper = _dereq_('./reserved-words-helper');
var restParamVisitors = _dereq_('./es6-rest-param-visitors');
var restPropertyHelpers = _dereq_('./es7-rest-property-helpers');
// -------------------------------------------------------
// 1. Structured variable declarations.
//
// var [a, b] = [b, a];
// var {x, y} = {y, x};
// -------------------------------------------------------
function visitStructuredVariable(traverse, node, path, state) {
// Allocate new temp for the pattern.
utils.append(utils.getTempVar(state.localScope.tempVarIndex) + '=', state);
// Skip the pattern and assign the init to the temp.
utils.catchupWhiteSpace(node.init.range[0], state);
traverse(node.init, path, state);
utils.catchup(node.init.range[1], state);
// Render the destructured data.
utils.append(',' + getDestructuredComponents(node.id, state), state);
state.localScope.tempVarIndex++;
return false;
}
visitStructuredVariable.test = function(node, path, state) {
return node.type === Syntax.VariableDeclarator &&
isStructuredPattern(node.id);
};
function isStructuredPattern(node) {
return node.type === Syntax.ObjectPattern ||
node.type === Syntax.ArrayPattern;
}
// Main function which does actual recursive destructuring
// of nested complex structures.
function getDestructuredComponents(node, state) {
var tmpIndex = state.localScope.tempVarIndex;
var components = [];
var patternItems = getPatternItems(node);
for (var idx = 0; idx < patternItems.length; idx++) {
var item = patternItems[idx];
if (!item) {
continue;
}
if (item.type === Syntax.SpreadElement) {
// Spread/rest of an array.
// TODO(dmitrys): support spread in the middle of a pattern
// and also for function param patterns: [x, ...xs, y]
components.push(item.argument.name +
'=Array.prototype.slice.call(' +
utils.getTempVar(tmpIndex) + ',' + idx + ')'
);
continue;
}
if (item.type === Syntax.SpreadProperty) {
var restExpression = restPropertyHelpers.renderRestExpression(
utils.getTempVar(tmpIndex),
patternItems
);
components.push(item.argument.name + '=' + restExpression);
continue;
}
// Depending on pattern type (Array or Object), we get
// corresponding pattern item parts.
var accessor = getPatternItemAccessor(node, item, tmpIndex, idx);
var value = getPatternItemValue(node, item);
// TODO(dmitrys): implement default values: {x, y=5}
if (value.type === Syntax.Identifier) {
// Simple pattern item.
components.push(value.name + '=' + accessor);
} else {
// Complex sub-structure.
components.push(
utils.getTempVar(++state.localScope.tempVarIndex) + '=' + accessor +
',' + getDestructuredComponents(value, state)
);
}
}
return components.join(',');
}
function getPatternItems(node) {
return node.properties || node.elements;
}
function getPatternItemAccessor(node, patternItem, tmpIndex, idx) {
var tmpName = utils.getTempVar(tmpIndex);
if (node.type === Syntax.ObjectPattern) {
if (reservedWordsHelper.isReservedWord(patternItem.key.name)) {
return tmpName + '["' + patternItem.key.name + '"]';
} else if (patternItem.key.type === Syntax.Literal) {
return tmpName + '[' + JSON.stringify(patternItem.key.value) + ']';
} else if (patternItem.key.type === Syntax.Identifier) {
return tmpName + '.' + patternItem.key.name;
}
} else if (node.type === Syntax.ArrayPattern) {
return tmpName + '[' + idx + ']';
}
}
function getPatternItemValue(node, patternItem) {
return node.type === Syntax.ObjectPattern
? patternItem.value
: patternItem;
}
// -------------------------------------------------------
// 2. Assignment expression.
//
// [a, b] = [b, a];
// ({x, y} = {y, x});
// -------------------------------------------------------
function visitStructuredAssignment(traverse, node, path, state) {
var exprNode = node.expression;
utils.append('var ' + utils.getTempVar(state.localScope.tempVarIndex) + '=', state);
utils.catchupWhiteSpace(exprNode.right.range[0], state);
traverse(exprNode.right, path, state);
utils.catchup(exprNode.right.range[1], state);
utils.append(
';' + getDestructuredComponents(exprNode.left, state) + ';',
state
);
utils.catchupWhiteSpace(node.range[1], state);
state.localScope.tempVarIndex++;
return false;
}
visitStructuredAssignment.test = function(node, path, state) {
// We consider the expression statement rather than just assignment
// expression to cover case with object patters which should be
// wrapped in grouping operator: ({x, y} = {y, x});
return node.type === Syntax.ExpressionStatement &&
node.expression.type === Syntax.AssignmentExpression &&
isStructuredPattern(node.expression.left);
};
// -------------------------------------------------------
// 3. Structured parameter.
//
// function foo({x, y}) { ... }
// -------------------------------------------------------
function visitStructuredParameter(traverse, node, path, state) {
utils.append(utils.getTempVar(getParamIndex(node, path)), state);
utils.catchupWhiteSpace(node.range[1], state);
return true;
}
function getParamIndex(paramNode, path) {
var funcNode = path[0];
var tmpIndex = 0;
for (var k = 0; k < funcNode.params.length; k++) {
var param = funcNode.params[k];
if (param === paramNode) {
break;
}
if (isStructuredPattern(param)) {
tmpIndex++;
}
}
return tmpIndex;
}
visitStructuredParameter.test = function(node, path, state) {
return isStructuredPattern(node) && isFunctionNode(path[0]);
};
function isFunctionNode(node) {
return (node.type == Syntax.FunctionDeclaration ||
node.type == Syntax.FunctionExpression ||
node.type == Syntax.MethodDefinition ||
node.type == Syntax.ArrowFunctionExpression);
}
// -------------------------------------------------------
// 4. Function body for structured parameters.
//
// function foo({x, y}) { x; y; }
// -------------------------------------------------------
function visitFunctionBodyForStructuredParameter(traverse, node, path, state) {
var funcNode = path[0];
utils.catchup(funcNode.body.range[0] + 1, state);
renderDestructuredComponents(funcNode, state);
if (funcNode.rest) {
utils.append(
restParamVisitors.renderRestParamSetup(funcNode, state),
state
);
}
return true;
}
function renderDestructuredComponents(funcNode, state) {
var destructuredComponents = [];
for (var k = 0; k < funcNode.params.length; k++) {
var param = funcNode.params[k];
if (isStructuredPattern(param)) {
destructuredComponents.push(
getDestructuredComponents(param, state)
);
state.localScope.tempVarIndex++;
}
}
if (destructuredComponents.length) {
utils.append('var ' + destructuredComponents.join(',') + ';', state);
}
}
visitFunctionBodyForStructuredParameter.test = function(node, path, state) {
return node.type === Syntax.BlockStatement && isFunctionNode(path[0]);
};
exports.visitorList = [
visitStructuredVariable,
visitStructuredAssignment,
visitStructuredParameter,
visitFunctionBodyForStructuredParameter
];
exports.renderDestructuredComponents = renderDestructuredComponents;
},{"../src/utils":23,"./es6-rest-param-visitors":30,"./es7-rest-property-helpers":32,"./reserved-words-helper":34,"esprima-fb":9}],28:[function(_dereq_,module,exports){
/**
* Copyright 2013 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.
*/
/*jslint node:true*/
/**
* Desugars concise methods of objects to function expressions.
*
* var foo = {
* method(x, y) { ... }
* };
*
* var foo = {
* method: function(x, y) { ... }
* };
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
var reservedWordsHelper = _dereq_('./reserved-words-helper');
function visitObjectConciseMethod(traverse, node, path, state) {
var isGenerator = node.value.generator;
if (isGenerator) {
utils.catchupWhiteSpace(node.range[0] + 1, state);
}
if (node.computed) { // [<expr>]() { ...}
utils.catchup(node.key.range[1] + 1, state);
} else if (reservedWordsHelper.isReservedWord(node.key.name)) {
utils.catchup(node.key.range[0], state);
utils.append('"', state);
utils.catchup(node.key.range[1], state);
utils.append('"', state);
}
utils.catchup(node.key.range[1], state);
utils.append(
':function' + (isGenerator ? '*' : ''),
state
);
path.unshift(node);
traverse(node.value, path, state);
path.shift();
return false;
}
visitObjectConciseMethod.test = function(node, path, state) {
return node.type === Syntax.Property &&
node.value.type === Syntax.FunctionExpression &&
node.method === true;
};
exports.visitorList = [
visitObjectConciseMethod
];
},{"../src/utils":23,"./reserved-words-helper":34,"esprima-fb":9}],29:[function(_dereq_,module,exports){
/**
* Copyright 2013 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.
*/
/*jslint node: true*/
/**
* Desugars ES6 Object Literal short notations into ES3 full notation.
*
* // Easier return values.
* function foo(x, y) {
* return {x, y}; // {x: x, y: y}
* };
*
* // Destructuring.
* function init({port, ip, coords: {x, y}}) { ... }
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
/**
* @public
*/
function visitObjectLiteralShortNotation(traverse, node, path, state) {
utils.catchup(node.key.range[1], state);
utils.append(':' + node.key.name, state);
return false;
}
visitObjectLiteralShortNotation.test = function(node, path, state) {
return node.type === Syntax.Property &&
node.kind === 'init' &&
node.shorthand === true &&
path[0].type !== Syntax.ObjectPattern;
};
exports.visitorList = [
visitObjectLiteralShortNotation
];
},{"../src/utils":23,"esprima-fb":9}],30:[function(_dereq_,module,exports){
/**
* Copyright 2013 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.
*/
/*jslint node:true*/
/**
* Desugars ES6 rest parameters into an ES3 arguments array.
*
* function printf(template, ...args) {
* args.forEach(...);
* }
*
* We could use `Array.prototype.slice.call`, but that usage of arguments causes
* functions to be deoptimized in V8, so instead we use a for-loop.
*
* function printf(template) {
* for (var args = [], $__0 = 1, $__1 = arguments.length; $__0 < $__1; $__0++)
* args.push(arguments[$__0]);
* args.forEach(...);
* }
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
function _nodeIsFunctionWithRestParam(node) {
return (node.type === Syntax.FunctionDeclaration
|| node.type === Syntax.FunctionExpression
|| node.type === Syntax.ArrowFunctionExpression)
&& node.rest;
}
function visitFunctionParamsWithRestParam(traverse, node, path, state) {
if (node.parametricType) {
utils.catchup(node.parametricType.range[0], state);
path.unshift(node);
traverse(node.parametricType, path, state);
path.shift();
}
// Render params.
if (node.params.length) {
path.unshift(node);
traverse(node.params, path, state);
path.shift();
} else {
// -3 is for ... of the rest.
utils.catchup(node.rest.range[0] - 3, state);
}
utils.catchupWhiteSpace(node.rest.range[1], state);
path.unshift(node);
traverse(node.body, path, state);
path.shift();
return false;
}
visitFunctionParamsWithRestParam.test = function(node, path, state) {
return _nodeIsFunctionWithRestParam(node);
};
function renderRestParamSetup(functionNode, state) {
var idx = state.localScope.tempVarIndex++;
var len = state.localScope.tempVarIndex++;
return 'for (var ' + functionNode.rest.name + '=[],' +
utils.getTempVar(idx) + '=' + functionNode.params.length + ',' +
utils.getTempVar(len) + '=arguments.length;' +
utils.getTempVar(idx) + '<' + utils.getTempVar(len) + ';' +
utils.getTempVar(idx) + '++) ' +
functionNode.rest.name + '.push(arguments[' + utils.getTempVar(idx) + ']);';
}
function visitFunctionBodyWithRestParam(traverse, node, path, state) {
utils.catchup(node.range[0] + 1, state);
var parentNode = path[0];
utils.append(renderRestParamSetup(parentNode, state), state);
return true;
}
visitFunctionBodyWithRestParam.test = function(node, path, state) {
return node.type === Syntax.BlockStatement
&& _nodeIsFunctionWithRestParam(path[0]);
};
exports.renderRestParamSetup = renderRestParamSetup;
exports.visitorList = [
visitFunctionParamsWithRestParam,
visitFunctionBodyWithRestParam
];
},{"../src/utils":23,"esprima-fb":9}],31:[function(_dereq_,module,exports){
/**
* Copyright 2013 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.
*/
/*jslint node:true*/
/**
* @typechecks
*/
'use strict';
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
/**
* http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.1.9
*/
function visitTemplateLiteral(traverse, node, path, state) {
var templateElements = node.quasis;
utils.append('(', state);
for (var ii = 0; ii < templateElements.length; ii++) {
var templateElement = templateElements[ii];
if (templateElement.value.raw !== '') {
utils.append(getCookedValue(templateElement), state);
if (!templateElement.tail) {
// + between element and substitution
utils.append(' + ', state);
}
// maintain line numbers
utils.move(templateElement.range[0], state);
utils.catchupNewlines(templateElement.range[1], state);
} else { // templateElement.value.raw === ''
// Concatenat adjacent substitutions, e.g. `${x}${y}`. Empty templates
// appear before the first and after the last element - nothing to add in
// those cases.
if (ii > 0 && !templateElement.tail) {
// + between substitution and substitution
utils.append(' + ', state);
}
}
utils.move(templateElement.range[1], state);
if (!templateElement.tail) {
var substitution = node.expressions[ii];
if (substitution.type === Syntax.Identifier ||
substitution.type === Syntax.MemberExpression ||
substitution.type === Syntax.CallExpression) {
utils.catchup(substitution.range[1], state);
} else {
utils.append('(', state);
traverse(substitution, path, state);
utils.catchup(substitution.range[1], state);
utils.append(')', state);
}
// if next templateElement isn't empty...
if (templateElements[ii + 1].value.cooked !== '') {
utils.append(' + ', state);
}
}
}
utils.move(node.range[1], state);
utils.append(')', state);
return false;
}
visitTemplateLiteral.test = function(node, path, state) {
return node.type === Syntax.TemplateLiteral;
};
/**
* http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.2.6
*/
function visitTaggedTemplateExpression(traverse, node, path, state) {
var template = node.quasi;
var numQuasis = template.quasis.length;
// print the tag
utils.move(node.tag.range[0], state);
traverse(node.tag, path, state);
utils.catchup(node.tag.range[1], state);
// print array of template elements
utils.append('(function() { var siteObj = [', state);
for (var ii = 0; ii < numQuasis; ii++) {
utils.append(getCookedValue(template.quasis[ii]), state);
if (ii !== numQuasis - 1) {
utils.append(', ', state);
}
}
utils.append(']; siteObj.raw = [', state);
for (ii = 0; ii < numQuasis; ii++) {
utils.append(getRawValue(template.quasis[ii]), state);
if (ii !== numQuasis - 1) {
utils.append(', ', state);
}
}
utils.append(
']; Object.freeze(siteObj.raw); Object.freeze(siteObj); return siteObj; }()',
state
);
// print substitutions
if (numQuasis > 1) {
for (ii = 0; ii < template.expressions.length; ii++) {
var expression = template.expressions[ii];
utils.append(', ', state);
// maintain line numbers by calling catchupWhiteSpace over the whole
// previous TemplateElement
utils.move(template.quasis[ii].range[0], state);
utils.catchupNewlines(template.quasis[ii].range[1], state);
utils.move(expression.range[0], state);
traverse(expression, path, state);
utils.catchup(expression.range[1], state);
}
}
// print blank lines to push the closing ) down to account for the final
// TemplateElement.
utils.catchupNewlines(node.range[1], state);
utils.append(')', state);
return false;
}
visitTaggedTemplateExpression.test = function(node, path, state) {
return node.type === Syntax.TaggedTemplateExpression;
};
function getCookedValue(templateElement) {
return JSON.stringify(templateElement.value.cooked);
}
function getRawValue(templateElement) {
return JSON.stringify(templateElement.value.raw);
}
exports.visitorList = [
visitTemplateLiteral,
visitTaggedTemplateExpression
];
},{"../src/utils":23,"esprima-fb":9}],32:[function(_dereq_,module,exports){
/**
* Copyright 2013 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.
*/
/*jslint node:true*/
/**
* Desugars ES7 rest properties into ES5 object iteration.
*/
var Syntax = _dereq_('esprima-fb').Syntax;
// TODO: This is a pretty massive helper, it should only be defined once, in the
// transform's runtime environment. We don't currently have a runtime though.
var restFunction =
'(function(source, exclusion) {' +
'var rest = {};' +
'var hasOwn = Object.prototype.hasOwnProperty;' +
'if (source == null) {' +
'throw new TypeError();' +
'}' +
'for (var key in source) {' +
'if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) {' +
'rest[key] = source[key];' +
'}' +
'}' +
'return rest;' +
'})';
function getPropertyNames(properties) {
var names = [];
for (var i = 0; i < properties.length; i++) {
var property = properties[i];
if (property.type === Syntax.SpreadProperty) {
continue;
}
if (property.type === Syntax.Identifier) {
names.push(property.name);
} else {
names.push(property.key.name);
}
}
return names;
}
function getRestFunctionCall(source, exclusion) {
return restFunction + '(' + source + ',' + exclusion + ')';
}
function getSimpleShallowCopy(accessorExpression) {
// This could be faster with 'Object.assign({}, ' + accessorExpression + ')'
// but to unify code paths and avoid a ES6 dependency we use the same
// helper as for the exclusion case.
return getRestFunctionCall(accessorExpression, '{}');
}
function renderRestExpression(accessorExpression, excludedProperties) {
var excludedNames = getPropertyNames(excludedProperties);
if (!excludedNames.length) {
return getSimpleShallowCopy(accessorExpression);
}
return getRestFunctionCall(
accessorExpression,
'{' + excludedNames.join(':1,') + ':1}'
);
}
exports.renderRestExpression = renderRestExpression;
},{"esprima-fb":9}],33:[function(_dereq_,module,exports){
/**
* Copyright 2004-present Facebook. All Rights Reserved.
*/
/*global exports:true*/
/**
* Implements ES7 object spread property.
* https://gist.github.com/sebmarkbage/aa849c7973cb4452c547
*
* { ...a, x: 1 }
*
* Object.assign({}, a, {x: 1 })
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
function visitObjectLiteralSpread(traverse, node, path, state) {
utils.catchup(node.range[0], state);
utils.append('Object.assign({', state);
// Skip the original {
utils.move(node.range[0] + 1, state);
var previousWasSpread = false;
for (var i = 0; i < node.properties.length; i++) {
var property = node.properties[i];
if (property.type === Syntax.SpreadProperty) {
// Close the previous object or initial object
if (!previousWasSpread) {
utils.append('}', state);
}
if (i === 0) {
// Normally there will be a comma when we catch up, but not before
// the first property.
utils.append(',', state);
}
utils.catchup(property.range[0], state);
// skip ...
utils.move(property.range[0] + 3, state);
traverse(property.argument, path, state);
utils.catchup(property.range[1], state);
previousWasSpread = true;
} else {
utils.catchup(property.range[0], state);
if (previousWasSpread) {
utils.append('{', state);
}
traverse(property, path, state);
utils.catchup(property.range[1], state);
previousWasSpread = false;
}
}
// Strip any non-whitespace between the last item and the end.
// We only catch up on whitespace so that we ignore any trailing commas which
// are stripped out for IE8 support. Unfortunately, this also strips out any
// trailing comments.
utils.catchupWhiteSpace(node.range[1] - 1, state);
// Skip the trailing }
utils.move(node.range[1], state);
if (!previousWasSpread) {
utils.append('}', state);
}
utils.append(')', state);
return false;
}
visitObjectLiteralSpread.test = function(node, path, state) {
if (node.type !== Syntax.ObjectExpression) {
return false;
}
// Tight loop optimization
var hasAtLeastOneSpreadProperty = false;
for (var i = 0; i < node.properties.length; i++) {
var property = node.properties[i];
if (property.type === Syntax.SpreadProperty) {
hasAtLeastOneSpreadProperty = true;
} else if (property.kind !== 'init') {
return false;
}
}
return hasAtLeastOneSpreadProperty;
};
exports.visitorList = [
visitObjectLiteralSpread
];
},{"../src/utils":23,"esprima-fb":9}],34:[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.
*/
var KEYWORDS = [
'break', 'do', 'in', 'typeof', 'case', 'else', 'instanceof', 'var', 'catch',
'export', 'new', 'void', 'class', 'extends', 'return', 'while', 'const',
'finally', 'super', 'with', 'continue', 'for', 'switch', 'yield', 'debugger',
'function', 'this', 'default', 'if', 'throw', 'delete', 'import', 'try'
];
var FUTURE_RESERVED_WORDS = [
'enum', 'await', 'implements', 'package', 'protected', 'static', 'interface',
'private', 'public'
];
var LITERALS = [
'null',
'true',
'false'
];
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-reserved-words
var RESERVED_WORDS = [].concat(
KEYWORDS,
FUTURE_RESERVED_WORDS,
LITERALS
);
var reservedWordsMap = Object.create(null);
RESERVED_WORDS.forEach(function(k) {
reservedWordsMap[k] = true;
});
/**
* This list should not grow as new reserved words are introdued. This list is
* of words that need to be quoted because ES3-ish browsers do not allow their
* use as identifier names.
*/
var ES3_FUTURE_RESERVED_WORDS = [
'enum', 'implements', 'package', 'protected', 'static', 'interface',
'private', 'public'
];
var ES3_RESERVED_WORDS = [].concat(
KEYWORDS,
ES3_FUTURE_RESERVED_WORDS,
LITERALS
);
var es3ReservedWordsMap = Object.create(null);
ES3_RESERVED_WORDS.forEach(function(k) {
es3ReservedWordsMap[k] = true;
});
exports.isReservedWord = function(word) {
return !!reservedWordsMap[word];
};
exports.isES3ReservedWord = function(word) {
return !!es3ReservedWordsMap[word];
};
},{}],35:[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.
*
*/
/*global exports:true*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
var reserverdWordsHelper = _dereq_('./reserved-words-helper');
/**
* Code adapted from https://github.com/spicyj/es3ify
* The MIT License (MIT)
* Copyright (c) 2014 Ben Alpert
*/
function visitProperty(traverse, node, path, state) {
utils.catchup(node.key.range[0], state);
utils.append('"', state);
utils.catchup(node.key.range[1], state);
utils.append('"', state);
utils.catchup(node.value.range[0], state);
traverse(node.value, path, state);
return false;
}
visitProperty.test = function(node) {
return node.type === Syntax.Property &&
node.key.type === Syntax.Identifier &&
!node.method &&
!node.shorthand &&
!node.computed &&
reserverdWordsHelper.isES3ReservedWord(node.key.name);
};
function visitMemberExpression(traverse, node, path, state) {
traverse(node.object, path, state);
utils.catchup(node.property.range[0] - 1, state);
utils.append('[', state);
utils.catchupWhiteSpace(node.property.range[0], state);
utils.append('"', state);
utils.catchup(node.property.range[1], state);
utils.append('"]', state);
return false;
}
visitMemberExpression.test = function(node) {
return node.type === Syntax.MemberExpression &&
node.property.type === Syntax.Identifier &&
reserverdWordsHelper.isES3ReservedWord(node.property.name);
};
exports.visitorList = [
visitProperty,
visitMemberExpression
];
},{"../src/utils":23,"./reserved-words-helper":34,"esprima-fb":9}],36:[function(_dereq_,module,exports){
var esprima = _dereq_('esprima-fb');
var utils = _dereq_('../src/utils');
var Syntax = esprima.Syntax;
function _isFunctionNode(node) {
return node.type === Syntax.FunctionDeclaration
|| node.type === Syntax.FunctionExpression
|| node.type === Syntax.ArrowFunctionExpression;
}
function visitClassProperty(traverse, node, path, state) {
utils.catchup(node.range[0], state);
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitClassProperty.test = function(node, path, state) {
return node.type === Syntax.ClassProperty;
};
function visitTypeAlias(traverse, node, path, state) {
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitTypeAlias.test = function(node, path, state) {
return node.type === Syntax.TypeAlias;
};
function visitTypeCast(traverse, node, path, state) {
path.unshift(node);
traverse(node.expression, path, state);
path.shift();
utils.catchup(node.typeAnnotation.range[0], state);
utils.catchupWhiteOut(node.typeAnnotation.range[1], state);
return false;
}
visitTypeCast.test = function(node, path, state) {
return node.type === Syntax.TypeCastExpression;
};
function visitInterfaceDeclaration(traverse, node, path, state) {
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitInterfaceDeclaration.test = function(node, path, state) {
return node.type === Syntax.InterfaceDeclaration;
};
function visitDeclare(traverse, node, path, state) {
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitDeclare.test = function(node, path, state) {
switch (node.type) {
case Syntax.DeclareVariable:
case Syntax.DeclareFunction:
case Syntax.DeclareClass:
case Syntax.DeclareModule:
return true;
}
return false;
};
function visitFunctionParametricAnnotation(traverse, node, path, state) {
utils.catchup(node.range[0], state);
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitFunctionParametricAnnotation.test = function(node, path, state) {
return node.type === Syntax.TypeParameterDeclaration
&& path[0]
&& _isFunctionNode(path[0])
&& node === path[0].typeParameters;
};
function visitFunctionReturnAnnotation(traverse, node, path, state) {
utils.catchup(node.range[0], state);
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitFunctionReturnAnnotation.test = function(node, path, state) {
return path[0] && _isFunctionNode(path[0]) && node === path[0].returnType;
};
function visitOptionalFunctionParameterAnnotation(traverse, node, path, state) {
utils.catchup(node.range[0] + node.name.length, state);
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitOptionalFunctionParameterAnnotation.test = function(node, path, state) {
return node.type === Syntax.Identifier
&& node.optional
&& path[0]
&& _isFunctionNode(path[0]);
};
function visitTypeAnnotatedIdentifier(traverse, node, path, state) {
utils.catchup(node.typeAnnotation.range[0], state);
utils.catchupWhiteOut(node.typeAnnotation.range[1], state);
return false;
}
visitTypeAnnotatedIdentifier.test = function(node, path, state) {
return node.type === Syntax.Identifier && node.typeAnnotation;
};
function visitTypeAnnotatedObjectOrArrayPattern(traverse, node, path, state) {
utils.catchup(node.typeAnnotation.range[0], state);
utils.catchupWhiteOut(node.typeAnnotation.range[1], state);
return false;
}
visitTypeAnnotatedObjectOrArrayPattern.test = function(node, path, state) {
var rightType = node.type === Syntax.ObjectPattern
|| node.type === Syntax.ArrayPattern;
return rightType && node.typeAnnotation;
};
/**
* Methods cause trouble, since esprima parses them as a key/value pair, where
* the location of the value starts at the method body. For example
* { bar(x:number,...y:Array<number>):number {} }
* is parsed as
* { bar: function(x: number, ...y:Array<number>): number {} }
* except that the location of the FunctionExpression value is 40-something,
* which is the location of the function body. This means that by the time we
* visit the params, rest param, and return type organically, we've already
* catchup()'d passed them.
*/
function visitMethod(traverse, node, path, state) {
path.unshift(node);
traverse(node.key, path, state);
path.unshift(node.value);
traverse(node.value.params, path, state);
node.value.rest && traverse(node.value.rest, path, state);
node.value.returnType && traverse(node.value.returnType, path, state);
traverse(node.value.body, path, state);
path.shift();
path.shift();
return false;
}
visitMethod.test = function(node, path, state) {
return (node.type === "Property" && (node.method || node.kind === "set" || node.kind === "get"))
|| (node.type === "MethodDefinition");
};
function visitImportType(traverse, node, path, state) {
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitImportType.test = function(node, path, state) {
return node.type === 'ImportDeclaration'
&& node.isType;
};
exports.visitorList = [
visitClassProperty,
visitDeclare,
visitImportType,
visitInterfaceDeclaration,
visitFunctionParametricAnnotation,
visitFunctionReturnAnnotation,
visitMethod,
visitOptionalFunctionParameterAnnotation,
visitTypeAlias,
visitTypeCast,
visitTypeAnnotatedIdentifier,
visitTypeAnnotatedObjectOrArrayPattern
];
},{"../src/utils":23,"esprima-fb":9}],37:[function(_dereq_,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/*global exports:true*/
'use strict';
var Syntax = _dereq_('jstransform').Syntax;
var utils = _dereq_('jstransform/src/utils');
function renderJSXLiteral(object, isLast, state, start, end) {
var lines = object.value.split(/\r\n|\n|\r/);
if (start) {
utils.append(start, state);
}
var lastNonEmptyLine = 0;
lines.forEach(function(line, index) {
if (line.match(/[^ \t]/)) {
lastNonEmptyLine = index;
}
});
lines.forEach(function(line, index) {
var isFirstLine = index === 0;
var isLastLine = index === lines.length - 1;
var isLastNonEmptyLine = index === lastNonEmptyLine;
// replace rendered whitespace tabs with spaces
var trimmedLine = line.replace(/\t/g, ' ');
// trim whitespace touching a newline
if (!isFirstLine) {
trimmedLine = trimmedLine.replace(/^[ ]+/, '');
}
if (!isLastLine) {
trimmedLine = trimmedLine.replace(/[ ]+$/, '');
}
if (!isFirstLine) {
utils.append(line.match(/^[ \t]*/)[0], state);
}
if (trimmedLine || isLastNonEmptyLine) {
utils.append(
JSON.stringify(trimmedLine) +
(!isLastNonEmptyLine ? ' + \' \' +' : ''),
state);
if (isLastNonEmptyLine) {
if (end) {
utils.append(end, state);
}
if (!isLast) {
utils.append(', ', state);
}
}
// only restore tail whitespace if line had literals
if (trimmedLine && !isLastLine) {
utils.append(line.match(/[ \t]*$/)[0], state);
}
}
if (!isLastLine) {
utils.append('\n', state);
}
});
utils.move(object.range[1], state);
}
function renderJSXExpressionContainer(traverse, object, isLast, path, state) {
// Plus 1 to skip `{`.
utils.move(object.range[0] + 1, state);
utils.catchup(object.expression.range[0], state);
traverse(object.expression, path, state);
if (!isLast && object.expression.type !== Syntax.JSXEmptyExpression) {
// If we need to append a comma, make sure to do so after the expression.
utils.catchup(object.expression.range[1], state, trimLeft);
utils.append(', ', state);
}
// Minus 1 to skip `}`.
utils.catchup(object.range[1] - 1, state, trimLeft);
utils.move(object.range[1], state);
return false;
}
function quoteAttrName(attr) {
// Quote invalid JS identifiers.
if (!/^[a-z_$][a-z\d_$]*$/i.test(attr)) {
return '"' + attr + '"';
}
return attr;
}
function trimLeft(value) {
return value.replace(/^[ ]+/, '');
}
exports.renderJSXExpressionContainer = renderJSXExpressionContainer;
exports.renderJSXLiteral = renderJSXLiteral;
exports.quoteAttrName = quoteAttrName;
exports.trimLeft = trimLeft;
},{"jstransform":22,"jstransform/src/utils":23}],38:[function(_dereq_,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/*global exports:true*/
'use strict';
var Syntax = _dereq_('jstransform').Syntax;
var utils = _dereq_('jstransform/src/utils');
var renderJSXExpressionContainer =
_dereq_('./jsx').renderJSXExpressionContainer;
var renderJSXLiteral = _dereq_('./jsx').renderJSXLiteral;
var quoteAttrName = _dereq_('./jsx').quoteAttrName;
var trimLeft = _dereq_('./jsx').trimLeft;
/**
* Customized desugar processor for React JSX. Currently:
*
* <X> </X> => React.createElement(X, null)
* <X prop="1" /> => React.createElement(X, {prop: '1'}, null)
* <X prop="2"><Y /></X> => React.createElement(X, {prop:'2'},
* React.createElement(Y, null)
* )
* <div /> => React.createElement("div", null)
*/
/**
* Removes all non-whitespace/parenthesis characters
*/
var reNonWhiteParen = /([^\s\(\)])/g;
function stripNonWhiteParen(value) {
return value.replace(reNonWhiteParen, '');
}
var tagConvention = /^[a-z]|\-/;
function isTagName(name) {
return tagConvention.test(name);
}
function visitReactTag(traverse, object, path, state) {
var openingElement = object.openingElement;
var nameObject = openingElement.name;
var attributesObject = openingElement.attributes;
utils.catchup(openingElement.range[0], state, trimLeft);
if (nameObject.type === Syntax.JSXNamespacedName && nameObject.namespace) {
throw new Error('Namespace tags are not supported. ReactJSX is not XML.');
}
// We assume that the React runtime is already in scope
utils.append('React.createElement(', state);
if (nameObject.type === Syntax.JSXIdentifier && isTagName(nameObject.name)) {
utils.append('"' + nameObject.name + '"', state);
utils.move(nameObject.range[1], state);
} else {
// Use utils.catchup in this case so we can easily handle
// JSXMemberExpressions which look like Foo.Bar.Baz. This also handles
// JSXIdentifiers that aren't fallback tags.
utils.move(nameObject.range[0], state);
utils.catchup(nameObject.range[1], state);
}
utils.append(', ', state);
var hasAttributes = attributesObject.length;
var hasAtLeastOneSpreadProperty = attributesObject.some(function(attr) {
return attr.type === Syntax.JSXSpreadAttribute;
});
// if we don't have any attributes, pass in null
if (hasAtLeastOneSpreadProperty) {
utils.append('React.__spread({', state);
} else if (hasAttributes) {
utils.append('{', state);
} else {
utils.append('null', state);
}
// keep track of if the previous attribute was a spread attribute
var previousWasSpread = false;
// write attributes
attributesObject.forEach(function(attr, index) {
var isLast = index === attributesObject.length - 1;
if (attr.type === Syntax.JSXSpreadAttribute) {
// Close the previous object or initial object
if (!previousWasSpread) {
utils.append('}, ', state);
}
// Move to the expression start, ignoring everything except parenthesis
// and whitespace.
utils.catchup(attr.range[0], state, stripNonWhiteParen);
// Plus 1 to skip `{`.
utils.move(attr.range[0] + 1, state);
utils.catchup(attr.argument.range[0], state, stripNonWhiteParen);
traverse(attr.argument, path, state);
utils.catchup(attr.argument.range[1], state);
// Move to the end, ignoring parenthesis and the closing `}`
utils.catchup(attr.range[1] - 1, state, stripNonWhiteParen);
if (!isLast) {
utils.append(', ', state);
}
utils.move(attr.range[1], state);
previousWasSpread = true;
return;
}
// If the next attribute is a spread, we're effective last in this object
if (!isLast) {
isLast = attributesObject[index + 1].type === Syntax.JSXSpreadAttribute;
}
if (attr.name.namespace) {
throw new Error(
'Namespace attributes are not supported. ReactJSX is not XML.');
}
var name = attr.name.name;
utils.catchup(attr.range[0], state, trimLeft);
if (previousWasSpread) {
utils.append('{', state);
}
utils.append(quoteAttrName(name), state);
utils.append(': ', state);
if (!attr.value) {
state.g.buffer += 'true';
state.g.position = attr.name.range[1];
if (!isLast) {
utils.append(', ', state);
}
} else {
utils.move(attr.name.range[1], state);
// Use catchupNewlines to skip over the '=' in the attribute
utils.catchupNewlines(attr.value.range[0], state);
if (attr.value.type === Syntax.Literal) {
renderJSXLiteral(attr.value, isLast, state);
} else {
renderJSXExpressionContainer(traverse, attr.value, isLast, path, state);
}
}
utils.catchup(attr.range[1], state, trimLeft);
previousWasSpread = false;
});
if (!openingElement.selfClosing) {
utils.catchup(openingElement.range[1] - 1, state, trimLeft);
utils.move(openingElement.range[1], state);
}
if (hasAttributes && !previousWasSpread) {
utils.append('}', state);
}
if (hasAtLeastOneSpreadProperty) {
utils.append(')', state);
}
// filter out whitespace
var childrenToRender = object.children.filter(function(child) {
return !(child.type === Syntax.Literal
&& typeof child.value === 'string'
&& child.value.match(/^[ \t]*[\r\n][ \t\r\n]*$/));
});
if (childrenToRender.length > 0) {
var lastRenderableIndex;
childrenToRender.forEach(function(child, index) {
if (child.type !== Syntax.JSXExpressionContainer ||
child.expression.type !== Syntax.JSXEmptyExpression) {
lastRenderableIndex = index;
}
});
if (lastRenderableIndex !== undefined) {
utils.append(', ', state);
}
childrenToRender.forEach(function(child, index) {
utils.catchup(child.range[0], state, trimLeft);
var isLast = index >= lastRenderableIndex;
if (child.type === Syntax.Literal) {
renderJSXLiteral(child, isLast, state);
} else if (child.type === Syntax.JSXExpressionContainer) {
renderJSXExpressionContainer(traverse, child, isLast, path, state);
} else {
traverse(child, path, state);
if (!isLast) {
utils.append(', ', state);
}
}
utils.catchup(child.range[1], state, trimLeft);
});
}
if (openingElement.selfClosing) {
// everything up to />
utils.catchup(openingElement.range[1] - 2, state, trimLeft);
utils.move(openingElement.range[1], state);
} else {
// everything up to </ sdflksjfd>
utils.catchup(object.closingElement.range[0], state, trimLeft);
utils.move(object.closingElement.range[1], state);
}
utils.append(')', state);
return false;
}
visitReactTag.test = function(object, path, state) {
return object.type === Syntax.JSXElement;
};
exports.visitorList = [
visitReactTag
];
},{"./jsx":37,"jstransform":22,"jstransform/src/utils":23}],39:[function(_dereq_,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/*global exports:true*/
'use strict';
var Syntax = _dereq_('jstransform').Syntax;
var utils = _dereq_('jstransform/src/utils');
function addDisplayName(displayName, object, state) {
if (object &&
object.type === Syntax.CallExpression &&
object.callee.type === Syntax.MemberExpression &&
object.callee.object.type === Syntax.Identifier &&
object.callee.object.name === 'React' &&
object.callee.property.type === Syntax.Identifier &&
object.callee.property.name === 'createClass' &&
object.arguments.length === 1 &&
object.arguments[0].type === Syntax.ObjectExpression) {
// Verify that the displayName property isn't already set
var properties = object.arguments[0].properties;
var safe = properties.every(function(property) {
var value = property.key.type === Syntax.Identifier ?
property.key.name :
property.key.value;
return value !== 'displayName';
});
if (safe) {
utils.catchup(object.arguments[0].range[0] + 1, state);
utils.append('displayName: "' + displayName + '",', state);
}
}
}
/**
* Transforms the following:
*
* var MyComponent = React.createClass({
* render: ...
* });
*
* into:
*
* var MyComponent = React.createClass({
* displayName: 'MyComponent',
* render: ...
* });
*
* Also catches:
*
* MyComponent = React.createClass(...);
* exports.MyComponent = React.createClass(...);
* module.exports = {MyComponent: React.createClass(...)};
*/
function visitReactDisplayName(traverse, object, path, state) {
var left, right;
if (object.type === Syntax.AssignmentExpression) {
left = object.left;
right = object.right;
} else if (object.type === Syntax.Property) {
left = object.key;
right = object.value;
} else if (object.type === Syntax.VariableDeclarator) {
left = object.id;
right = object.init;
}
if (left && left.type === Syntax.MemberExpression) {
left = left.property;
}
if (left && left.type === Syntax.Identifier) {
addDisplayName(left.name, right, state);
}
}
visitReactDisplayName.test = function(object, path, state) {
return (
object.type === Syntax.AssignmentExpression ||
object.type === Syntax.Property ||
object.type === Syntax.VariableDeclarator
);
};
exports.visitorList = [
visitReactDisplayName
];
},{"jstransform":22,"jstransform/src/utils":23}],40:[function(_dereq_,module,exports){
/*global exports:true*/
'use strict';
var es6ArrowFunctions =
_dereq_('jstransform/visitors/es6-arrow-function-visitors');
var es6Classes = _dereq_('jstransform/visitors/es6-class-visitors');
var es6Destructuring =
_dereq_('jstransform/visitors/es6-destructuring-visitors');
var es6ObjectConciseMethod =
_dereq_('jstransform/visitors/es6-object-concise-method-visitors');
var es6ObjectShortNotation =
_dereq_('jstransform/visitors/es6-object-short-notation-visitors');
var es6RestParameters = _dereq_('jstransform/visitors/es6-rest-param-visitors');
var es6Templates = _dereq_('jstransform/visitors/es6-template-visitors');
var es6CallSpread =
_dereq_('jstransform/visitors/es6-call-spread-visitors');
var es7SpreadProperty =
_dereq_('jstransform/visitors/es7-spread-property-visitors');
var react = _dereq_('./transforms/react');
var reactDisplayName = _dereq_('./transforms/reactDisplayName');
var reservedWords = _dereq_('jstransform/visitors/reserved-words-visitors');
/**
* Map from transformName => orderedListOfVisitors.
*/
var transformVisitors = {
'es6-arrow-functions': es6ArrowFunctions.visitorList,
'es6-classes': es6Classes.visitorList,
'es6-destructuring': es6Destructuring.visitorList,
'es6-object-concise-method': es6ObjectConciseMethod.visitorList,
'es6-object-short-notation': es6ObjectShortNotation.visitorList,
'es6-rest-params': es6RestParameters.visitorList,
'es6-templates': es6Templates.visitorList,
'es6-call-spread': es6CallSpread.visitorList,
'es7-spread-property': es7SpreadProperty.visitorList,
'react': react.visitorList.concat(reactDisplayName.visitorList),
'reserved-words': reservedWords.visitorList
};
var transformSets = {
'harmony': [
'es6-arrow-functions',
'es6-object-concise-method',
'es6-object-short-notation',
'es6-classes',
'es6-rest-params',
'es6-templates',
'es6-destructuring',
'es6-call-spread',
'es7-spread-property'
],
'es3': [
'reserved-words'
],
'react': [
'react'
]
};
/**
* Specifies the order in which each transform should run.
*/
var transformRunOrder = [
'reserved-words',
'es6-arrow-functions',
'es6-object-concise-method',
'es6-object-short-notation',
'es6-classes',
'es6-rest-params',
'es6-templates',
'es6-destructuring',
'es6-call-spread',
'es7-spread-property',
'react'
];
/**
* Given a list of transform names, return the ordered list of visitors to be
* passed to the transform() function.
*
* @param {array?} excludes
* @return {array}
*/
function getAllVisitors(excludes) {
var ret = [];
for (var i = 0, il = transformRunOrder.length; i < il; i++) {
if (!excludes || excludes.indexOf(transformRunOrder[i]) === -1) {
ret = ret.concat(transformVisitors[transformRunOrder[i]]);
}
}
return ret;
}
/**
* Given a list of visitor set names, return the ordered list of visitors to be
* passed to jstransform.
*
* @param {array}
* @return {array}
*/
function getVisitorsBySet(sets) {
var visitorsToInclude = sets.reduce(function(visitors, set) {
if (!transformSets.hasOwnProperty(set)) {
throw new Error('Unknown visitor set: ' + set);
}
transformSets[set].forEach(function(visitor) {
visitors[visitor] = true;
});
return visitors;
}, {});
var visitorList = [];
for (var i = 0; i < transformRunOrder.length; i++) {
if (visitorsToInclude.hasOwnProperty(transformRunOrder[i])) {
visitorList = visitorList.concat(transformVisitors[transformRunOrder[i]]);
}
}
return visitorList;
}
exports.getVisitorsBySet = getVisitorsBySet;
exports.getAllVisitors = getAllVisitors;
exports.transformVisitors = transformVisitors;
},{"./transforms/react":38,"./transforms/reactDisplayName":39,"jstransform/visitors/es6-arrow-function-visitors":24,"jstransform/visitors/es6-call-spread-visitors":25,"jstransform/visitors/es6-class-visitors":26,"jstransform/visitors/es6-destructuring-visitors":27,"jstransform/visitors/es6-object-concise-method-visitors":28,"jstransform/visitors/es6-object-short-notation-visitors":29,"jstransform/visitors/es6-rest-param-visitors":30,"jstransform/visitors/es6-template-visitors":31,"jstransform/visitors/es7-spread-property-visitors":33,"jstransform/visitors/reserved-words-visitors":35}],41:[function(_dereq_,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
/*eslint-disable no-undef*/
var Buffer = _dereq_('buffer').Buffer;
function inlineSourceMap(sourceMap, sourceCode, sourceFilename) {
// This can be used with a sourcemap that has already has toJSON called on it.
// Check first.
var json = sourceMap;
if (typeof sourceMap.toJSON === 'function') {
json = sourceMap.toJSON();
}
json.sources = [sourceFilename];
json.sourcesContent = [sourceCode];
var base64 = Buffer(JSON.stringify(json)).toString('base64');
return '//# sourceMappingURL=data:application/json;base64,' + base64;
}
module.exports = inlineSourceMap;
},{"buffer":3}]},{},[1])(1)
}); |
src/index.js | elarssen/reflux-bootstrap-alerts | import React from 'react';
import AlertMessage from './Message';
React.render(<AlertMessage ticks={10}></AlertMessage>, document.body);
|
django/webcode/webcode/frontend/node_modules/react-bootstrap/es/DropdownMenu.js | OpenKGB/webcode | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _Array$from from 'babel-runtime/core-js/array/from';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import keycode from 'keycode';
import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import RootCloseWrapper from 'react-overlays/lib/RootCloseWrapper';
import { bsClass, getClassSet, prefix, splitBsPropsAndOmit } from './utils/bootstrapUtils';
import createChainedFunction from './utils/createChainedFunction';
import ValidComponentChildren from './utils/ValidComponentChildren';
var propTypes = {
open: PropTypes.bool,
pullRight: PropTypes.bool,
onClose: PropTypes.func,
labelledBy: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
onSelect: PropTypes.func,
rootCloseEvent: PropTypes.oneOf(['click', 'mousedown'])
};
var defaultProps = {
bsRole: 'menu',
pullRight: false
};
var DropdownMenu = function (_React$Component) {
_inherits(DropdownMenu, _React$Component);
function DropdownMenu(props) {
_classCallCheck(this, DropdownMenu);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
_this.handleRootClose = _this.handleRootClose.bind(_this);
_this.handleKeyDown = _this.handleKeyDown.bind(_this);
return _this;
}
DropdownMenu.prototype.handleRootClose = function handleRootClose(event) {
this.props.onClose(event, { source: 'rootClose' });
};
DropdownMenu.prototype.handleKeyDown = function handleKeyDown(event) {
switch (event.keyCode) {
case keycode.codes.down:
this.focusNext();
event.preventDefault();
break;
case keycode.codes.up:
this.focusPrevious();
event.preventDefault();
break;
case keycode.codes.esc:
case keycode.codes.tab:
this.props.onClose(event, { source: 'keydown' });
break;
default:
}
};
DropdownMenu.prototype.getItemsAndActiveIndex = function getItemsAndActiveIndex() {
var items = this.getFocusableMenuItems();
var activeIndex = items.indexOf(document.activeElement);
return { items: items, activeIndex: activeIndex };
};
DropdownMenu.prototype.getFocusableMenuItems = function getFocusableMenuItems() {
var node = ReactDOM.findDOMNode(this);
if (!node) {
return [];
}
return _Array$from(node.querySelectorAll('[tabIndex="-1"]'));
};
DropdownMenu.prototype.focusNext = function focusNext() {
var _getItemsAndActiveInd = this.getItemsAndActiveIndex(),
items = _getItemsAndActiveInd.items,
activeIndex = _getItemsAndActiveInd.activeIndex;
if (items.length === 0) {
return;
}
var nextIndex = activeIndex === items.length - 1 ? 0 : activeIndex + 1;
items[nextIndex].focus();
};
DropdownMenu.prototype.focusPrevious = function focusPrevious() {
var _getItemsAndActiveInd2 = this.getItemsAndActiveIndex(),
items = _getItemsAndActiveInd2.items,
activeIndex = _getItemsAndActiveInd2.activeIndex;
if (items.length === 0) {
return;
}
var prevIndex = activeIndex === 0 ? items.length - 1 : activeIndex - 1;
items[prevIndex].focus();
};
DropdownMenu.prototype.render = function render() {
var _extends2,
_this2 = this;
var _props = this.props,
open = _props.open,
pullRight = _props.pullRight,
labelledBy = _props.labelledBy,
onSelect = _props.onSelect,
className = _props.className,
rootCloseEvent = _props.rootCloseEvent,
children = _props.children,
props = _objectWithoutProperties(_props, ['open', 'pullRight', 'labelledBy', 'onSelect', 'className', 'rootCloseEvent', 'children']);
var _splitBsPropsAndOmit = splitBsPropsAndOmit(props, ['onClose']),
bsProps = _splitBsPropsAndOmit[0],
elementProps = _splitBsPropsAndOmit[1];
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, 'right')] = pullRight, _extends2));
return React.createElement(
RootCloseWrapper,
{
disabled: !open,
onRootClose: this.handleRootClose,
event: rootCloseEvent
},
React.createElement(
'ul',
_extends({}, elementProps, {
role: 'menu',
className: classNames(className, classes),
'aria-labelledby': labelledBy
}),
ValidComponentChildren.map(children, function (child) {
return React.cloneElement(child, {
onKeyDown: createChainedFunction(child.props.onKeyDown, _this2.handleKeyDown),
onSelect: createChainedFunction(child.props.onSelect, onSelect)
});
})
)
);
};
return DropdownMenu;
}(React.Component);
DropdownMenu.propTypes = propTypes;
DropdownMenu.defaultProps = defaultProps;
export default bsClass('dropdown-menu', DropdownMenu); |
src/svg-icons/editor/vertical-align-center.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorVerticalAlignCenter = (props) => (
<SvgIcon {...props}>
<path d="M8 19h3v4h2v-4h3l-4-4-4 4zm8-14h-3V1h-2v4H8l4 4 4-4zM4 11v2h16v-2H4z"/>
</SvgIcon>
);
EditorVerticalAlignCenter = pure(EditorVerticalAlignCenter);
EditorVerticalAlignCenter.displayName = 'EditorVerticalAlignCenter';
EditorVerticalAlignCenter.muiName = 'SvgIcon';
export default EditorVerticalAlignCenter;
|
client/src/components/Discussion.js | codefordenver/Circular | import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Well } from 'react-bootstrap';
import { fetchComments, postComment } from '../redux/actions/comments';
import Comment from './Comment';
import PostBox from './PostBox';
class Discussion extends Component {
constructor(props) {
super(props);
this.state = { error: false };
this.comments = this.props.comments;
}
componentDidMount() {
this.props.fetchComments(this.props.campaignID);
}
shouldComponentUpdate(nextProps, nextState) {
return (
nextProps.comments.commentsLoaded === true || nextProps.comments.fetchError !== undefined
);
}
componentWillUpdate(nextProps, nextState) {
if (this.props.campaignID !== nextProps.campaignID) {
nextProps.fetchComments(nextProps.campaignID);
}
}
renderMainPostBox() {
if (this.props.auth && this.props.auth._id) {
return (
<PostBox
className="main-post-box"
campaignID={this.props.campaignID}
fetchComments={this.props.fetchComments}
isAReply={false}
/>
);
}
return <Well className="login-post-box">Log in to join the discussion!</Well>;
}
renderComments() {
const comments = this.props.comments;
if (comments.commentsLoaded === true) {
return (
<div>
{Object.keys(comments.campaignComments).map(u => (
<div key={comments.campaignComments[u]._id}>
<Comment
userName={comments.campaignComments[u].userName}
message={comments.campaignComments[u].message}
dateAdded={comments.campaignComments[u].createdAt}
passedChildren={comments.campaignComments[u].children}
campaignID={this.props.campaignID}
commentID={comments.campaignComments[u]._id}
authorized={this.props.auth !== undefined && this.props.auth._id !== undefined}
/>
</div>
))}
</div>
);
}
return <div />;
}
render() {
return (
<div className="discussion">
<div className="discussion-header">COMMENTS</div>
<div className="comment-box">{this.renderComments()}</div>
<div>{this.renderMainPostBox()}</div>
</div>
);
}
}
Discussion.defaultProps = {
signatureObj: { signatures: [] },
auth: {}
};
Discussion.propTypes = {
auth: PropTypes.shape({
_id: PropTypes.string,
googleID: PropTypes.string
}),
comments: PropTypes.shape({
campaignComments: PropTypes.Object,
commentsLoaded: PropTypes.bool,
fetchError: PropTypes.Object
}).isRequired,
campaignID: PropTypes.string.isRequired,
fetchComments: PropTypes.func.isRequired
};
export default connect(
({ activeCampaign, auth, comments }) => ({ activeCampaign, auth, comments }),
{
fetchComments,
postComment
}
)(Discussion);
|
packages/material-ui-icons/src/DepartureBoard.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M16 1c-2.4 0-4.52 1.21-5.78 3.05.01-.01.01-.02.02-.03C9.84 4 9.42 4 9 4c-4.42 0-8 .5-8 4v10c0 .88.39 1.67 1 2.22V22c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h8v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1.78c.61-.55 1-1.34 1-2.22v-3.08c3.39-.49 6-3.39 6-6.92 0-3.87-3.13-7-7-7zM4.5 19c-.83 0-1.5-.67-1.5-1.5S3.67 16 4.5 16s1.5.67 1.5 1.5S5.33 19 4.5 19zM3 13V8h6c0 1.96.81 3.73 2.11 5H3zm10.5 6c-.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.5zm2.5-6c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm.5-9H15v5l3.62 2.16.75-1.23-2.87-1.68z" />
, 'DepartureBoard');
|
docs/src/app/components/pages/components/FontIcon/ExampleIcons.js | kasra-co/material-ui | import React from 'react';
import FontIcon from 'material-ui/FontIcon';
import {red500, yellow500, blue500} from 'material-ui/styles/colors';
const iconStyles = {
marginRight: 24,
};
const FontIconExampleIcons = () => (
<div>
<FontIcon className="material-icons" style={iconStyles}>home</FontIcon>
<FontIcon className="material-icons" style={iconStyles} color={red500}>flight_takeoff</FontIcon>
<FontIcon className="material-icons" style={iconStyles} color={yellow500}>cloud_download</FontIcon>
<FontIcon className="material-icons" style={iconStyles} color={blue500}>videogame_asset</FontIcon>
</div>
);
export default FontIconExampleIcons;
|
node_modules/react-icons/ti/social-tumbler-circular.js | bairrada97/festival |
import React from 'react'
import Icon from 'react-icon-base'
const TiSocialTumblerCircular = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m24 26v-2.1c-0.7 0.5-1.4 0.7-2 0.7-0.3 0-0.6-0.1-1-0.3-0.2-0.1-0.3-0.3-0.4-0.5-0.1-0.2-0.1-0.7-0.1-1.4v-3.3h3v-2.1h-3v-3.2h-1.8c-0.2 0.7-0.3 1.3-0.5 1.6-0.1 0.4-0.4 0.8-0.9 1.1-0.4 0.4-0.8 0.6-1.2 0.8v1.8h1.4v4.5c0 0.5 0 1 0.2 1.3 0.1 0.3 0.3 0.6 0.7 0.9 0.2 0.3 0.6 0.5 1.1 0.7 0.6 0.1 1.1 0.2 1.5 0.2 0.5 0 1-0.1 1.5-0.2 0.5-0.1 1-0.3 1.5-0.5z m-4 9c-8.3 0-15-6.7-15-15s6.7-15 15-15 15 6.7 15 15-6.7 15-15 15z m0-26.7c-6.4 0-11.7 5.3-11.7 11.7s5.3 11.7 11.7 11.7 11.7-5.3 11.7-11.7-5.3-11.7-11.7-11.7z"/></g>
</Icon>
)
export default TiSocialTumblerCircular
|
ajax/libs/react-contextmenu/2.6.5/react-contextmenu.js | jdh8/cdnjs | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports.ReactContextMenu=t(require("react")):e.ReactContextMenu=t(e.React)}(this,function(e){return function(e){function t(o){if(n[o])return n[o].exports;var r=n[o]={i:o,l:!1,exports:{}};return e[o].call(r.exports,r,r.exports,t),r.l=!0,r.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,o){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:o})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=11)}([function(t,n){t.exports=e},function(e,t,n){"use strict";function o(e){for(var t=arguments.length,n=Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return"function"==typeof e&&e.apply(void 0,n)}function r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function i(){return Math.random().toString(36).substring(7)}t.a=o,t.d=r,t.f=i,n.d(t,"c",function(){return u}),n.d(t,"e",function(){return a}),n.d(t,"b",function(){return s});var u={menu:"react-contextmenu",menuVisible:"react-contextmenu--visible",menuWrapper:"react-contextmenu-wrapper",menuItem:"react-contextmenu-item",menuItemActive:"react-contextmenu-item--active",menuItemDisabled:"react-contextmenu-item--disabled",menuItemDivider:"react-contextmenu-item--divider",menuItemSelected:"react-contextmenu-item--selected",subMenu:"react-contextmenu-submenu"},a={},s=Boolean("undefined"!=typeof window&&window.document&&window.document.createElement)},function(e,t,n){e.exports=n(13)()},function(e,t,n){"use strict";function o(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:window,o=void 0;"function"==typeof window.CustomEvent?o=new window.CustomEvent(e,{detail:t}):(o=document.createEvent("CustomEvent"),o.initCustomEvent(e,!1,!0,t)),n&&(n.dispatchEvent(o),a()(s.e,t))}function r(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1];o(c,a()({},e,{type:c}),t)}function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1];o(l,a()({},e,{type:l}),t)}n.d(t,"b",function(){return c}),n.d(t,"a",function(){return l}),t.d=r,t.c=i;var u=n(5),a=n.n(u),s=n(1),c="REACT_CONTEXTMENU_SHOW",l="REACT_CONTEXTMENU_HIDE"},function(e,t,n){var o,r;/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
!function(){"use strict";function n(){for(var e=[],t=0;t<arguments.length;t++){var o=arguments[t];if(o){var r=typeof o;if("string"===r||"number"===r)e.push(o);else if(Array.isArray(o))e.push(n.apply(null,o));else if("object"===r)for(var u in o)i.call(o,u)&&o[u]&&e.push(u)}}return e.join(" ")}var i={}.hasOwnProperty;void 0!==e&&e.exports?e.exports=n:(o=[],void 0!==(r=function(){return n}.apply(t,o))&&(e.exports=r))}()},function(e,t,n){"use strict";function o(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
var r=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,u=Object.prototype.propertyIsEnumerable;e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var o={};return"abcdefghijklmnopqrst".split("").forEach(function(e){o[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},o)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var n,a,s=o(e),c=1;c<arguments.length;c++){n=Object(arguments[c]);for(var l in n)i.call(n,l)&&(s[l]=n[l]);if(r){a=r(n);for(var f=0;f<a.length;f++)u.call(n,a[f])&&(s[a[f]]=n[a[f]])}}return s}},function(e,t,n){"use strict";function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var r=n(3),i=n(1),u=function e(){var t=this;o(this,e),this.handleShowEvent=function(e){for(var n in t.callbacks)Object(i.d)(t.callbacks,n)&&t.callbacks[n].show(e)},this.handleHideEvent=function(e){for(var n in t.callbacks)Object(i.d)(t.callbacks,n)&&t.callbacks[n].hide(e)},this.register=function(e,n){var o=Object(i.f)();return t.callbacks[o]={show:e,hide:n},o},this.unregister=function(e){e&&t.callbacks[e]&&delete t.callbacks[e]},this.callbacks={},i.b&&(window.addEventListener(r.b,this.handleShowEvent),window.addEventListener(r.a,this.handleHideEvent))};t.a=new u},function(e,t,n){"use strict";function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var u=n(0),a=n.n(u),s=n(2),c=n.n(s),l=n(8),f=function(e){function t(e){o(this,t);var n=r(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return d.call(n),n.seletedItemRef=null,n.state={selectedItem:null,forceSubMenuOpen:!1},n}return i(t,e),t}(u.Component);f.propTypes={children:c.a.node.isRequired};var d=function(){var e=this;this.handleKeyNavigation=function(t){if(e.state.isVisible)switch(t.keyCode){case 37:case 27:t.preventDefault(),e.hideMenu(t);break;case 38:t.preventDefault(),e.selectChildren(!0);break;case 40:t.preventDefault(),e.selectChildren(!1);break;case 39:e.tryToOpenSubMenu(t);break;case 13:t.preventDefault(),e.tryToOpenSubMenu(t),e.seletedItemRef&&e.seletedItemRef.ref instanceof HTMLElement&&e.seletedItemRef.ref.click()}},this.handleForceClose=function(){e.setState({forceSubMenuOpen:!1})},this.tryToOpenSubMenu=function(t){e.state.selectedItem&&e.state.selectedItem.type===e.getSubMenuType()&&(t.preventDefault(),e.setState({forceSubMenuOpen:!0}))},this.selectChildren=function(t){var n=e.state.selectedItem,o=[],r=function t(n){n&&([l.a,e.getSubMenuType()].indexOf(n.type)<0?a.a.Children.forEach(n.props.children,t):n.props.divider||o.push(n))};a.a.Children.forEach(e.props.children,r);var i=o.indexOf(n);i<0?e.setState({selectedItem:t?o[o.length-1]:o[0],forceSubMenuOpen:!1}):t?e.setState({selectedItem:o[i-1<0?o.length-1:i-1],forceSubMenuOpen:!1}):e.setState({selectedItem:o[i+1<o.length?i+1:0],forceSubMenuOpen:!1})},this.onChildMouseMove=function(t){e.state.selectedItem!==t&&e.setState({selectedItem:t,forceSubMenuOpen:!1})},this.onChildMouseLeave=function(){e.setState({selectedItem:null,forceSubMenuOpen:!1})},this.renderChildren=function(t){return a.a.Children.map(t,function(t){var n={};return a.a.isValidElement(t)?[l.a,e.getSubMenuType()].indexOf(t.type)<0?(n.children=e.renderChildren(t.props.children),a.a.cloneElement(t,n)):(n.onMouseLeave=e.onChildMouseLeave.bind(e),t.type===e.getSubMenuType()&&(n.forceOpen=e.state.forceSubMenuOpen&&e.state.selectedItem===t,n.forceClose=e.handleForceClose,n.parentKeyNavigationHandler=e.handleKeyNavigation),t.props.divider||e.state.selectedItem!==t?(n.onMouseMove=function(){return e.onChildMouseMove(t)},a.a.cloneElement(t,n)):(n.selected=!0,n.ref=function(t){e.seletedItemRef=t},a.a.cloneElement(t,n))):t})}};t.a=f},function(e,t,n){"use strict";function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(0),s=n.n(a),c=n(2),l=n.n(c),f=n(4),d=n.n(f),p=n(5),h=n.n(p),b=n(3),m=n(1),v=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},y=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),O=function(e){function t(){var e,n,o,u;r(this,t);for(var a=arguments.length,s=Array(a),c=0;c<a;c++)s[c]=arguments[c];return n=o=i(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),o.handleClick=function(e){e.preventDefault(),o.props.disabled||o.props.divider||(Object(m.a)(o.props.onClick,e,h()({},o.props.data,m.e.data),m.e.target),o.props.preventClose||Object(b.c)())},u=n,i(o,u)}return u(t,e),y(t,[{key:"render",value:function(){var e,t=this,n=this.props,r=n.disabled,i=n.divider,u=n.children,a=n.attributes,c=n.selected,l=d()(m.c.menuItem,a&&a.className,(e={},o(e,m.c.menuItemDisabled,r),o(e,m.c.menuItemDivider,i),o(e,m.c.menuItemSelected,c),e));return s.a.createElement("div",v({},a,{className:l,role:"menuitem",tabIndex:"-1","aria-disabled":r?"true":"false","aria-orientation":i?"horizontal":null,ref:function(e){t.ref=e},onMouseMove:this.props.onMouseMove,onMouseLeave:this.props.onMouseLeave,onTouchEnd:this.handleClick,onClick:this.handleClick}),i?null:u)}}]),t}(a.Component);O.propTypes={children:l.a.node,attributes:l.a.object,data:l.a.object,disabled:l.a.bool,divider:l.a.bool,preventClose:l.a.bool,onClick:l.a.func,selected:l.a.bool,onMouseMove:l.a.func,onMouseLeave:l.a.func},O.defaultProps={disabled:!1,data:{},divider:!1,attributes:{},preventClose:!1,onClick:function(){return null},children:null,selected:!1,onMouseMove:function(){return null},onMouseLeave:function(){return null}},t.a=O},function(e,t,n){"use strict";function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(0),s=n.n(a),c=n(2),l=n.n(c),f=n(4),d=n.n(f),p=n(7),h=n(1),b=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},m=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),v=function(e){function t(e){r(this,t);var n=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.getMenuPosition=function(){var e=window,t=e.innerWidth,o=e.innerHeight,r=n.subMenu.getBoundingClientRect(),i={};return r.bottom>o?i.bottom=0:i.top=0,r.right<t?i.left="100%":i.right="100%",i},n.getRTLMenuPosition=function(){var e=window,t=e.innerHeight,o=n.subMenu.getBoundingClientRect(),r={};return o.bottom>t?r.bottom=0:r.top=0,o.left<0?r.left="100%":r.right="100%",r},n.hideMenu=function(){n.props.forceOpen&&n.props.forceClose(),n.setState({visible:!1,selectedItem:null})},n.handleClick=function(e){e.preventDefault()},n.handleMouseEnter=function(){n.closetimer&&clearTimeout(n.closetimer),n.props.disabled||n.state.visible||(n.opentimer=setTimeout(function(){return n.setState({visible:!0,selectedItem:null})},n.props.hoverDelay))},n.handleMouseLeave=function(){n.opentimer&&clearTimeout(n.opentimer),n.state.visible&&(n.closetimer=setTimeout(function(){return n.setState({visible:!1,selectedItem:null})},n.props.hoverDelay))},n.menuRef=function(e){n.menu=e},n.subMenuRef=function(e){n.subMenu=e},n.registerHandlers=function(){document.removeEventListener("keydown",n.props.parentKeyNavigationHandler),document.addEventListener("keydown",n.handleKeyNavigation)},n.unregisterHandlers=function(){document.removeEventListener("keydown",n.handleKeyNavigation),document.addEventListener("keydown",n.props.parentKeyNavigationHandler)},n.state=Object.assign({},n.state,{visible:!1}),n}return u(t,e),m(t,[{key:"getSubMenuType",value:function(){return t}},{key:"shouldComponentUpdate",value:function(e,t){return this.isVisibilityChange=!(this.state.visible===t.visible&&this.props.forceOpen===e.forceOpen||this.state.visible&&e.forceOpen||this.props.forceOpen&&t.visible),!0}},{key:"componentDidUpdate",value:function(){var e=this;if(this.isVisibilityChange)if(this.props.forceOpen||this.state.visible){var t=window.requestAnimationFrame||setTimeout;t(function(){var t=e.props.rtl?e.getRTLMenuPosition():e.getMenuPosition();e.subMenu.style.removeProperty("top"),e.subMenu.style.removeProperty("bottom"),e.subMenu.style.removeProperty("left"),e.subMenu.style.removeProperty("right"),Object(h.d)(t,"top")&&(e.subMenu.style.top=t.top),Object(h.d)(t,"left")&&(e.subMenu.style.left=t.left),Object(h.d)(t,"bottom")&&(e.subMenu.style.bottom=t.bottom),Object(h.d)(t,"right")&&(e.subMenu.style.right=t.right),e.subMenu.classList.add(h.c.menuVisible),e.registerHandlers(),e.setState({selectedItem:null})})}else{var n=function t(){e.subMenu.removeEventListener("transitionend",t),e.subMenu.style.removeProperty("bottom"),e.subMenu.style.removeProperty("right"),e.subMenu.style.top=0,e.subMenu.style.left="100%",e.unregisterHandlers()};this.subMenu.addEventListener("transitionend",n),this.subMenu.classList.remove(h.c.menuVisible)}}},{key:"componentWillUnmount",value:function(){this.opentimer&&clearTimeout(this.opentimer),this.closetimer&&clearTimeout(this.closetimer),this.unregisterHandlers()}},{key:"render",value:function(){var e,t=this.props,n=t.children,r=t.disabled,i=t.title,u=t.selected,a=this.state.visible,c={ref:this.menuRef,onMouseEnter:this.handleMouseEnter,onMouseLeave:this.handleMouseLeave,className:d()(h.c.menuItem,h.c.subMenu),style:{position:"relative"}},l={className:d()(h.c.menuItem,(e={},o(e,h.c.menuItemDisabled,r),o(e,h.c.menuItemActive,a),o(e,h.c.menuItemSelected,u),e)),onMouseMove:this.props.onMouseMove,onMouseOut:this.props.onMouseOut,onClick:this.handleClick},f={ref:this.subMenuRef,style:{position:"absolute",transition:"opacity 1ms",top:0,left:"100%"},className:d()(h.c.menu,this.props.className)};return s.a.createElement("nav",b({},c,{role:"menuitem",tabIndex:"-1","aria-haspopup":"true"}),s.a.createElement("div",l,i),s.a.createElement("nav",b({},f,{role:"menu",tabIndex:"-1"}),this.renderChildren(n)))}}]),t}(p.a);v.propTypes={children:l.a.node.isRequired,title:l.a.node.isRequired,className:l.a.string,disabled:l.a.bool,hoverDelay:l.a.number,rtl:l.a.bool,selected:l.a.bool,onMouseMove:l.a.func,onMouseOut:l.a.func,forceOpen:l.a.bool,forceClose:l.a.func,parentKeyNavigationHandler:l.a.func},v.defaultProps={disabled:!1,hoverDelay:500,className:"",rtl:!1,selected:!1,onMouseMove:function(){return null},onMouseOut:function(){return null},forceOpen:!1,forceClose:function(){return null},parentKeyNavigationHandler:function(){return null}},t.a=v},function(e,t,n){"use strict";function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var u=n(0),a=n.n(u),s=n(2),c=n.n(s),l=n(4),f=n.n(l),d=n(5),p=n.n(d),h=n(3),b=n(1),m=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),v=function(e){function t(){var e,n,i,u;o(this,t);for(var a=arguments.length,s=Array(a),c=0;c<a;c++)s[c]=arguments[c];return n=i=r(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),i.touchHandled=!1,i.handleMouseDown=function(e){i.props.holdToDisplay>=0&&0===e.button&&(e.persist(),i.mouseDownTimeoutId=setTimeout(function(){return i.handleContextClick(e)},i.props.holdToDisplay)),Object(b.a)(i.props.attributes.onMouseDown,e)},i.handleMouseUp=function(e){0===e.button&&clearTimeout(i.mouseDownTimeoutId),Object(b.a)(i.props.attributes.onMouseUp,e)},i.handleMouseOut=function(e){0===e.button&&clearTimeout(i.mouseDownTimeoutId),Object(b.a)(i.props.attributes.onMouseOut,e)},i.handleTouchstart=function(e){i.touchHandled=!1,i.props.holdToDisplay>=0&&(e.persist(),i.touchstartTimeoutId=setTimeout(function(){i.handleContextClick(e),i.touchHandled=!0},i.props.holdToDisplay)),Object(b.a)(i.props.attributes.onTouchStart,e)},i.handleTouchEnd=function(e){i.touchHandled&&e.preventDefault(),clearTimeout(i.touchstartTimeoutId),Object(b.a)(i.props.attributes.onTouchEnd,e)},i.handleContextMenu=function(e){i.handleContextClick(e),Object(b.a)(i.props.attributes.onContextMenu,e)},i.handleContextClick=function(e){if(!i.props.disable){e.preventDefault(),e.stopPropagation();var t=e.clientX||e.touches&&e.touches[0].pageX,n=e.clientY||e.touches&&e.touches[0].pageY;Object(h.c)();var o=Object(b.a)(i.props.collect,i.props),r={position:{x:t,y:n},target:i.elem,id:i.props.id,data:o};o&&"function"==typeof o.then?o.then(function(e){r.data=e,Object(h.d)(r)}):Object(h.d)(r)}},i.elemRef=function(e){i.elem=e},u=n,r(i,u)}return i(t,e),m(t,[{key:"render",value:function(){var e=this.props,t=e.renderTag,n=e.attributes,o=e.children,r=p()({},n,{className:f()(b.c.menuWrapper,n.className),onContextMenu:this.handleContextMenu,onMouseDown:this.handleMouseDown,onMouseUp:this.handleMouseUp,onTouchStart:this.handleTouchstart,onTouchEnd:this.handleTouchEnd,onMouseOut:this.handleMouseOut,ref:this.elemRef});return a.a.createElement(t,r,o)}}]),t}(u.Component);v.propTypes={id:c.a.string.isRequired,children:c.a.node.isRequired,attributes:c.a.object,collect:c.a.func,disable:c.a.bool,holdToDisplay:c.a.number,renderTag:c.a.oneOfType([c.a.node,c.a.func])},v.defaultProps={attributes:{},collect:function(){return null},disable:!1,holdToDisplay:1e3,renderTag:"div"},t.a=v},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=n(12);n.d(t,"ContextMenu",function(){return o.a});var r=n(10);n.d(t,"ContextMenuTrigger",function(){return r.a});var i=n(8);n.d(t,"MenuItem",function(){return i.a});var u=n(9);n.d(t,"SubMenu",function(){return u.a});var a=n(17);n.d(t,"connectMenu",function(){return a.a});var s=n(3);n.d(t,"hideMenu",function(){return s.c}),n.d(t,"showMenu",function(){return s.d})},function(e,t,n){"use strict";function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(0),s=n.n(a),c=n(2),l=n.n(c),f=n(4),d=n.n(f),p=n(5),h=n.n(p),b=n(6),m=n(7),v=n(9),y=n(3),O=n(1),g=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),w=function(e){function t(e){r(this,t);var n=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.registerHandlers=function(){document.addEventListener("mousedown",n.handleOutsideClick),document.addEventListener("ontouchstart",n.handleOutsideClick),document.addEventListener("scroll",n.handleHide),document.addEventListener("contextmenu",n.handleHide),document.addEventListener("keydown",n.handleKeyNavigation),window.addEventListener("resize",n.handleHide)},n.unregisterHandlers=function(){document.removeEventListener("mousedown",n.handleOutsideClick),document.removeEventListener("ontouchstart",n.handleOutsideClick),document.removeEventListener("scroll",n.handleHide),document.removeEventListener("contextmenu",n.handleHide),document.removeEventListener("keydown",n.handleKeyNavigation),window.removeEventListener("resize",n.handleHide)},n.handleShow=function(e){if(e.detail.id===n.props.id&&!n.state.isVisible){var t=e.detail.position,o=t.x,r=t.y;n.setState({isVisible:!0,x:o,y:r}),n.registerHandlers(),Object(O.a)(n.props.onShow,e)}},n.handleHide=function(e){!n.state.isVisible||e.detail&&e.detail.id&&e.detail.id!==n.props.id||(n.unregisterHandlers(),n.setState({isVisible:!1,selectedItem:null,forceSubMenuOpen:!1}),Object(O.a)(n.props.onHide,e))},n.handleOutsideClick=function(e){n.menu.contains(e.target)||Object(y.c)()},n.handleMouseLeave=function(e){e.preventDefault(),Object(O.a)(n.props.onMouseLeave,e,h()({},n.props.data,O.e.data),O.e.target),n.props.hideOnLeave&&Object(y.c)()},n.handleContextMenu=function(e){e.preventDefault(),n.handleHide(e)},n.hideMenu=function(e){27===e.keyCode&&Object(y.c)()},n.getMenuPosition=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o={top:t,left:e};if(!n.menu)return o;var r=window,i=r.innerWidth,u=r.innerHeight,a=n.menu.getBoundingClientRect();return t+a.height>u&&(o.top-=a.height),e+a.width>i&&(o.left-=a.width),o.top<0&&(o.top=a.height<u?(u-a.height)/2:0),o.left<0&&(o.left=a.width<i?(i-a.width)/2:0),o},n.menuRef=function(e){n.menu=e},n.state=Object.assign({},n.state,{x:0,y:0,isVisible:!1}),n}return u(t,e),g(t,[{key:"getSubMenuType",value:function(){return v.a}},{key:"componentDidMount",value:function(){this.listenId=b.a.register(this.handleShow,this.handleHide)}},{key:"componentDidUpdate",value:function(){var e=this;if(this.state.isVisible){var t=window.requestAnimationFrame||setTimeout;t(function(){var n=e.state,o=n.x,r=n.y,i=e.getMenuPosition(o,r),u=i.top,a=i.left;t(function(){e.menu&&(e.menu.style.top=u+"px",e.menu.style.left=a+"px",e.menu.style.opacity=1,e.menu.style.pointerEvents="auto")})})}else{if(!this.menu)return;this.menu.style.opacity=0,this.menu.style.pointerEvents="none"}}},{key:"componentWillUnmount",value:function(){this.listenId&&b.a.unregister(this.listenId),this.unregisterHandlers()}},{key:"render",value:function(){var e=this.props,t=e.children,n=e.className,r=this.state.isVisible,i={position:"fixed",opacity:0,pointerEvents:"none"},u=d()(O.c.menu,n,o({},O.c.menuVisible,r));return s.a.createElement("nav",{role:"menu",tabIndex:"-1",ref:this.menuRef,style:i,className:u,onContextMenu:this.handleContextMenu,onMouseLeave:this.handleMouseLeave},this.renderChildren(t))}}]),t}(m.a);w.propTypes={id:l.a.string.isRequired,children:l.a.node.isRequired,data:l.a.object,className:l.a.string,hideOnLeave:l.a.bool,onHide:l.a.func,onMouseLeave:l.a.func,onShow:l.a.func},w.defaultProps={className:"",data:{},hideOnLeave:!1,onHide:function(){return null},onMouseLeave:function(){return null},onShow:function(){return null}},t.a=w},function(e,t,n){"use strict";var o=n(14),r=n(15),i=n(16);e.exports=function(){function e(e,t,n,o,u,a){a!==i&&r(!1,"Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types")}function t(){return e}e.isRequired=e;var n={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t};return n.checkPropTypes=o,n.PropTypes=n,n}},function(e,t,n){"use strict";function o(e){return function(){return e}}var r=function(){};r.thatReturns=o,r.thatReturnsFalse=o(!1),r.thatReturnsTrue=o(!0),r.thatReturnsNull=o(null),r.thatReturnsThis=function(){return this},r.thatReturnsArgument=function(e){return e},e.exports=r},function(e,t,n){"use strict";function o(e,t,n,o,i,u,a,s){if(r(t),!e){var c;if(void 0===t)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[n,o,i,u,a,s],f=0;c=new Error(t.replace(/%s/g,function(){return l[f++]})),c.name="Invariant Violation"}throw c.framesToPop=1,c}}var r=function(e){};e.exports=o},function(e,t,n){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(e,t,n){"use strict";function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var u=n(0),a=n.n(u),s=n(10),c=n(6),l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},f=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),d=[].concat(function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}(Object.keys(s.a.propTypes)),["children"]);t.a=function(e){return function(t){return function(n){function u(t){o(this,u);var n=r(this,(u.__proto__||Object.getPrototypeOf(u)).call(this,t));return n.handleShow=function(t){if(t.detail.id===e){var o=t.detail.data,r={};for(var i in o)d.includes(i)||(r[i]=o[i]);n.setState({trigger:r})}},n.handleHide=function(){n.setState({trigger:null})},n.state={trigger:null},n}return i(u,n),f(u,[{key:"componentDidMount",value:function(){this.listenId=c.a.register(this.handleShow,this.handleHide)}},{key:"componentWillUnmount",value:function(){this.listenId&&c.a.unregister(this.listenId)}},{key:"render",value:function(){return a.a.createElement(t,l({},this.props,{id:e,trigger:this.state.trigger}))}}]),u}(u.Component)}}}])}); |
assets/search-view/MessageViewComponent/EmailComponent.js | janta-devs/nyumbani | import React, { Component } from 'react';
var MessageInfo = {};
const Confirmation = () => {
return(
<div>
Message Sent!
</div>
)
}
class Form extends Component{
takeInput( e ){
e.preventDefault();
e.stopPropagation();
MessageInfo['to_id'] = this.refs.employer_id.value.replace(/Employee ID :/, "").trim();
MessageInfo['message_title'] = this.refs.title.value;
MessageInfo['message_body'] = this.refs.message_body.value;
}
render(){
const styleIEButton = {
lineHeight: '10px',
padding: '1px 1px 1px 1px',
textTransform: 'unset',
};
const styleChat = {
height: '200px',
width: '250px',
borderRadius: '10px',
border:'1px solid black',
padding: '10px 10px 10px 10px',
marginBottom: '10px'
};
const inputWidth = {
width: '100%',
};
const tdWidth = {
width: '800px',
};
return(
<div className="form-group label-floating">
<form onSubmit = {this.props.handleSend}>
<div className="mdl-textfield mdl-js-textfield">
<input className="mdl-textfield__input" type="text" id="sample1" name = "employer_id" ref = "employer_id" value ={`Employee ID : ${this.props.userLogin}`} readOnly/>
</div>
<div className="mdl-textfield mdl-js-textfield mdl-textfield--floating-label" style={inputWidth} >
<input className="mdl-textfield__input" type="text" id="sample1" name = "title" ref = "title" onBlur = {this.takeInput.bind(this)}/>
<label className="mdl-textfield__label" htmlFor="smaple1">Type Message Title</label>
</div>
<div className="mdl-textfield mdl-js-textfield mdl-textfield--floating-label" style={inputWidth} >
<textarea cols = "200" rows = "4.52" className="mdl-textfield__input" type="text" id="sample1" name = "message_body" ref = "message_body" onBlur = {this.takeInput.bind(this)}/>
<label className="mdl-textfield__label" htmlFor="smaple1">Message</label>
</div>
<button className = "mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--colored">Send Message</button>
</form>
</div>
)
}
}
class EmailComponent extends Component {
constructor( context, props ){
super();
this.state = {
MessageSent: false
}
}
handleSend( e ){
e.preventDefault();
e.stopPropagation();
MessageInfo['from_id'] = this.props.data.message.to_id;
if( MessageInfo.hasOwnProperty('message_title')
&& MessageInfo.hasOwnProperty('message_body')
&& MessageInfo.hasOwnProperty('to_id'))
{
this.setState({MessageSent: true });
this.props.data.state.Actions.SendMessage( MessageInfo );
}
else
{
console.log( MessageInfo );
}
}
render(){
if(this.state.MessageSent === false ){
return (
<div>
<Form handleSend = {this.handleSend.bind(this)} userLogin = {this.props.data.message.from_id}/>
</div>
);
}
else
{
return <Confirmation />;
}
}
};
export default EmailComponent; |
presto-main/src/main/resources/webapp/vendor/react/react-dom-15.0.1.js | mandusm/presto | /**
* ReactDOM v15.0.1
*
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
// Based off https://github.com/ForbesLindesay/umd/blob/master/template.js
;(function(f) {
// CommonJS
if (typeof exports === "object" && typeof module !== "undefined") {
module.exports = f(require('react'));
// RequireJS
} else if (typeof define === "function" && define.amd) {
define(['react'], f);
// <script>
} else {
var g;
if (typeof window !== "undefined") {
g = window;
} else if (typeof global !== "undefined") {
g = global;
} else if (typeof self !== "undefined") {
g = self;
} else {
// works providing we're not in "use strict";
// needed for Java 8 Nashorn
// see https://github.com/facebook/react/issues/3037
g = this;
}
g.ReactDOM = f(g.React);
}
})(function(React) {
return React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
});
|
packages/material-ui-icons/src/PieChart.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="M11 2v20c-5.07-.5-9-4.79-9-10s3.93-9.5 9-10zm2.03 0v8.99H22c-.47-4.74-4.24-8.52-8.97-8.99zm0 11.01V22c4.74-.47 8.5-4.25 8.97-8.99h-8.97z" /></React.Fragment>
, 'PieChart');
|
src/components/Player.js | jansuchomel/tosine | import React, { Component } from 'react';
import { render } from 'react-dom';
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
export default class Player extends Component {
render() {
const { track, state, mopidyAction, position } = this.props;
let artistComps = [];
if (track.artists != undefined) {
track.artists.forEach(function (artist, i) {
artistComps.push(<b key={"artist_" + i}> {artist.name} </b>);
});
}
return (
<span>
<b>{ track.title } </b>
by { artistComps }
from <b> { track.album.name }</b>
<Control state={ state } mopidyAction={ mopidyAction } />
<SeekBar duration={ track.duration } position={position} state={state} />
</span>);
}
}
class Control extends Component {
resume() {
this.props.mopidyAction("resume");
}
pause() {
this.props.mopidyAction("pause");
}
previous() {
this.props.mopidyAction("previous");
}
next() {
this.props.mopidyAction("next");
}
render() {
const { state, mopidyAction } = this.props;
let playPause = <Button onClick={ this.resume.bind(this) }> <Glyphicon glyph="play" /> </Button>;
if ( state == "playing" ) {
playPause = <Button onClick={ this.pause.bind(this) }> <Glyphicon glyph="pause" /> </Button>;
}
else if ( state == "stopped" ) {
playPause = <b>stopped</b>
}
return (
<div>
<Button onClick={ this.previous.bind(this) }> <Glyphicon glyph="step-backward" /> </Button>
{ playPause }
<Button onClick={ this.next.bind(this) }> <Glyphicon glyph="step-forward" /> </Button>
</div>
)
}
}
class SeekBar extends Component {
constructor(props) {
super(props);
this.state = {position: props.position};
}
componentDidMount() {
setInterval(() => {
this.tick();
}, 100);
this.setState({position: this.props.position});
}
componentWillReceiveProps(nextProps) {
this.setState({position: nextProps.position});
}
tick() {
if (this.props.state == "playing") {
this.setState({position: this.state.position + 100});
this.state.step++;
}
}
render() {
const { duration } = this.props;
if (this.state && "position" in this.state) {
return <b>{ this.state.position / 1000}/{duration / 1000}</b>
}
else {
return <b>ERROR</b>
}
}
}
|
src/icons/AndroidWifi.js | fbfeix/react-icons | import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class AndroidWifi extends React.Component {
render() {
if(this.props.bare) {
return <g>
<path d="M256,228.719c-22.879,0-41.597,18.529-41.597,41.18c0,22.652,18.718,41.182,41.597,41.182
c22.878,0,41.597-18.529,41.597-41.182C297.597,247.248,278.878,228.719,256,228.719z M380.8,269.898
c0-67.946-56.163-123.539-124.8-123.539s-124.8,55.593-124.8,123.539c0,45.303,24.961,85.447,62.396,107.072l20.807-36.032
c-24.972-14.417-41.604-40.153-41.604-71.04c0-45.295,37.433-82.358,83.201-82.358c45.771,0,83.201,37.063,83.201,82.358
c0,30.887-16.633,56.623-41.604,71.04l20.807,36.032C355.837,355.346,380.8,315.201,380.8,269.898z M256,64
C141.597,64,48,156.654,48,269.898C48,346.085,89.592,411.968,152,448l20.799-36.032c-49.919-28.824-83.207-81.324-83.207-142.069
c0-90.593,74.891-164.718,166.408-164.718c91.517,0,166.406,74.125,166.406,164.718c0,60.745-33.284,114.271-83.205,142.069L360,448
c62.406-36.032,104-101.915,104-178.102C464,156.654,370.403,64,256,64z"></path>
</g>;
} return <IconBase>
<path d="M256,228.719c-22.879,0-41.597,18.529-41.597,41.18c0,22.652,18.718,41.182,41.597,41.182
c22.878,0,41.597-18.529,41.597-41.182C297.597,247.248,278.878,228.719,256,228.719z M380.8,269.898
c0-67.946-56.163-123.539-124.8-123.539s-124.8,55.593-124.8,123.539c0,45.303,24.961,85.447,62.396,107.072l20.807-36.032
c-24.972-14.417-41.604-40.153-41.604-71.04c0-45.295,37.433-82.358,83.201-82.358c45.771,0,83.201,37.063,83.201,82.358
c0,30.887-16.633,56.623-41.604,71.04l20.807,36.032C355.837,355.346,380.8,315.201,380.8,269.898z M256,64
C141.597,64,48,156.654,48,269.898C48,346.085,89.592,411.968,152,448l20.799-36.032c-49.919-28.824-83.207-81.324-83.207-142.069
c0-90.593,74.891-164.718,166.408-164.718c91.517,0,166.406,74.125,166.406,164.718c0,60.745-33.284,114.271-83.205,142.069L360,448
c62.406-36.032,104-101.915,104-178.102C464,156.654,370.403,64,256,64z"></path>
</IconBase>;
}
};AndroidWifi.defaultProps = {bare: false} |
enterprise-modules/status-bar/dist/status-bar.esm.min.js | ceolter/ag-grid | /**
* @ag-grid-enterprise/status-bar - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v25.1.0
* @link http://www.ag-grid.com/
' * @license Commercial
*/
/**
* @ag-grid-enterprise/status-bar - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v25.1.0
* @link http://www.ag-grid.com/
' * @license Commercial
*/
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
function t(t){return null==t||""===t?null:t}function e(t,e){return void 0===e&&(e=!1),null!=t&&(""!==t||e)}function o(t){return!e(t)}function n(t){return null==t||0===t.length}function i(t){return null!=t&&"function"==typeof t.toString?t.toString():null}function r(t){if(void 0!==t){if(null===t||""===t)return null;if("number"==typeof t)return isNaN(t)?void 0:t;var e=parseInt(t,10);return isNaN(e)?void 0:e}}function s(t){if(void 0!==t)return null!==t&&""!==t&&("boolean"==typeof t?t:/true/i.test(t))}function a(t,e,o){if(null==t)return null;if(!Array.isArray(t))return a(l(t),e,o);for(var n=t,i=null,r=0;r<n.length;r++){var s=n[r];if("string"==typeof e){if(s[e]===o){i=s;break}}else if(e(s)){i=s;break}}return i}function l(t){if(t instanceof Set||t instanceof Map){var e=[];return t.forEach((function(t){return e.push(t)})),e}return Object.keys(t).map((function(e){return t[e]}))}var p=Object.freeze({__proto__:null,makeNull:t,exists:e,missing:o,missingOrEmpty:n,toStringOrNull:i,attrToNumber:r,attrToBoolean:s,attrToString:function(t){if(null!=t&&""!==t)return t},referenceCompare:function(t,e){return null==t&&null==e||(null!=t||null==e)&&((null==t||null!=e)&&t===e)},jsonEquals:function(t,e){return(t?JSON.stringify(t):null)===(e?JSON.stringify(e):null)},defaultComparator:function(t,e,o){void 0===o&&(o=!1);var n=null==t,i=null==e;if(t&&t.toNumber&&(t=t.toNumber()),e&&e.toNumber&&(e=e.toNumber()),n&&i)return 0;if(n)return-1;if(i)return 1;function r(t,e){return t>e?1:t<e?-1:0}if("string"!=typeof t)return r(t,e);if(!o)return r(t,e);try{return t.localeCompare(e)}catch(o){return r(t,e)}},find:a,values:l}),u=function(){function t(){this.existingKeys={}}return t.prototype.addExistingKeys=function(t){for(var e=0;e<t.length;e++)this.existingKeys[t[e]]=!0},t.prototype.getUniqueKey=function(t,e){t=i(t);for(var o=0;;){var n=void 0;if(t?(n=t,0!==o&&(n+="_"+o)):e?(n=e,0!==o&&(n+="_"+o)):n=""+o,!this.existingKeys[n])return this.existingKeys[n]=!0,n;o++}},t}();
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
function c(){for(var t=[],o=0;o<arguments.length;o++)t[o]=arguments[o];for(var n=0;n<t.length;n++){var i=t[n];if(e(i))return i}return null}function d(t){if(t&&t.length)return t[t.length-1]}function h(t,e,o){return null==t&&null==e||null!=t&&null!=e&&t.length===e.length&&R(t,(function(t,n){return o?o(t,e[n]):e[n]===t}))}function f(t){return t.sort((function(t,e){return t-e}))}function g(t,e){var o=t.indexOf(e);o>=0&&t.splice(o,1)}function y(t,e){P(e,(function(e){return g(t,e)}))}function v(t,e,o){t.splice(o,0,e)}function m(t,e,o){y(t,e),P(e.slice().reverse(),(function(e){return v(t,e,o)}))}function C(t,e){return t.indexOf(e)>-1}function w(t,e){null!=e&&null!=t&&P(e,(function(e){return t.push(e)}))}function E(t,e){for(var o=0;o<t.length;o++)if(e(t[o],o,t))return o;return-1}function R(t,e){if(null==t)return!0;for(var o=0;o<t.length;o++)if(!e(t[o],o))return!1;return!0}function O(t,e){if(null==t)return!1;for(var o=0;o<t.length;o++)if(e(t[o],o))return!0;return!1}function P(t,e){if(null!=t)for(var o=0;o<t.length;o++)e(t[o],o)}function S(t,e){if(null==t)return null;for(var o=[],n=0;n<t.length;n++)o.push(e(t[n],n));return o}function b(t,e){if(null==t)return null;for(var o=[],n=0;n<t.length;n++)e(t[n],n)&&o.push(t[n]);return o}var D=Object.freeze({__proto__:null,firstExistingValue:c,anyExists:function(t){return t&&null!=c(t)},existsAndNotEmpty:function(t){return null!=t&&t.length>0},last:d,areEqual:h,compareArrays:function(t,e){return h(t,e)},shallowCompare:function(t,e){return h(t,e)},sortNumerically:f,removeRepeatsFromArray:function(t,e){if(t)for(var o=t.length-2;o>=0;o--){var n=t[o]===e,i=t[o+1]===e;n&&i&&t.splice(o+1,1)}},removeFromArray:g,removeAllFromArray:y,insertIntoArray:v,insertArrayIntoArray:function(t,e,o){if(null!=t&&null!=e)for(var n=e.length-1;n>=0;n--){v(t,e[n],o)}},moveInArray:m,includes:C,flatten:function(t){return[].concat.apply([],t)},pushAll:w,toStrings:function(t){return S(t,i)},findIndex:E,every:R,some:O,forEach:P,forEachReverse:function(t,e){if(null!=t)for(var o=t.length-1;o>=0;o--)e(t[o],o)},map:S,filter:b,reduce:function(t,e,o){if(null==t||null==o)return null;for(var n=o,i=0;i<t.length;i++)n=e(n,t[i],i);return n},forEachSnapshotFirst:function(t,e){t&&t.slice(0).forEach(e)}});
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/function A(t,e){null!=t&&(Array.isArray(t)?P(t,(function(t,o){return e(""+o,t)})):P(Object.keys(t),(function(o){return e(o,t[o])})))}function T(t){for(var e={},o=Object.keys(t),n=0;n<o.length;n++){var i=o[n],r=t[i];e[i]=r}return e}function _(t,e){if(t){var o=t,n={};return Object.keys(o).forEach((function(t){if(!(e&&e.indexOf(t)>=0)){var i=o[t],r=W(i)&&i.constructor===Object;n[t]=r?_(i):i}})),n}}function F(t,e){return t[e]}function N(t,e,o){t[e]=o}function L(t,e,o,n){var i=F(t,o);void 0!==i&&N(e,o,n?n(i):i)}function I(t){var e={};return t.filter((function(t){return null!=t})).forEach((function(t){P(Object.keys(t),(function(t){return e[t]=null}))})),Object.keys(e)}function G(t,o,n,i){void 0===n&&(n=!0),void 0===i&&(i=!1),e(o)&&A(o,(function(e,o){var r=t[e];if(r!==o){if(i)if(null==r&&null!=o)"object"==typeof o&&o.constructor===Object&&(r={},t[e]=r);W(o)&&W(r)&&!Array.isArray(r)?G(r,o,n,i):(n||void 0!==o)&&(t[e]=o)}}))}function M(t){for(var e=[],o=1;o<arguments.length;o++)e[o-1]=arguments[o];return P(e,(function(e){return A(e,(function(e,o){return t[e]=o}))})),t}function x(t,e,o){if(null==t)return o;for(var n=e.split("."),i=t;n.length>1;)if(null==(i=i[n.shift()]))return o;var r=i[n[0]];return null!=r?r:o}function V(t,e,o){if(e&&t){if(!o)return t[e];for(var n=e.split("."),i=t,r=0;r<n.length;r++){if(null==i)return;i=i[n[r]]}return i}}function H(t,e){Object.keys(t).forEach((function(e){"object"==typeof t[e]&&(t[e]=void 0)}));var o=Object.getPrototypeOf(t),n={};Object.keys(o).forEach((function(t){if("function"==typeof o[t]){n[t]={value:function(){console.warn("AG Grid: "+e+" function "+t+"() cannot be called as the grid has been destroyed.\n Please don't call grid API functions on destroyed grids - as a matter of fact you shouldn't\n be keeping the API reference, your application has a memory leak! Remove the API reference\n when the grid is destroyed.")},writable:!0}}})),Object.defineProperties(t,n)}function W(t){return"object"==typeof t&&null!==t}var k=Object.freeze({__proto__:null,iterateObject:A,cloneObject:T,deepCloneObject:function(t){return JSON.parse(JSON.stringify(t))},deepCloneDefinition:_,getProperty:F,setProperty:N,copyPropertiesIfPresent:function(t,e){for(var o=[],n=2;n<arguments.length;n++)o[n-2]=arguments[n];P(o,(function(o){return L(t,e,o)}))},copyPropertyIfPresent:L,getAllKeysInObjects:I,getAllValuesInObject:function(t){if(!t)return[];if("function"==typeof Object.values)return Object.values(t);var e=[];for(var o in t)t.hasOwnProperty(o)&&t.propertyIsEnumerable(o)&&e.push(t[o]);return e},mergeDeep:G,assign:M,missingOrEmptyObject:function(t){return o(t)||0===Object.keys(t).length},get:x,set:function(t,e,o){if(null!=t){for(var n=e.split("."),i=t;n.length>1;)if(null==(i=i[n.shift()]))return;i[n[0]]=o}},deepFreeze:function t(e){return Object.freeze(e),P(l(e),(function(e){(W(e)||"function"==typeof e)&&t(e)})),e},getValueUsingField:V,removeAllReferences:H,isNonNullObject:W}),B=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,j=/([^\s,]+)/g,U={};
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/function z(t,e){U[e]||(t(),U[e]=!0)}function K(t){if(t.name)return t.name;var e=/function\s+([^\(]+)/.exec(t.toString());return e&&2===e.length?e[1].trim():null}function Y(t){return!!(t&&t.constructor&&t.call&&t.apply)}function q(t){Q(t,400)}function X(t){Q(t,0)}function Q(t,e){void 0===e&&(e=0),t.length>0&&window.setTimeout((function(){return t.forEach((function(t){return t()}))}),e)}function $(t,e,o){var n;return void 0===o&&(o=!1),function(){for(var i=[],r=0;r<arguments.length;r++)i[r]=arguments[r];var s=this,a=o&&!n;window.clearTimeout(n),n=window.setTimeout((function(){n=null,o||t.apply(s,i)}),e),a&&t.apply(s,i)}}function Z(t){t&&t()}var J=Object.freeze({__proto__:null,doOnce:z,getFunctionName:K,getFunctionParameters:function(t){var e=t.toString().replace(B,"");return e.slice(e.indexOf("(")+1,e.indexOf(")")).match(j)||[]},isFunction:Y,executeInAWhile:q,executeNextVMTurn:X,executeAfter:Q,debounce:$,compose:function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return function(e){return t.reduce((function(t,e){return e(t)}),e)}},callIfPresent:Z});
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/function tt(t,e,o){var n=lt(t.constructor);n.preConstructMethods||(n.preConstructMethods=[]),n.preConstructMethods.push(e)}function et(t,e,o){var n=lt(t.constructor);n.postConstructMethods||(n.postConstructMethods=[]),n.postConstructMethods.push(e)}function ot(t,e,o){var n=lt(t.constructor);n.preDestroyMethods||(n.preDestroyMethods=[]),n.preDestroyMethods.push(e)}function nt(t){return function(e){lt(e).beanName=t}}function it(t){return function(e,o,n){st(e,t,!1,e,o,null)}}function rt(t){return function(e,o,n){st(e,t,!0,e,o,null)}}function st(t,e,o,n,i,r){if(null!==e)if("number"!=typeof r){var s=lt(t.constructor);s.agClassAttributes||(s.agClassAttributes=[]),s.agClassAttributes.push({attributeName:i,beanName:e,optional:o})}else console.error("AG Grid: Autowired should be on an attribute");else console.error("AG Grid: Autowired name should not be null")}function at(t){return function(e,o,n){var i,r="function"==typeof e?e:e.constructor;if("number"==typeof n){var s=void 0;o?(i=lt(r),s=o):(i=lt(r),s="agConstructor"),i.autowireMethods||(i.autowireMethods={}),i.autowireMethods[s]||(i.autowireMethods[s]={}),i.autowireMethods[s][n]=t}}}function lt(t){return t.hasOwnProperty("__agBeanMetaData")||(t.__agBeanMetaData={}),t.__agBeanMetaData}
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/var pt,ut=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},ct=function(t,e){return function(o,n){e(o,n,t)}},dt=function(){function t(){this.allSyncListeners=new Map,this.allAsyncListeners=new Map,this.globalSyncListeners=new Set,this.globalAsyncListeners=new Set,this.asyncFunctionsQueue=[],this.scheduled=!1,this.firedEvents={}}return t.prototype.setBeans=function(t,e,o,n){if(void 0===n&&(n=null),this.logger=t.create("EventService"),this.frameworkOverrides=o,n){var i=e.useAsyncEvents();this.addGlobalListener(n,i)}},t.prototype.getListeners=function(t,e){var o=e?this.allAsyncListeners:this.allSyncListeners,n=o.get(t);return n||(n=new Set,o.set(t,n)),n},t.prototype.addEventListener=function(t,e,o){void 0===o&&(o=!1),this.getListeners(t,o).add(e)},t.prototype.removeEventListener=function(t,e,o){void 0===o&&(o=!1),this.getListeners(t,o).delete(e)},t.prototype.addGlobalListener=function(t,e){void 0===e&&(e=!1),(e?this.globalAsyncListeners:this.globalSyncListeners).add(t)},t.prototype.removeGlobalListener=function(t,e){void 0===e&&(e=!1),(e?this.globalAsyncListeners:this.globalSyncListeners).delete(t)},t.prototype.dispatchEvent=function(t){this.dispatchToListeners(t,!0),this.dispatchToListeners(t,!1),this.firedEvents[t.type]=!0},t.prototype.dispatchEventOnce=function(t){this.firedEvents[t.type]||this.dispatchEvent(t)},t.prototype.dispatchToListeners=function(t,e){var o=this,n=t.type;this.getListeners(n,e).forEach((function(n){e?o.dispatchAsync((function(){return n(t)})):n(t)})),(e?this.globalAsyncListeners:this.globalSyncListeners).forEach((function(i){e?o.dispatchAsync((function(){return o.frameworkOverrides.dispatchEvent(n,(function(){return i(n,t)}))})):o.frameworkOverrides.dispatchEvent(n,(function(){return i(n,t)}))}))},t.prototype.dispatchAsync=function(t){this.asyncFunctionsQueue.push(t),this.scheduled||(window.setTimeout(this.flushAsyncQueue.bind(this),0),this.scheduled=!0)},t.prototype.flushAsyncQueue=function(){this.scheduled=!1;var t=this.asyncFunctionsQueue.slice();this.asyncFunctionsQueue=[],t.forEach((function(t){return t()}))},ut([ct(0,at("loggerFactory")),ct(1,at("gridOptionsWrapper")),ct(2,at("frameworkOverrides")),ct(3,at("globalEventListener"))],t.prototype,"setBeans",null),t=ut([nt("eventService")],t)}(),ht=function(){function t(){}return t.ROW_BUFFER_SIZE=10,t.LAYOUT_INTERVAL=500,t.BATCH_WAIT_MILLIS=50,t.EXPORT_TYPE_DRAG_COPY="dragCopy",t.EXPORT_TYPE_CLIPBOARD="clipboard",t.EXPORT_TYPE_EXCEL="excel",t.EXPORT_TYPE_CSV="csv",t.ROW_MODEL_TYPE_INFINITE="infinite",t.ROW_MODEL_TYPE_VIEWPORT="viewport",t.ROW_MODEL_TYPE_CLIENT_SIDE="clientSide",t.ROW_MODEL_TYPE_SERVER_SIDE="serverSide",t.ALWAYS="always",t.ONLY_WHEN_GROUPING="onlyWhenGrouping",t.PINNED_TOP="top",t.PINNED_BOTTOM="bottom",t.DOM_LAYOUT_NORMAL="normal",t.DOM_LAYOUT_PRINT="print",t.DOM_LAYOUT_AUTO_HEIGHT="autoHeight",t.GROUP_AUTO_COLUMN_ID="ag-Grid-AutoColumn",t.SOURCE_PASTE="paste",t.PINNED_RIGHT="right",t.PINNED_LEFT="left",t.SORT_ASC="asc",t.SORT_DESC="desc",t.INPUT_SELECTOR="input, select, button, textarea",t.FOCUSABLE_SELECTOR="[tabindex], input, select, button, textarea",t.FOCUSABLE_EXCLUDE=".ag-hidden, .ag-hidden *, [disabled], .ag-disabled, .ag-disabled *",t}();!function(t){t.CommunityCoreModule="@ag-grid-community/core",t.CommunityAllModules="@ag-grid-community/all",t.InfiniteRowModelModule="@ag-grid-community/infinite-row-model",t.ClientSideRowModelModule="@ag-grid-community/client-side-row-model",t.CsvExportModule="@ag-grid-community/csv-export",t.EnterpriseCoreModule="@ag-grid-enterprise/core",t.EnterpriseAllModules="@ag-grid-enterprise/all",t.RowGroupingModule="@ag-grid-enterprise/row-grouping",t.ColumnToolPanelModule="@ag-grid-enterprise/column-tool-panel",t.FiltersToolPanelModule="@ag-grid-enterprise/filter-tool-panel",t.MenuModule="@ag-grid-enterprise/menu",t.SetFilterModule="@ag-grid-enterprise/set-filter",t.MultiFilterModule="@ag-grid-enterprise/multi-filter",t.StatusBarModule="@ag-grid-enterprise/status-bar",t.SideBarModule="@ag-grid-enterprise/side-bar",t.RangeSelectionModule="@ag-grid-enterprise/range-selection",t.MasterDetailModule="@ag-grid-enterprise/master-detail",t.RichSelectModule="@ag-grid-enterprise/rich-select",t.GridChartsModule="@ag-grid-enterprise/charts",t.ViewportRowModelModule="@ag-grid-enterprise/viewport-row-model",t.ServerSideRowModelModule="@ag-grid-enterprise/server-side-row-model",t.ExcelExportModule="@ag-grid-enterprise/excel-export",t.ClipboardModule="@ag-grid-enterprise/clipboard",t.DateTimeCellEditorModule="@ag-grid-enterprise/date-time-cell-editor",t.AngularModule="@ag-grid-community/angular",t.ReactModule="@ag-grid-community/react",t.VueModule="@ag-grid-community/vue",t.PolymerModule="@ag-grid-community/polymer"}(pt||(pt={}));
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
var ft=function(){function t(){}return t.register=function(e,o){void 0===o&&(o=!0),t.modulesMap[e.moduleName]=e,void 0===t.moduleBased?t.moduleBased=o:t.moduleBased!==o&&z((function(){console.warn("AG Grid: You are mixing modules (i.e. @ag-grid-community/core) and packages (ag-grid-community) - you can only use one or the other of these mechanisms."),console.warn("Please see https://www.ag-grid.com/documentation/javascript/packages-modules/ for more information.")}),"ModulePackageCheck")},t.registerModules=function(e,o){void 0===o&&(o=!0),e&&e.forEach((function(e){return t.register(e,o)}))},t.assertRegistered=function(t,e){if(this.isRegistered(t))return!0;var o="AG Grid: unable to use "+e+" as module "+t+" is not present. Please see: https://www.ag-grid.com/documentation/javascript/modules/";return z((function(){console.warn(o)}),e+t),!1},t.isRegistered=function(e){return!!t.modulesMap[e]},t.getRegisteredModules=function(){return l(t.modulesMap)},t.isPackageBased=function(){return!t.moduleBased},t.modulesMap={},t}(),gt=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},yt=function(){function t(t,e,o,n){this.moving=!1,this.menuVisible=!1,this.filterActive=!1,this.eventService=new dt,this.rowGroupActive=!1,this.pivotActive=!1,this.aggregationActive=!1,this.colDef=t,this.userProvidedColDef=e,this.colId=o,this.primary=n,this.setState(t)}return t.prototype.setState=function(t){void 0!==t.sort?t.sort!==ht.SORT_ASC&&t.sort!==ht.SORT_DESC||(this.sort=t.sort):t.initialSort!==ht.SORT_ASC&&t.initialSort!==ht.SORT_DESC||(this.sort=t.initialSort);var e=r(t.sortIndex),o=r(t.initialSortIndex);void 0!==e?null!==e&&(this.sortIndex=e):null!==o&&(this.sortIndex=o);var n=s(t.hide),i=s(t.initialHide);this.visible=void 0!==n?!n:!i,void 0!==t.pinned?this.setPinned(t.pinned):this.setPinned(t.initialPinned);var a=r(t.flex),l=r(t.initialFlex);void 0!==a?this.flex=a:void 0!==l&&(this.flex=l)},t.prototype.setColDef=function(t,e){this.colDef=t,this.userProvidedColDef=e},t.prototype.getUserProvidedColDef=function(){return this.userProvidedColDef},t.prototype.setParent=function(t){this.parent=t},t.prototype.getParent=function(){return this.parent},t.prototype.setOriginalParent=function(t){this.originalParent=t},t.prototype.getOriginalParent=function(){return this.originalParent},t.prototype.initialise=function(){var t=this.gridOptionsWrapper.getMinColWidth(),o=this.gridOptionsWrapper.getMaxColWidth();null!=this.colDef.minWidth?this.minWidth=Math.max(this.colDef.minWidth,1):this.minWidth=t,null!=this.colDef.maxWidth?this.maxWidth=this.colDef.maxWidth:this.maxWidth=o,this.resetActualWidth("gridInitializing");var n=this.gridOptionsWrapper.isSuppressFieldDotNotation();this.fieldContainsDots=e(this.colDef.field)&&this.colDef.field.indexOf(".")>=0&&!n,this.tooltipFieldContainsDots=e(this.colDef.tooltipField)&&this.colDef.tooltipField.indexOf(".")>=0&&!n,this.validate()},t.prototype.resetActualWidth=function(t){void 0===t&&(t="api");var e=this.columnUtils.calculateColInitialWidth(this.colDef);this.setActualWidth(e,t,!0)},t.prototype.isEmptyGroup=function(){return!1},t.prototype.isRowGroupDisplayed=function(t){if(o(this.colDef)||o(this.colDef.showRowGroup))return!1;var e=!0===this.colDef.showRowGroup,n=this.colDef.showRowGroup===t;return e||n},t.prototype.getUniqueId=function(){return this.getId()},t.prototype.isPrimary=function(){return this.primary},t.prototype.isFilterAllowed=function(){var t=!!this.colDef.filter||!!this.colDef.filterFramework;return this.primary&&t},t.prototype.isFieldContainsDots=function(){return this.fieldContainsDots},t.prototype.isTooltipFieldContainsDots=function(){return this.tooltipFieldContainsDots},t.prototype.validate=function(){var t=this.colDef;function o(t,e,o){z((function(){o?console.warn(t,o):z((function(){return console.warn(t)}),e)}),e)}if(!ft.isRegistered(pt.RowGroupingModule)){["enableRowGroup","rowGroup","rowGroupIndex","enablePivot","enableValue","pivot","pivotIndex","aggFunc"].forEach((function(n){e(t[n])&&(ft.isPackageBased()?o("AG Grid: "+n+" is only valid in ag-grid-enterprise, your column definition should not have "+n,"ColumnRowGroupingMissing"+n):o("AG Grid: "+n+" is only valid with AG Grid Enterprise Module "+pt.RowGroupingModule+" - your column definition should not have "+n,"ColumnRowGroupingMissing"+n))}))}if(ft.isRegistered(pt.RichSelectModule)||"agRichSelect"!==this.colDef.cellEditor&&"agRichSelectCellEditor"!==this.colDef.cellEditor||(ft.isPackageBased()?o("AG Grid: "+this.colDef.cellEditor+" can only be used with ag-grid-enterprise","ColumnRichSelectMissing"):o("AG Grid: "+this.colDef.cellEditor+" can only be used with AG Grid Enterprise Module "+pt.RichSelectModule,"ColumnRichSelectMissing")),ft.isRegistered(pt.DateTimeCellEditorModule)||"agRichSelect"!==this.colDef.cellEditor&&"agDateTimeCellEditor"!==this.colDef.cellEditor||(ft.isPackageBased()?o("AG Grid: "+this.colDef.cellEditor+" can only be used with ag-grid-enterprise","ColumnDateTimeMissing"):o("AG Grid: "+this.colDef.cellEditor+" can only be used with AG Grid Enterprise Module "+pt.DateTimeCellEditorModule,"ColumnDateTimeMissing")),this.gridOptionsWrapper.isTreeData()){["rowGroup","rowGroupIndex","pivot","pivotIndex"].forEach((function(n){e(t[n])&&o("AG Grid: "+n+" is not possible when doing tree data, your column definition should not have "+n,"TreeDataCannotRowGroup")}))}e(this.colDef.width)&&"number"!=typeof this.colDef.width&&o("AG Grid: colDef.width should be a number, not "+typeof this.colDef.width,"ColumnCheck_asdfawef")},t.prototype.addEventListener=function(t,e){this.eventService.addEventListener(t,e)},t.prototype.removeEventListener=function(t,e){this.eventService.removeEventListener(t,e)},t.prototype.createColumnFunctionCallbackParams=function(t){return{node:t,data:t.data,column:this,colDef:this.colDef,context:this.gridOptionsWrapper.getContext(),api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi()}},t.prototype.isSuppressNavigable=function(t){if("boolean"==typeof this.colDef.suppressNavigable)return this.colDef.suppressNavigable;if("function"==typeof this.colDef.suppressNavigable){var e=this.createColumnFunctionCallbackParams(t);return(0,this.colDef.suppressNavigable)(e)}return!1},t.prototype.isCellEditable=function(t){return!(t.group&&!this.gridOptionsWrapper.isEnableGroupEdit())&&this.isColumnFunc(t,this.colDef.editable)},t.prototype.isRowDrag=function(t){return this.isColumnFunc(t,this.colDef.rowDrag)},t.prototype.isDndSource=function(t){return this.isColumnFunc(t,this.colDef.dndSource)},t.prototype.isCellCheckboxSelection=function(t){return this.isColumnFunc(t,this.colDef.checkboxSelection)},t.prototype.isSuppressPaste=function(t){return this.isColumnFunc(t,this.colDef?this.colDef.suppressPaste:null)},t.prototype.isResizable=function(){return!0===this.colDef.resizable},t.prototype.isColumnFunc=function(t,e){return"boolean"==typeof e?e:"function"==typeof e&&e(this.createColumnFunctionCallbackParams(t))},t.prototype.setMoving=function(e,o){void 0===o&&(o="api"),this.moving=e,this.eventService.dispatchEvent(this.createColumnEvent(t.EVENT_MOVING_CHANGED,o))},t.prototype.createColumnEvent=function(t,e){return{api:this.gridApi,columnApi:this.columnApi,type:t,column:this,columns:[this],source:e}},t.prototype.isMoving=function(){return this.moving},t.prototype.getSort=function(){return this.sort},t.prototype.setSort=function(e,o){void 0===o&&(o="api"),this.sort!==e&&(this.sort=e,this.eventService.dispatchEvent(this.createColumnEvent(t.EVENT_SORT_CHANGED,o)))},t.prototype.setMenuVisible=function(e,o){void 0===o&&(o="api"),this.menuVisible!==e&&(this.menuVisible=e,this.eventService.dispatchEvent(this.createColumnEvent(t.EVENT_MENU_VISIBLE_CHANGED,o)))},t.prototype.isMenuVisible=function(){return this.menuVisible},t.prototype.isSortAscending=function(){return this.sort===ht.SORT_ASC},t.prototype.isSortDescending=function(){return this.sort===ht.SORT_DESC},t.prototype.isSortNone=function(){return o(this.sort)},t.prototype.isSorting=function(){return e(this.sort)},t.prototype.getSortIndex=function(){return this.sortIndex},t.prototype.setSortIndex=function(t){this.sortIndex=t},t.prototype.setAggFunc=function(t){this.aggFunc=t},t.prototype.getAggFunc=function(){return this.aggFunc},t.prototype.getLeft=function(){return this.left},t.prototype.getOldLeft=function(){return this.oldLeft},t.prototype.getRight=function(){return this.left+this.actualWidth},t.prototype.setLeft=function(e,o){void 0===o&&(o="api"),this.oldLeft=this.left,this.left!==e&&(this.left=e,this.eventService.dispatchEvent(this.createColumnEvent(t.EVENT_LEFT_CHANGED,o)))},t.prototype.isFilterActive=function(){return this.filterActive},t.prototype.setFilterActive=function(e,o,n){void 0===o&&(o="api"),this.filterActive!==e&&(this.filterActive=e,this.eventService.dispatchEvent(this.createColumnEvent(t.EVENT_FILTER_ACTIVE_CHANGED,o)));var i=this.createColumnEvent(t.EVENT_FILTER_CHANGED,o);n&&G(i,n),this.eventService.dispatchEvent(i)},t.prototype.setPinned=function(t){!0===t||t===ht.PINNED_LEFT?this.pinned=ht.PINNED_LEFT:t===ht.PINNED_RIGHT?this.pinned=ht.PINNED_RIGHT:this.pinned=null},t.prototype.setFirstRightPinned=function(e,o){void 0===o&&(o="api"),this.firstRightPinned!==e&&(this.firstRightPinned=e,this.eventService.dispatchEvent(this.createColumnEvent(t.EVENT_FIRST_RIGHT_PINNED_CHANGED,o)))},t.prototype.setLastLeftPinned=function(e,o){void 0===o&&(o="api"),this.lastLeftPinned!==e&&(this.lastLeftPinned=e,this.eventService.dispatchEvent(this.createColumnEvent(t.EVENT_LAST_LEFT_PINNED_CHANGED,o)))},t.prototype.isFirstRightPinned=function(){return this.firstRightPinned},t.prototype.isLastLeftPinned=function(){return this.lastLeftPinned},t.prototype.isPinned=function(){return this.pinned===ht.PINNED_LEFT||this.pinned===ht.PINNED_RIGHT},t.prototype.isPinnedLeft=function(){return this.pinned===ht.PINNED_LEFT},t.prototype.isPinnedRight=function(){return this.pinned===ht.PINNED_RIGHT},t.prototype.getPinned=function(){return this.pinned},t.prototype.setVisible=function(e,o){void 0===o&&(o="api");var n=!0===e;this.visible!==n&&(this.visible=n,this.eventService.dispatchEvent(this.createColumnEvent(t.EVENT_VISIBLE_CHANGED,o)))},t.prototype.isVisible=function(){return this.visible},t.prototype.getColDef=function(){return this.colDef},t.prototype.getColumnGroupShow=function(){return this.colDef.columnGroupShow},t.prototype.getColId=function(){return this.colId},t.prototype.getId=function(){return this.getColId()},t.prototype.getDefinition=function(){return this.colDef},t.prototype.getActualWidth=function(){return this.actualWidth},t.prototype.createBaseColDefParams=function(t){return{node:t,data:t.data,colDef:this.colDef,column:this,api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi(),context:this.gridOptionsWrapper.getContext()}},t.prototype.getColSpan=function(t){if(o(this.colDef.colSpan))return 1;var e=this.createBaseColDefParams(t),n=this.colDef.colSpan(e);return Math.max(n,1)},t.prototype.getRowSpan=function(t){if(o(this.colDef.rowSpan))return 1;var e=this.createBaseColDefParams(t),n=this.colDef.rowSpan(e);return Math.max(n,1)},t.prototype.setActualWidth=function(t,e,o){void 0===e&&(e="api"),void 0===o&&(o=!1),null!=this.minWidth&&(t=Math.max(t,this.minWidth)),null!=this.maxWidth&&(t=Math.min(t,this.maxWidth)),this.actualWidth!==t&&(this.actualWidth=t,this.flex&&"flex"!==e&&"gridInitializing"!==e&&(this.flex=null),o||this.fireColumnWidthChangedEvent(e))},t.prototype.fireColumnWidthChangedEvent=function(e){this.eventService.dispatchEvent(this.createColumnEvent(t.EVENT_WIDTH_CHANGED,e))},t.prototype.isGreaterThanMax=function(t){return null!=this.maxWidth&&t>this.maxWidth},t.prototype.getMinWidth=function(){return this.minWidth},t.prototype.getMaxWidth=function(){return this.maxWidth},t.prototype.getFlex=function(){return this.flex||0},t.prototype.setFlex=function(t){this.flex!==t&&(this.flex=t)},t.prototype.setMinimum=function(t){void 0===t&&(t="api"),e(this.minWidth)&&this.setActualWidth(this.minWidth,t)},t.prototype.setRowGroupActive=function(e,o){void 0===o&&(o="api"),this.rowGroupActive!==e&&(this.rowGroupActive=e,this.eventService.dispatchEvent(this.createColumnEvent(t.EVENT_ROW_GROUP_CHANGED,o)))},t.prototype.isRowGroupActive=function(){return this.rowGroupActive},t.prototype.setPivotActive=function(e,o){void 0===o&&(o="api"),this.pivotActive!==e&&(this.pivotActive=e,this.eventService.dispatchEvent(this.createColumnEvent(t.EVENT_PIVOT_CHANGED,o)))},t.prototype.isPivotActive=function(){return this.pivotActive},t.prototype.isAnyFunctionActive=function(){return this.isPivotActive()||this.isRowGroupActive()||this.isValueActive()},t.prototype.isAnyFunctionAllowed=function(){return this.isAllowPivot()||this.isAllowRowGroup()||this.isAllowValue()},t.prototype.setValueActive=function(e,o){void 0===o&&(o="api"),this.aggregationActive!==e&&(this.aggregationActive=e,this.eventService.dispatchEvent(this.createColumnEvent(t.EVENT_VALUE_CHANGED,o)))},t.prototype.isValueActive=function(){return this.aggregationActive},t.prototype.isAllowPivot=function(){return!0===this.colDef.enablePivot},t.prototype.isAllowValue=function(){return!0===this.colDef.enableValue},t.prototype.isAllowRowGroup=function(){return!0===this.colDef.enableRowGroup},t.prototype.getMenuTabs=function(t){var e=this.getColDef().menuTabs;return null==e&&(e=t),e},t.prototype.isLockPosition=function(){return console.warn("AG Grid: since v21, col.isLockPosition() should not be used, please use col.getColDef().lockPosition instead."),!!this.colDef&&!!this.colDef.lockPosition},t.prototype.isLockVisible=function(){return console.warn("AG Grid: since v21, col.isLockVisible() should not be used, please use col.getColDef().lockVisible instead."),!!this.colDef&&!!this.colDef.lockVisible},t.prototype.isLockPinned=function(){return console.warn("AG Grid: since v21, col.isLockPinned() should not be used, please use col.getColDef().lockPinned instead."),!!this.colDef&&!!this.colDef.lockPinned},t.EVENT_MOVING_CHANGED="movingChanged",t.EVENT_LEFT_CHANGED="leftChanged",t.EVENT_WIDTH_CHANGED="widthChanged",t.EVENT_LAST_LEFT_PINNED_CHANGED="lastLeftPinnedChanged",t.EVENT_FIRST_RIGHT_PINNED_CHANGED="firstRightPinnedChanged",t.EVENT_VISIBLE_CHANGED="visibleChanged",t.EVENT_FILTER_CHANGED="filterChanged",t.EVENT_FILTER_ACTIVE_CHANGED="filterActiveChanged",t.EVENT_SORT_CHANGED="sortChanged",t.EVENT_MENU_VISIBLE_CHANGED="menuVisibleChanged",t.EVENT_ROW_GROUP_CHANGED="columnRowGroupChanged",t.EVENT_PIVOT_CHANGED="columnPivotChanged",t.EVENT_VALUE_CHANGED="columnValueChanged",gt([it("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),gt([it("columnUtils")],t.prototype,"columnUtils",void 0),gt([it("columnApi")],t.prototype,"columnApi",void 0),gt([it("gridApi")],t.prototype,"gridApi",void 0),gt([it("context")],t.prototype,"context",void 0),gt([et],t.prototype,"initialise",null),t}(),vt=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},mt=function(){function t(t,e,o,n){this.displayedChildren=[],this.localEventService=new dt,this.groupId=e,this.instanceId=o,this.originalColumnGroup=t,this.pinned=n}return t.createUniqueId=function(t,e){return t+"_"+e},t.prototype.reset=function(){this.parent=null,this.children=null,this.displayedChildren=null},t.prototype.getParent=function(){return this.parent},t.prototype.setParent=function(t){this.parent=t},t.prototype.getUniqueId=function(){return t.createUniqueId(this.groupId,this.instanceId)},t.prototype.isEmptyGroup=function(){return 0===this.displayedChildren.length},t.prototype.isMoving=function(){var t=this.getOriginalColumnGroup().getLeafColumns();return!(!t||0===t.length)&&t.every((function(t){return t.isMoving()}))},t.prototype.checkLeft=function(){if(this.displayedChildren.forEach((function(e){e instanceof t&&e.checkLeft()})),this.displayedChildren.length>0)if(this.gridOptionsWrapper.isEnableRtl()){var e=d(this.displayedChildren).getLeft();this.setLeft(e)}else{var o=this.displayedChildren[0].getLeft();this.setLeft(o)}else this.setLeft(null)},t.prototype.getLeft=function(){return this.left},t.prototype.getOldLeft=function(){return this.oldLeft},t.prototype.setLeft=function(e){this.oldLeft=e,this.left!==e&&(this.left=e,this.localEventService.dispatchEvent(this.createAgEvent(t.EVENT_LEFT_CHANGED)))},t.prototype.getPinned=function(){return this.pinned},t.prototype.createAgEvent=function(t){return{type:t}},t.prototype.addEventListener=function(t,e){this.localEventService.addEventListener(t,e)},t.prototype.removeEventListener=function(t,e){this.localEventService.removeEventListener(t,e)},t.prototype.getGroupId=function(){return this.groupId},t.prototype.getInstanceId=function(){return this.instanceId},t.prototype.isChildInThisGroupDeepSearch=function(e){var o=!1;return this.children.forEach((function(n){e===n&&(o=!0),n instanceof t&&n.isChildInThisGroupDeepSearch(e)&&(o=!0)})),o},t.prototype.getActualWidth=function(){var t=0;return this.displayedChildren&&this.displayedChildren.forEach((function(e){t+=e.getActualWidth()})),t},t.prototype.isResizable=function(){if(!this.displayedChildren)return!1;var t=!1;return this.displayedChildren.forEach((function(e){e.isResizable()&&(t=!0)})),t},t.prototype.getMinWidth=function(){var t=0;return this.displayedChildren.forEach((function(e){t+=e.getMinWidth()||0})),t},t.prototype.addChild=function(t){this.children||(this.children=[]),this.children.push(t)},t.prototype.getDisplayedChildren=function(){return this.displayedChildren},t.prototype.getLeafColumns=function(){var t=[];return this.addLeafColumns(t),t},t.prototype.getDisplayedLeafColumns=function(){var t=[];return this.addDisplayedLeafColumns(t),t},t.prototype.getDefinition=function(){return this.originalColumnGroup.getColGroupDef()},t.prototype.getColGroupDef=function(){return this.originalColumnGroup.getColGroupDef()},t.prototype.isPadding=function(){return this.originalColumnGroup.isPadding()},t.prototype.isExpandable=function(){return this.originalColumnGroup.isExpandable()},t.prototype.isExpanded=function(){return this.originalColumnGroup.isExpanded()},t.prototype.setExpanded=function(t){this.originalColumnGroup.setExpanded(t)},t.prototype.addDisplayedLeafColumns=function(e){this.displayedChildren.forEach((function(o){o instanceof yt?e.push(o):o instanceof t&&o.addDisplayedLeafColumns(e)}))},t.prototype.addLeafColumns=function(e){this.children.forEach((function(o){o instanceof yt?e.push(o):o instanceof t&&o.addLeafColumns(e)}))},t.prototype.getChildren=function(){return this.children},t.prototype.getColumnGroupShow=function(){return this.originalColumnGroup.getColumnGroupShow()},t.prototype.getOriginalColumnGroup=function(){return this.originalColumnGroup},t.prototype.getPaddingLevel=function(){var t=this.getParent();return this.isPadding()&&t&&t.isPadding()?1+t.getPaddingLevel():0},t.prototype.calculateDisplayedColumns=function(){var e=this;this.displayedChildren=[];for(var o=this;null!=o&&o.isPadding();)o=o.getParent();!!o&&o.originalColumnGroup.isExpandable()?(this.children.forEach((function(n){if(!(n instanceof t&&(!n.displayedChildren||!n.displayedChildren.length)))switch(n.getColumnGroupShow()){case t.HEADER_GROUP_SHOW_OPEN:o.originalColumnGroup.isExpanded()&&e.displayedChildren.push(n);break;case t.HEADER_GROUP_SHOW_CLOSED:o.originalColumnGroup.isExpanded()||e.displayedChildren.push(n);break;default:e.displayedChildren.push(n)}})),this.localEventService.dispatchEvent(this.createAgEvent(t.EVENT_DISPLAYED_CHILDREN_CHANGED))):this.displayedChildren=this.children},t.HEADER_GROUP_SHOW_OPEN="open",t.HEADER_GROUP_SHOW_CLOSED="closed",t.EVENT_LEFT_CHANGED="leftChanged",t.EVENT_DISPLAYED_CHILDREN_CHANGED="displayedChildrenChanged",vt([it("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),t}(),Ct=function(){function t(t,e,o,n){this.localEventService=new dt,this.expandable=!1,this.colGroupDef=t,this.groupId=e,this.expanded=!!t&&!!t.openByDefault,this.padding=o,this.level=n}return t.prototype.setOriginalParent=function(t){this.originalParent=t},t.prototype.getOriginalParent=function(){return this.originalParent},t.prototype.getLevel=function(){return this.level},t.prototype.isVisible=function(){return!!this.children&&this.children.some((function(t){return t.isVisible()}))},t.prototype.isPadding=function(){return this.padding},t.prototype.setExpanded=function(e){this.expanded=void 0!==e&&e;var o={type:t.EVENT_EXPANDED_CHANGED};this.localEventService.dispatchEvent(o)},t.prototype.isExpandable=function(){return this.expandable},t.prototype.isExpanded=function(){return this.expanded},t.prototype.getGroupId=function(){return this.groupId},t.prototype.getId=function(){return this.getGroupId()},t.prototype.setChildren=function(t){this.children=t},t.prototype.getChildren=function(){return this.children},t.prototype.getColGroupDef=function(){return this.colGroupDef},t.prototype.getLeafColumns=function(){var t=[];return this.addLeafColumns(t),t},t.prototype.addLeafColumns=function(e){this.children&&this.children.forEach((function(o){o instanceof yt?e.push(o):o instanceof t&&o.addLeafColumns(e)}))},t.prototype.getColumnGroupShow=function(){var t=this.colGroupDef;if(t)return t.columnGroupShow},t.prototype.setupExpandable=function(){var t=this;this.setExpandable(),this.getLeafColumns().forEach((function(e){return e.addEventListener(yt.EVENT_VISIBLE_CHANGED,t.onColumnVisibilityChanged.bind(t))}))},t.prototype.setExpandable=function(){if(!this.isPadding()){for(var e=!1,o=!1,n=!1,i=this.findChildrenRemovingPadding(),r=0,s=i.length;r<s;r++){var a=i[r];if(a.isVisible()){var l=a.getColumnGroupShow();l===mt.HEADER_GROUP_SHOW_OPEN?(e=!0,n=!0):l===mt.HEADER_GROUP_SHOW_CLOSED?(o=!0,n=!0):(e=!0,o=!0)}}var p=e&&o&&n;if(this.expandable!==p){this.expandable=p;var u={type:t.EVENT_EXPANDABLE_CHANGED};this.localEventService.dispatchEvent(u)}}},t.prototype.findChildrenRemovingPadding=function(){var e=[],o=function(n){n.forEach((function(n){n instanceof t&&n.isPadding()?o(n.children):e.push(n)}))};return o(this.children),e},t.prototype.onColumnVisibilityChanged=function(){this.setExpandable()},t.prototype.addEventListener=function(t,e){this.localEventService.addEventListener(t,e)},t.prototype.removeEventListener=function(t,e){this.localEventService.removeEventListener(t,e)},t.EVENT_EXPANDED_CHANGED="expandedChanged",t.EVENT_EXPANDABLE_CHANGED="expandableChanged",t}(),wt={numericColumn:{headerClass:"ag-right-aligned-header",cellClass:"ag-right-aligned-cell"},rightAligned:{headerClass:"ag-right-aligned-header",cellClass:"ag-right-aligned-cell"}},Et=["touchstart","touchend","touchmove","touchcancel"],Rt={};
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/function Ot(t){t.__ag_Grid_Stop_Propagation=!0}function Pt(t){return!0===t.__ag_Grid_Stop_Propagation}var St,bt=(St={select:"input",change:"input",submit:"form",reset:"form",error:"img",load:"img",abort:"img"},function(t){if("boolean"==typeof Rt[t])return Rt[t];var e=document.createElement(St[t]||"div"),o=(t="on"+t)in e;return o||(e.setAttribute(t,"return;"),o="function"==typeof e[t]),Rt[t]=o});function Dt(t,e,o){for(var n=At(e);n;){var i=t.getDomData(n,o);if(i)return i;n=n.parentElement}return null}function At(t){var e=t;return e.target||e.srcElement}function Tt(t,e){return!(!e||!t)&&Ft(e).indexOf(t)>=0}function _t(t){for(var e=[],o=At(t);o;)e.push(o),o=o.parentElement;return e}function Ft(t){var e=t;return e.deepPath?e.deepPath():e.path?e.path:e.composedPath?e.composedPath():e.__agGridEventPath?e.__agGridEventPath:_t(t)}function Nt(t,e,o,n){var i=C(Et,o)?{passive:!0}:void 0;t&&t.addEventListener&&t.addEventListener(e,o,n,i)}var Lt,It=Object.freeze({__proto__:null,stopPropagationForAgGrid:Ot,isStopPropagationForAgGrid:Pt,isEventSupported:bt,getComponentForEvent:Dt,addChangeListener:function(t,e){t.addEventListener("changed",e),t.addEventListener("paste",e),t.addEventListener("input",e),t.addEventListener("keydown",e),t.addEventListener("keyup",e)},getTarget:At,isElementInEventPath:Tt,createEventPath:_t,addAgGridEventPath:function(t){t.__agGridEventPath=Ft(t)},getEventPath:Ft,addSafePassiveEventListener:Nt}),Gt=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Mt=function(){function t(){var t=this;this.destroyFunctions=[],this.destroyed=!1,this.__v_skip=!0,this.getContext=function(){return t.context},this.isAlive=function(){return!t.destroyed}}return t.prototype.getFrameworkOverrides=function(){return this.frameworkOverrides},t.prototype.destroy=function(){this.destroyFunctions.forEach((function(t){return t()})),this.destroyFunctions.length=0,this.destroyed=!0,this.dispatchEvent({type:t.EVENT_DESTROYED})},t.prototype.addEventListener=function(t,e){this.localEventService||(this.localEventService=new dt),this.localEventService.addEventListener(t,e)},t.prototype.removeEventListener=function(t,e){this.localEventService&&this.localEventService.removeEventListener(t,e)},t.prototype.dispatchEventAsync=function(t){var e=this;window.setTimeout((function(){return e.dispatchEvent(t)}),0)},t.prototype.dispatchEvent=function(t){this.localEventService&&this.localEventService.dispatchEvent(t)},t.prototype.addManagedListener=function(t,e,o){var n=this;if(!this.destroyed){t instanceof HTMLElement?Nt(this.getFrameworkOverrides(),t,e,o):t.addEventListener(e,o);var i=function(){return t.removeEventListener(e,o),n.destroyFunctions=n.destroyFunctions.filter((function(t){return t!==i})),null};return this.destroyFunctions.push(i),i}},t.prototype.addDestroyFunc=function(t){this.isAlive()?this.destroyFunctions.push(t):t()},t.prototype.createManagedBean=function(t,e){var o=this.createBean(t,e);return this.addDestroyFunc(this.destroyBean.bind(this,t,e)),o},t.prototype.createBean=function(t,e,o){return(e||this.getContext()).createBean(t,o)},t.prototype.destroyBean=function(t,e){return(e||this.getContext()).destroyBean(t)},t.prototype.destroyBeans=function(t,e){var o=this;return t&&P(t,(function(t){return o.destroyBean(t,e)})),[]},t.EVENT_DESTROYED="destroyed",Gt([it("frameworkOverrides")],t.prototype,"frameworkOverrides",void 0),Gt([it("context")],t.prototype,"context",void 0),Gt([it("eventService")],t.prototype,"eventService",void 0),Gt([it("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),Gt([ot],t.prototype,"destroy",null),t}(),xt=(Lt=function(t,e){return(Lt=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(t,e)},function(t,e){function o(){this.constructor=t}Lt(t,e),t.prototype=null===e?Object.create(e):(o.prototype=e.prototype,new o)}),Vt=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Ht=function(t,e){return function(o,n){e(o,n,t)}},Wt=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}xt(e,t),e.prototype.setBeans=function(t){this.logger=t.create("ColumnFactory")},e.prototype.createColumnTree=function(t,e,o){var n=new u,i=this.extractExistingTreeData(o),r=i.existingCols,s=i.existingGroups,a=i.existingColKeys;n.addExistingKeys(a);var l=this.recursivelyCreateColumns(t,0,e,r,n,s),p=this.findMaxDept(l,0);this.logger.log("Number of levels for grouped columns is "+p);var c=this.balanceColumnTree(l,0,p,n);return this.columnUtils.depthFirstOriginalTreeSearch(null,c,(function(t,e){t instanceof Ct&&t.setupExpandable(),t.setOriginalParent(e)})),{columnTree:c,treeDept:p}},e.prototype.extractExistingTreeData=function(t){var e=[],o=[],n=[];return t&&this.columnUtils.depthFirstOriginalTreeSearch(null,t,(function(t){if(t instanceof Ct){var i=t;o.push(i)}else{var r=t;n.push(r.getId()),e.push(r)}})),{existingCols:e,existingGroups:o,existingColKeys:n}},e.prototype.createForAutoGroups=function(t,e){var o=this,n=[];return t.forEach((function(t){var i=o.createAutoGroupTreeItem(e,t);n.push(i)})),n},e.prototype.createAutoGroupTreeItem=function(t,e){for(var o=e,n=this.findDepth(t)-1;n>=0;n--){var i=new Ct(null,"FAKE_PATH_"+e.getId()+"}_"+n,!0,n);this.context.createBean(i),i.setChildren([o]),o.setOriginalParent(i),o=i}return o},e.prototype.findDepth=function(t){for(var e=0,o=t;o&&o[0]&&o[0]instanceof Ct;)e++,o=o[0].getChildren();return e},e.prototype.balanceColumnTree=function(t,e,o,n){for(var i=[],r=0;r<t.length;r++){var s=t[r];if(s instanceof Ct){var a=s,l=this.balanceColumnTree(a.getChildren(),e+1,o,n);a.setChildren(l),i.push(a)}else{for(var p=void 0,u=void 0,c=o-1;c>=e;c--){var d=n.getUniqueKey(null,null),h=this.createMergedColGroupDef(null),f=new Ct(h,d,!0,e);this.context.createBean(f),u&&u.setChildren([f]),u=f,p||(p=u)}if(p&&u){if(i.push(p),t.some((function(t){return t instanceof Ct}))){u.setChildren([s]);continue}u.setChildren(t);break}i.push(s)}}return i},e.prototype.findMaxDept=function(t,e){for(var o=e,n=0;n<t.length;n++){var i=t[n];if(i instanceof Ct){var r=i,s=this.findMaxDept(r.getChildren(),e+1);o<s&&(o=s)}}return o},e.prototype.recursivelyCreateColumns=function(t,e,o,n,i,r){var s=this,a=[];return t?(t.forEach((function(t){var l;l=s.isColumnGroup(t)?s.createColumnGroup(o,t,e,n,i,r):s.createColumn(o,t,n,i),a.push(l)})),a):a},e.prototype.createColumnGroup=function(t,e,o,n,i,r){var s=this.createMergedColGroupDef(e),a=i.getUniqueKey(s.groupId||null,null),l=new Ct(s,a,!1,o);this.context.createBean(l);var p=this.findExistingGroup(e,r);p&&p.isExpanded()&&l.setExpanded(!0);var u=this.recursivelyCreateColumns(s.children,o+1,t,n,i,r);return l.setChildren(u),l},e.prototype.createMergedColGroupDef=function(t){var e={};return M(e,this.gridOptionsWrapper.getDefaultColGroupDef()),M(e,t),this.checkForDeprecatedItems(e),e},e.prototype.createColumn=function(t,e,o,n){var i=this.mergeColDefs(e);this.checkForDeprecatedItems(i);var r=this.findExistingColumn(e,o);if(r)r.setColDef(i,e),this.applyColumnState(r,i);else{var s=n.getUniqueKey(i.colId,i.field);r=new yt(i,e,s,t),this.context.createBean(r)}return r},e.prototype.applyColumnState=function(t,e){var o=r(e.flex);if(void 0!==o&&t.setFlex(o),t.getFlex()<=0){var n=r(e.width);null!=n&&t.setActualWidth(n)}void 0!==e.sort&&(e.sort==ht.SORT_ASC||e.sort==ht.SORT_DESC?t.setSort(e.sort):t.setSort(void 0));var i=r(e.sortIndex);void 0!==i&&t.setSortIndex(i);var a=s(e.hide);void 0!==a&&t.setVisible(!a),void 0!==e.pinned&&t.setPinned(e.pinned)},e.prototype.findExistingColumn=function(t,e){var o=a(e,(function(e){var o=e.getUserProvidedColDef();if(!o)return!1;var n=null!=t.colId,i=null!=t.field;return n?e.getId()===t.colId:i?o.field===t.field:o===t}));return e&&o&&g(e,o),o},e.prototype.findExistingGroup=function(t,e){var o=a(e,(function(e){return!!e.getColGroupDef()&&(!(null==t.groupId)&&e.getId()===t.groupId)}));return o&&g(e,o),o},e.prototype.mergeColDefs=function(t){var e={},o=this.gridOptionsWrapper.getDefaultColDef();G(e,o,!0,!0);var n=t.type;return n||(n=o&&o.type),n&&this.assignColumnTypes(n,e),G(e,t,!0,!0),e},e.prototype.assignColumnTypes=function(t,e){var o=[];if(t instanceof Array){t.some((function(t){return"string"!=typeof t}))?console.warn("ag-grid: if colDef.type is supplied an array it should be of type 'string[]'"):o=t}else{if("string"!=typeof t)return void console.warn("ag-grid: colDef.type should be of type 'string' | 'string[]'");o=t.split(",")}var n=M({},wt);A(this.gridOptionsWrapper.getColumnTypes()||{},(function(t,e){t in n?console.warn("AG Grid: the column type '"+t+"' is a default column type and cannot be overridden."):n[t]=e})),o.forEach((function(t){var o=n[t.trim()];o?G(e,o,!0,!0):console.warn("ag-grid: colDef.type '"+t+"' does not correspond to defined gridOptions.columnTypes")}))},e.prototype.checkForDeprecatedItems=function(t){if(t){var e=t;void 0!==e.group&&console.warn("ag-grid: colDef.group is invalid, please check documentation on how to do grouping as it changed in version 3"),void 0!==e.headerGroup&&console.warn("ag-grid: colDef.headerGroup is invalid, please check documentation on how to do grouping as it changed in version 3"),void 0!==e.headerGroupShow&&console.warn("ag-grid: colDef.headerGroupShow is invalid, should be columnGroupShow, please check documentation on how to do grouping as it changed in version 3"),void 0!==e.suppressRowGroup&&console.warn("ag-grid: colDef.suppressRowGroup is deprecated, please use colDef.type instead"),void 0!==e.suppressAggregation&&console.warn("ag-grid: colDef.suppressAggregation is deprecated, please use colDef.type instead"),(e.suppressRowGroup||e.suppressAggregation)&&console.warn("ag-grid: colDef.suppressAggregation and colDef.suppressRowGroup are deprecated, use allowRowGroup, allowPivot and allowValue instead"),e.displayName&&(console.warn("ag-grid: Found displayName "+e.displayName+", please use headerName instead, displayName is deprecated."),e.headerName=e.displayName)}},e.prototype.isColumnGroup=function(t){return void 0!==t.children},Vt([it("columnUtils")],e.prototype,"columnUtils",void 0),Vt([Ht(0,at("loggerFactory"))],e.prototype,"setBeans",null),e=Vt([nt("columnFactory")],e)}(Mt),function(){function t(){}return t.EVENT_COLUMN_EVERYTHING_CHANGED="columnEverythingChanged",t.EVENT_NEW_COLUMNS_LOADED="newColumnsLoaded",t.EVENT_COLUMN_PIVOT_MODE_CHANGED="columnPivotModeChanged",t.EVENT_COLUMN_ROW_GROUP_CHANGED="columnRowGroupChanged",t.EVENT_EXPAND_COLLAPSE_ALL="expandOrCollapseAll",t.EVENT_COLUMN_PIVOT_CHANGED="columnPivotChanged",t.EVENT_GRID_COLUMNS_CHANGED="gridColumnsChanged",t.EVENT_COLUMN_VALUE_CHANGED="columnValueChanged",t.EVENT_COLUMN_MOVED="columnMoved",t.EVENT_COLUMN_VISIBLE="columnVisible",t.EVENT_COLUMN_PINNED="columnPinned",t.EVENT_COLUMN_GROUP_OPENED="columnGroupOpened",t.EVENT_COLUMN_RESIZED="columnResized",t.EVENT_DISPLAYED_COLUMNS_CHANGED="displayedColumnsChanged",t.EVENT_VIRTUAL_COLUMNS_CHANGED="virtualColumnsChanged",t.EVENT_ASYNC_TRANSACTIONS_FLUSHED="asyncTransactionsFlushed",t.EVENT_ROW_GROUP_OPENED="rowGroupOpened",t.EVENT_ROW_DATA_CHANGED="rowDataChanged",t.EVENT_ROW_DATA_UPDATED="rowDataUpdated",t.EVENT_PINNED_ROW_DATA_CHANGED="pinnedRowDataChanged",t.EVENT_RANGE_SELECTION_CHANGED="rangeSelectionChanged",t.EVENT_CHART_CREATED="chartCreated",t.EVENT_CHART_RANGE_SELECTION_CHANGED="chartRangeSelectionChanged",t.EVENT_CHART_OPTIONS_CHANGED="chartOptionsChanged",t.EVENT_CHART_DESTROYED="chartDestroyed",t.EVENT_TOOL_PANEL_VISIBLE_CHANGED="toolPanelVisibleChanged",t.EVENT_MODEL_UPDATED="modelUpdated",t.EVENT_PASTE_START="pasteStart",t.EVENT_PASTE_END="pasteEnd",t.EVENT_FILL_START="fillStart",t.EVENT_FILL_END="fillEnd",t.EVENT_CELL_CLICKED="cellClicked",t.EVENT_CELL_DOUBLE_CLICKED="cellDoubleClicked",t.EVENT_CELL_MOUSE_DOWN="cellMouseDown",t.EVENT_CELL_CONTEXT_MENU="cellContextMenu",t.EVENT_CELL_VALUE_CHANGED="cellValueChanged",t.EVENT_ROW_VALUE_CHANGED="rowValueChanged",t.EVENT_CELL_FOCUSED="cellFocused",t.EVENT_ROW_SELECTED="rowSelected",t.EVENT_SELECTION_CHANGED="selectionChanged",t.EVENT_CELL_KEY_DOWN="cellKeyDown",t.EVENT_CELL_KEY_PRESS="cellKeyPress",t.EVENT_CELL_MOUSE_OVER="cellMouseOver",t.EVENT_CELL_MOUSE_OUT="cellMouseOut",t.EVENT_FILTER_CHANGED="filterChanged",t.EVENT_FILTER_MODIFIED="filterModified",t.EVENT_FILTER_OPENED="filterOpened",t.EVENT_SORT_CHANGED="sortChanged",t.EVENT_VIRTUAL_ROW_REMOVED="virtualRowRemoved",t.EVENT_ROW_CLICKED="rowClicked",t.EVENT_ROW_DOUBLE_CLICKED="rowDoubleClicked",t.EVENT_GRID_READY="gridReady",t.EVENT_GRID_SIZE_CHANGED="gridSizeChanged",t.EVENT_VIEWPORT_CHANGED="viewportChanged",t.EVENT_SCROLLBAR_WIDTH_CHANGED="scrollbarWidthChanged",t.EVENT_FIRST_DATA_RENDERED="firstDataRendered",t.EVENT_DRAG_STARTED="dragStarted",t.EVENT_DRAG_STOPPED="dragStopped",t.EVENT_CHECKBOX_CHANGED="checkboxChanged",t.EVENT_ROW_EDITING_STARTED="rowEditingStarted",t.EVENT_ROW_EDITING_STOPPED="rowEditingStopped",t.EVENT_CELL_EDITING_STARTED="cellEditingStarted",t.EVENT_CELL_EDITING_STOPPED="cellEditingStopped",t.EVENT_BODY_SCROLL="bodyScroll",t.EVENT_ANIMATION_QUEUE_EMPTY="animationQueueEmpty",t.EVENT_HEIGHT_SCALE_CHANGED="heightScaleChanged",t.EVENT_PAGINATION_CHANGED="paginationChanged",t.EVENT_COMPONENT_STATE_CHANGED="componentStateChanged",t.EVENT_BODY_HEIGHT_CHANGED="bodyHeightChanged",t.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED="displayedColumnsWidthChanged",t.EVENT_SCROLL_VISIBILITY_CHANGED="scrollVisibilityChanged",t.EVENT_COLUMN_HOVER_CHANGED="columnHoverChanged",t.EVENT_FLASH_CELLS="flashCells",t.EVENT_PAGINATION_PIXEL_OFFSET_CHANGED="paginationPixelOffsetChanged",t.EVENT_ROW_DRAG_ENTER="rowDragEnter",t.EVENT_ROW_DRAG_MOVE="rowDragMove",t.EVENT_ROW_DRAG_LEAVE="rowDragLeave",t.EVENT_ROW_DRAG_END="rowDragEnd",t.EVENT_POPUP_TO_FRONT="popupToFront",t.EVENT_COLUMN_ROW_GROUP_CHANGE_REQUEST="columnRowGroupChangeRequest",t.EVENT_COLUMN_PIVOT_CHANGE_REQUEST="columnPivotChangeRequest",t.EVENT_COLUMN_VALUE_CHANGE_REQUEST="columnValueChangeRequest",t.EVENT_COLUMN_AGG_FUNC_CHANGE_REQUEST="columnAggFuncChangeRequest",t.EVENT_KEYBOARD_FOCUS="keyboardFocus",t.EVENT_MOUSE_FOCUS="mouseFocus",t.EVENT_STORE_UPDATED="storeUpdated",t}()),kt=function(){function t(){this.existingIds={}}return t.prototype.getInstanceIdForKey=function(t){var e,o=this.existingIds[t];return e="number"!=typeof o?0:o+1,this.existingIds[t]=e,e},t}(),Bt=/[&<>"']/g,jt={"&":"&","<":"<",">":">",'"':""","'":"'"};
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/function Ut(t){return null==t?null:t.replace(/([A-Z])/g,(function(t){return"-"+t[0].toLowerCase()}))}function zt(t){return null==t?null:t.replace(/-([a-z])/g,(function(t){return t[1].toUpperCase()}))}function Kt(t){return null!=t&&t.replace?t.replace(Bt,(function(t){return jt[t]})):t}function Yt(t){if(!t||null==t)return null;return t.replace(/([A-Z])([A-Z])([a-z])|([a-z])([A-Z])/g,"$1$4 $2$3$5").replace("."," ").split(" ").map((function(t){return t.substring(0,1).toUpperCase()+(t.length>1?t.substring(1,t.length):"")})).join(" ")}function qt(t,e){return t===e||null!=t&&t.slice(0,e.length)===e}var Xt=Object.freeze({__proto__:null,utf8_encode:function(t){var e=String.fromCharCode;function o(t,o){return e(t>>o&63|128)}function n(t){if(0==(4294967168&t))return e(t);var n="";return 0==(4294965248&t)?n=e(t>>6&31|192):0==(4294901760&t)?(!function(t){if(t>=55296&&t<=57343)throw Error("Lone surrogate U+"+t.toString(16).toUpperCase()+" is not a scalar value")}(t),n=e(t>>12&15|224),n+=o(t,6)):0==(4292870144&t)&&(n=e(t>>18&7|240),n+=o(t,12),n+=o(t,6)),n+=e(63&t|128)}for(var i=function(t){var e=[];if(!t)return[];for(var o,n,i=t.length,r=0;r<i;)(o=t.charCodeAt(r++))>=55296&&o<=56319&&r<i?56320==(64512&(n=t.charCodeAt(r++)))?e.push(((1023&o)<<10)+(1023&n)+65536):(e.push(o),r--):e.push(o);return e}(t),r=i.length,s=-1,a="";++s<r;)a+=n(i[s]);return a},camelCaseToHyphen:Ut,hyphenToCamelCase:zt,capitalise:function(t){return t[0].toUpperCase()+t.substr(1).toLowerCase()},escapeString:Kt,camelCaseToHumanText:Yt,startsWith:qt}),Qt=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),$t=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Zt=function(t,e){return function(o,n){e(o,n,t)}};
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/!function(t){function i(){var e=null!==t&&t.apply(this,arguments)||this;return e.primaryHeaderRowCount=0,e.secondaryHeaderRowCount=0,e.secondaryColumnsPresent=!1,e.gridHeaderRowCount=0,e.displayedColumnsLeft=[],e.displayedColumnsRight=[],e.displayedColumnsCenter=[],e.displayedColumns=[],e.displayedColumnsAndGroupsMap={},e.viewportColumns=[],e.viewportColumnsCenter=[],e.rowGroupColumns=[],e.valueColumns=[],e.pivotColumns=[],e.ready=!1,e.autoGroupsNeedBuilding=!1,e.forceRecreateAutoGroups=!1,e.pivotMode=!1,e.bodyWidth=0,e.leftWidth=0,e.rightWidth=0,e.bodyWidthDirty=!0,e.colDefVersion=0,e.flexColsCalculatedAtLestOnce=!1,e}Qt(i,t),i.prototype.init=function(){this.suppressColumnVirtualisation=this.gridOptionsWrapper.isSuppressColumnVirtualisation();var t=this.gridOptionsWrapper.isPivotMode();this.isPivotSettingAllowed(t)&&(this.pivotMode=t),this.usingTreeData=this.gridOptionsWrapper.isTreeData(),this.addManagedListener(this.gridOptionsWrapper,"autoGroupColumnDef",this.onAutoGroupColumnDefChanged.bind(this))},i.prototype.onAutoGroupColumnDefChanged=function(){this.autoGroupsNeedBuilding=!0,this.forceRecreateAutoGroups=!0,this.updateGridColumns(),this.updateDisplayedColumns("gridOptionsChanged")},i.prototype.getColDefVersion=function(){return this.colDefVersion},i.prototype.setColumnDefs=function(t,e){var o=this;void 0===e&&(e="api");var n=!!this.columnDefs;this.colDefVersion++;var i=this.compareColumnStatesAndRaiseEvents(e);this.columnDefs=t,this.valueCache.expire(),this.autoGroupsNeedBuilding=!0;var r=this.primaryColumns,s=this.primaryColumnTree,a=this.columnFactory.createColumnTree(t,!0,s);this.primaryColumnTree=a.columnTree,this.primaryHeaderRowCount=a.treeDept+1,this.primaryColumns=this.getColumnsFromTree(this.primaryColumnTree),this.primaryColumnsMap={},this.primaryColumns.forEach((function(t){return o.primaryColumnsMap[t.getId()]=t})),this.extractRowGroupColumns(e,r),this.extractPivotColumns(e,r),this.extractValueColumns(e,r),this.ready=!0,this.updateGridColumns(),n&&this.gridColsArePrimary&&this.gridOptionsWrapper.isApplyColumnDefOrder()&&this.orderGridColumnsLikePrimary(),this.updateDisplayedColumns(e),this.checkViewportColumns(),this.dispatchEverythingChanged(e),i(),this.dispatchNewColumnsLoaded()},i.prototype.dispatchNewColumnsLoaded=function(){var t={type:Wt.EVENT_NEW_COLUMNS_LOADED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(t)},i.prototype.dispatchEverythingChanged=function(t){void 0===t&&(t="api");var e={type:Wt.EVENT_COLUMN_EVERYTHING_CHANGED,api:this.gridApi,columnApi:this.columnApi,source:t};this.eventService.dispatchEvent(e)},i.prototype.orderGridColumnsLikePrimary=function(){var t=this;this.gridColumns.sort((function(e,o){var n=t.primaryColumns.indexOf(e),i=t.primaryColumns.indexOf(o),r=n>=0,s=i>=0;return r&&s?n-i:r?1:s?-1:t.gridColumns.indexOf(e)-t.gridColumns.indexOf(o)}))},i.prototype.isAutoRowHeightActive=function(){return this.autoRowHeightColumns&&this.autoRowHeightColumns.length>0},i.prototype.getAllAutoRowHeightCols=function(){return this.autoRowHeightColumns},i.prototype.setViewport=function(){this.gridOptionsWrapper.isEnableRtl()?(this.viewportLeft=this.bodyWidth-this.scrollPosition-this.scrollWidth,this.viewportRight=this.bodyWidth-this.scrollPosition):(this.viewportLeft=this.scrollPosition,this.viewportRight=this.scrollWidth+this.scrollPosition)},i.prototype.getDisplayedColumnsStartingAt=function(t){for(var e=t,o=[];null!=e;)o.push(e),e=this.getDisplayedColAfter(e);return o},i.prototype.checkViewportColumns=function(){if(null!=this.displayedColumnsCenter){var t=this.viewportColumns.map((function(t){return t.getId()})).join("#");if(this.extractViewport(),t!==this.viewportColumns.map((function(t){return t.getId()})).join("#")){var e={type:Wt.EVENT_VIRTUAL_COLUMNS_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(e)}}},i.prototype.setViewportPosition=function(t,e){(t!==this.scrollWidth||e!==this.scrollPosition||this.bodyWidthDirty)&&(this.scrollWidth=t,this.scrollPosition=e,this.bodyWidthDirty=!0,this.setViewport(),this.ready&&this.checkViewportColumns())},i.prototype.isPivotMode=function(){return this.pivotMode},i.prototype.isPivotSettingAllowed=function(t){return!t||!this.gridOptionsWrapper.isTreeData()||(console.warn("AG Grid: Pivot mode not available in conjunction Tree Data i.e. 'gridOptions.treeData: true'"),!1)},i.prototype.setPivotMode=function(t,e){if(void 0===e&&(e="api"),t!==this.pivotMode&&this.isPivotSettingAllowed(this.pivotMode)){this.pivotMode=t,this.autoGroupsNeedBuilding=!0,this.updateGridColumns(),this.updateDisplayedColumns(e);var o={type:Wt.EVENT_COLUMN_PIVOT_MODE_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(o)}},i.prototype.getSecondaryPivotColumn=function(t,e){if(!this.secondaryColumnsPresent||!this.secondaryColumns)return null;var o=this.getPrimaryColumn(e),n=null;return this.secondaryColumns.forEach((function(e){var i=e.getColDef().pivotKeys,r=e.getColDef().pivotValueColumn;h(i,t)&&r===o&&(n=e)})),n},i.prototype.setBeans=function(t){this.logger=t.create("ColumnController")},i.prototype.setFirstRightAndLastLeftPinned=function(t){var e,o;this.gridOptionsWrapper.isEnableRtl()?(e=this.displayedColumnsLeft?this.displayedColumnsLeft[0]:null,o=this.displayedColumnsRight?d(this.displayedColumnsRight):null):(e=this.displayedColumnsLeft?d(this.displayedColumnsLeft):null,o=this.displayedColumnsRight?this.displayedColumnsRight[0]:null),this.gridColumns.forEach((function(n){n.setLastLeftPinned(n===e,t),n.setFirstRightPinned(n===o,t)}))},i.prototype.autoSizeColumns=function(t,e,o){var n=this;void 0===o&&(o="api"),this.animationFrameService.flushAllFrames();var i=[],r=-1;for(null==e&&(e=this.gridOptionsWrapper.isSkipHeaderOnAutoSize());0!==r;)r=0,this.actionOnGridColumns(t,(function(t){if(i.indexOf(t)>=0)return!1;var s=n.autoWidthCalculator.getPreferredWidthForColumn(t,e);if(s>0){var a=n.normaliseColumnWidth(t,s);t.setActualWidth(a,o),i.push(t),r++}return!0}),o);this.fireColumnResizedEvent(i,!0,"autosizeColumns")},i.prototype.fireColumnResizedEvent=function(t,e,o,n){if(void 0===n&&(n=null),t&&t.length){var i={type:Wt.EVENT_COLUMN_RESIZED,columns:t,column:1===t.length?t[0]:null,flexColumns:n,finished:e,api:this.gridApi,columnApi:this.columnApi,source:o};this.eventService.dispatchEvent(i)}},i.prototype.autoSizeColumn=function(t,e,o){void 0===o&&(o="api"),t&&this.autoSizeColumns([t],e,o)},i.prototype.autoSizeAllColumns=function(t,e){void 0===e&&(e="api");var o=this.getAllDisplayedColumns();this.autoSizeColumns(o,t,e)},i.prototype.getColumnsFromTree=function(t){var e=[],o=function(t){for(var n=0;n<t.length;n++){var i=t[n];i instanceof yt?e.push(i):i instanceof Ct&&o(i.getChildren())}};return o(t),e},i.prototype.getAllDisplayedTrees=function(){return this.displayedTreeLeft&&this.displayedTreeRight&&this.displayedTreeCentre?this.displayedTreeLeft.concat(this.displayedTreeCentre).concat(this.displayedTreeRight):null},i.prototype.getPrimaryColumnTree=function(){return this.primaryColumnTree},i.prototype.getHeaderRowCount=function(){return this.gridHeaderRowCount},i.prototype.getDisplayedTreeLeft=function(){return this.displayedTreeLeft},i.prototype.getDisplayedTreeRight=function(){return this.displayedTreeRight},i.prototype.getDisplayedTreeCentre=function(){return this.displayedTreeCentre},i.prototype.isColumnDisplayed=function(t){return this.getAllDisplayedColumns().indexOf(t)>=0},i.prototype.getAllDisplayedColumns=function(){return this.displayedColumns},i.prototype.getViewportColumns=function(){return this.viewportColumns},i.prototype.getDisplayedLeftColumnsForRow=function(t){return this.colSpanActive?this.getDisplayedColumnsForRow(t,this.displayedColumnsLeft):this.displayedColumnsLeft},i.prototype.getDisplayedRightColumnsForRow=function(t){return this.colSpanActive?this.getDisplayedColumnsForRow(t,this.displayedColumnsRight):this.displayedColumnsRight},i.prototype.getDisplayedColumnsForRow=function(t,e,o,n){for(var i,r=[],s=null,a=function(a){var l,p=e[a],u=e.length-a,c=Math.min(p.getColSpan(t),u),d=[p];if(c>1){for(var h=c-1,f=1;f<=h;f++)d.push(e[a+f]);a+=h}if(o?(l=!1,d.forEach((function(t){o(t)&&(l=!0)}))):l=!0,l){if(0===r.length&&s)!!n&&n(p)&&r.push(s);r.push(p)}s=p,i=a},l=0;l<e.length;l++)a(l),l=i;return r},i.prototype.getViewportCenterColumnsForRow=function(t){var o=this;if(!this.colSpanActive)return this.viewportColumnsCenter;var n=this.suppressColumnVirtualisation?null:this.isColumnInViewport.bind(this);return this.getDisplayedColumnsForRow(t,this.displayedColumnsCenter,n,(function(t){var n=t.getLeft();return e(n)&&n>o.viewportLeft}))},i.prototype.getAriaColumnIndex=function(t){return this.getAllGridColumns().indexOf(t)+1},i.prototype.isColumnInViewport=function(t){var e=t.getLeft()||0,o=e+t.getActualWidth(),n=this.viewportLeft-200,i=this.viewportRight+200;return!(e<n&&o<n)&&!(e>i&&o>i)},i.prototype.getDisplayedColumnsLeftWidth=function(){return this.getWidthOfColsInList(this.displayedColumnsLeft)},i.prototype.getDisplayedColumnsRightWidth=function(){return this.getWidthOfColsInList(this.displayedColumnsRight)},i.prototype.updatePrimaryColumnList=function(t,e,o,i,r,s){var a=this;if(void 0===s&&(s="api"),t&&!n(t)){var l=!1;if(t.forEach((function(t){var n=a.getPrimaryColumn(t);if(n){if(o){if(e.indexOf(n)>=0)return;e.push(n)}else{if(e.indexOf(n)<0)return;g(e,n)}i(n),l=!0}})),l){this.autoGroupsNeedBuilding&&this.updateGridColumns(),this.updateDisplayedColumns(s);var p={type:r,columns:e,column:1===e.length?e[0]:null,api:this.gridApi,columnApi:this.columnApi,source:s};this.eventService.dispatchEvent(p)}}},i.prototype.setRowGroupColumns=function(t,e){void 0===e&&(e="api"),this.autoGroupsNeedBuilding=!0,this.setPrimaryColumnList(t,this.rowGroupColumns,Wt.EVENT_COLUMN_ROW_GROUP_CHANGED,this.setRowGroupActive.bind(this),e)},i.prototype.setRowGroupActive=function(t,e,o){t!==e.isRowGroupActive()&&(e.setRowGroupActive(t,o),t||this.gridOptionsWrapper.isSuppressMakeColumnVisibleAfterUnGroup()||e.setVisible(!0,o))},i.prototype.addRowGroupColumn=function(t,e){void 0===e&&(e="api"),t&&this.addRowGroupColumns([t],e)},i.prototype.addRowGroupColumns=function(t,e){void 0===e&&(e="api"),this.autoGroupsNeedBuilding=!0,this.updatePrimaryColumnList(t,this.rowGroupColumns,!0,this.setRowGroupActive.bind(this,!0),Wt.EVENT_COLUMN_ROW_GROUP_CHANGED,e)},i.prototype.removeRowGroupColumns=function(t,e){void 0===e&&(e="api"),this.autoGroupsNeedBuilding=!0,this.updatePrimaryColumnList(t,this.rowGroupColumns,!1,this.setRowGroupActive.bind(this,!1),Wt.EVENT_COLUMN_ROW_GROUP_CHANGED,e)},i.prototype.removeRowGroupColumn=function(t,e){void 0===e&&(e="api"),t&&this.removeRowGroupColumns([t],e)},i.prototype.addPivotColumns=function(t,e){void 0===e&&(e="api"),this.updatePrimaryColumnList(t,this.pivotColumns,!0,(function(t){return t.setPivotActive(!0,e)}),Wt.EVENT_COLUMN_PIVOT_CHANGED,e)},i.prototype.setPivotColumns=function(t,e){void 0===e&&(e="api"),this.setPrimaryColumnList(t,this.pivotColumns,Wt.EVENT_COLUMN_PIVOT_CHANGED,(function(t,o){o.setPivotActive(t,e)}),e)},i.prototype.addPivotColumn=function(t,e){void 0===e&&(e="api"),this.addPivotColumns([t],e)},i.prototype.removePivotColumns=function(t,e){void 0===e&&(e="api"),this.updatePrimaryColumnList(t,this.pivotColumns,!1,(function(t){return t.setPivotActive(!1,e)}),Wt.EVENT_COLUMN_PIVOT_CHANGED,e)},i.prototype.removePivotColumn=function(t,e){void 0===e&&(e="api"),this.removePivotColumns([t],e)},i.prototype.setPrimaryColumnList=function(t,o,n,i,r){var s=this;o.length=0,e(t)&&t.forEach((function(t){var e=s.getPrimaryColumn(t);e&&o.push(e)})),this.primaryColumns.forEach((function(t){var e=o.indexOf(t)>=0;i(e,t)})),this.autoGroupsNeedBuilding&&this.updateGridColumns(),this.updateDisplayedColumns(r);var a={type:n,columns:o,column:1===o.length?o[0]:null,api:this.gridApi,columnApi:this.columnApi,source:r};this.eventService.dispatchEvent(a)},i.prototype.setValueColumns=function(t,e){void 0===e&&(e="api"),this.setPrimaryColumnList(t,this.valueColumns,Wt.EVENT_COLUMN_VALUE_CHANGED,this.setValueActive.bind(this),e)},i.prototype.setValueActive=function(t,e,o){if(t!==e.isValueActive()&&(e.setValueActive(t,o),t&&!e.getAggFunc())){var n=this.aggFuncService.getDefaultAggFunc(e);e.setAggFunc(n)}},i.prototype.addValueColumns=function(t,e){void 0===e&&(e="api"),this.updatePrimaryColumnList(t,this.valueColumns,!0,this.setValueActive.bind(this,!0),Wt.EVENT_COLUMN_VALUE_CHANGED,e)},i.prototype.addValueColumn=function(t,e){void 0===e&&(e="api"),t&&this.addValueColumns([t],e)},i.prototype.removeValueColumn=function(t,e){void 0===e&&(e="api"),this.removeValueColumns([t],e)},i.prototype.removeValueColumns=function(t,e){void 0===e&&(e="api"),this.updatePrimaryColumnList(t,this.valueColumns,!1,this.setValueActive.bind(this,!1),Wt.EVENT_COLUMN_VALUE_CHANGED,e)},i.prototype.normaliseColumnWidth=function(t,o){var n=t.getMinWidth();e(n)&&o<n&&(o=n);var i=t.getMaxWidth();return e(i)&&t.isGreaterThanMax(o)&&(o=i),o},i.prototype.getPrimaryOrGridColumn=function(t){return this.getPrimaryColumn(t)||this.getGridColumn(t)},i.prototype.setColumnWidths=function(t,e,o,n){var i=this;void 0===n&&(n="api");var r=[];t.forEach((function(t){var o=i.getPrimaryOrGridColumn(t.key);if(o&&(r.push({width:t.newWidth,ratios:[1],columns:[o]}),"shift"===i.gridOptionsWrapper.getColResizeDefault()&&(e=!e),e)){var n=i.getDisplayedColAfter(o);if(!n)return;var s=o.getActualWidth()-t.newWidth,a=n.getActualWidth()+s;r.push({width:a,ratios:[1],columns:[n]})}})),0!==r.length&&this.resizeColumnSets(r,o,n)},i.prototype.checkMinAndMaxWidthsForSet=function(t){var o=t.columns,n=t.width,i=0,r=0,s=!0;return o.forEach((function(t){var o=t.getMinWidth();i+=o||0;var n=t.getMaxWidth();e(n)&&n>0?r+=n:s=!1})),n>=i&&(!s||n<=r)},i.prototype.resizeColumnSets=function(t,o,n){if(!t||t.every(this.checkMinAndMaxWidthsForSet.bind(this))){var i=[],r=[];t.forEach((function(t){var o=t.width,s=t.columns,a=t.ratios,l={},p={};s.forEach((function(t){return r.push(t)}));for(var u=!0,c=0,d=function(){if(++c>1e3)return console.error("AG Grid: infinite loop in resizeColumnSets"),"break";u=!1;var t=[],n=0,i=o;s.forEach((function(e,o){if(p[e.getId()])i-=l[e.getId()];else{t.push(e);var r=a[o];n+=r}}));var r=1/n;t.forEach((function(n,s){var c;s===t.length-1?c=i:(c=Math.round(a[s]*o*r),i-=c);var d=n.getMinWidth(),h=n.getMaxWidth();e(d)&&c<d?(c=d,p[n.getId()]=!0,u=!0):e(h)&&h>0&&c>h&&(c=h,p[n.getId()]=!0,u=!0),l[n.getId()]=c}))};u;){if("break"===d())break}s.forEach((function(t){var e=l[t.getId()];t.getActualWidth()!==e&&(t.setActualWidth(e,n),i.push(t))}))}));var s=i.length>0,a=this.refreshFlexedColumns({resizingCols:r,skipSetLeft:!0});s&&(this.setLeftValues(n),this.updateBodyWidths(),this.checkViewportColumns());var l=r.concat(a);(s||o)&&this.fireColumnResizedEvent(l,o,n,a)}else if(o){var p=t&&t.length>0?t[0].columns:null;this.fireColumnResizedEvent(p,o,n)}},i.prototype.setColumnAggFunc=function(t,e,o){if(void 0===o&&(o="api"),t){var n=this.getPrimaryColumn(t);if(n){n.setAggFunc(e);var i={type:Wt.EVENT_COLUMN_VALUE_CHANGED,columns:[n],column:n,api:this.gridApi,columnApi:this.columnApi,source:o};this.eventService.dispatchEvent(i)}}},i.prototype.moveRowGroupColumn=function(t,e,o){void 0===o&&(o="api");var n=this.rowGroupColumns[t];this.rowGroupColumns.splice(t,1),this.rowGroupColumns.splice(e,0,n);var i={type:Wt.EVENT_COLUMN_ROW_GROUP_CHANGED,columns:this.rowGroupColumns,column:1===this.rowGroupColumns.length?this.rowGroupColumns[0]:null,api:this.gridApi,columnApi:this.columnApi,source:o};this.eventService.dispatchEvent(i)},i.prototype.moveColumns=function(t,e,o){if(void 0===o&&(o="api"),this.columnAnimationService.start(),e>this.gridColumns.length-t.length)return console.warn("AG Grid: tried to insert columns in invalid location, toIndex = "+e),void console.warn("AG Grid: remember that you should not count the moving columns when calculating the new index");var n=this.getGridColumns(t);if(!!this.doesMovePassRules(n,e)){m(this.gridColumns,n,e),this.updateDisplayedColumns(o);var i={type:Wt.EVENT_COLUMN_MOVED,columns:n,column:1===n.length?n[0]:null,toIndex:e,api:this.gridApi,columnApi:this.columnApi,source:o};this.eventService.dispatchEvent(i),this.columnAnimationService.finish()}},i.prototype.doesMovePassRules=function(t,e){var o=this.gridColumns.slice();return m(o,t,e),!!this.doesMovePassMarryChildren(o)&&!!this.doesMovePassLockedPositions(o)},i.prototype.sortColumnsLikeGridColumns=function(t){var e=this;!t||t.length<=1||(t.filter((function(t){return e.gridColumns.indexOf(t)<0})).length>0||t.sort((function(t,o){return e.gridColumns.indexOf(t)-e.gridColumns.indexOf(o)})))},i.prototype.doesMovePassLockedPositions=function(t){var e=!1,o=!0;return t.forEach((function(t){t.getColDef().lockPosition?e&&(o=!1):e=!0})),o},i.prototype.doesMovePassMarryChildren=function(t){var e=!0;return this.columnUtils.depthFirstOriginalTreeSearch(null,this.gridBalancedTree,(function(o){if(o instanceof Ct){var n=o,i=n.getColGroupDef();if(i&&i.marryChildren){var r=[];n.getLeafColumns().forEach((function(e){var o=t.indexOf(e);r.push(o)})),Math.max.apply(Math,r)-Math.min.apply(Math,r)>n.getLeafColumns().length-1&&(e=!1)}}})),e},i.prototype.moveColumn=function(t,e,o){void 0===o&&(o="api"),this.moveColumns([t],e,o)},i.prototype.moveColumnByIndex=function(t,e,o){void 0===o&&(o="api");var n=this.gridColumns[t];this.moveColumn(n,e,o)},i.prototype.getColumnDefs=function(){var t=this,e=this.primaryColumns.slice();return this.gridColsArePrimary?e.sort((function(e,o){return t.gridColumns.indexOf(e)-t.gridColumns.indexOf(o)})):this.lastPrimaryOrder&&e.sort((function(e,o){return t.lastPrimaryOrder.indexOf(e)-t.lastPrimaryOrder.indexOf(o)})),this.columnDefFactory.buildColumnDefs(e,this.rowGroupColumns,this.pivotColumns)},i.prototype.getBodyContainerWidth=function(){return this.bodyWidth},i.prototype.getContainerWidth=function(t){switch(t){case ht.PINNED_LEFT:return this.leftWidth;case ht.PINNED_RIGHT:return this.rightWidth;default:return this.bodyWidth}},i.prototype.updateBodyWidths=function(){var t=this.getWidthOfColsInList(this.displayedColumnsCenter),e=this.getWidthOfColsInList(this.displayedColumnsLeft),o=this.getWidthOfColsInList(this.displayedColumnsRight);if(this.bodyWidthDirty=this.bodyWidth!==t,this.bodyWidth!==t||this.leftWidth!==e||this.rightWidth!==o){this.bodyWidth=t,this.leftWidth=e,this.rightWidth=o;var n={type:Wt.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(n)}},i.prototype.getValueColumns=function(){return this.valueColumns?this.valueColumns:[]},i.prototype.getPivotColumns=function(){return this.pivotColumns?this.pivotColumns:[]},i.prototype.isPivotActive=function(){return this.pivotColumns&&this.pivotColumns.length>0&&this.pivotMode},i.prototype.getRowGroupColumns=function(){return this.rowGroupColumns?this.rowGroupColumns:[]},i.prototype.getDisplayedCenterColumns=function(){return this.displayedColumnsCenter},i.prototype.getDisplayedLeftColumns=function(){return this.displayedColumnsLeft},i.prototype.getDisplayedRightColumns=function(){return this.displayedColumnsRight},i.prototype.getDisplayedColumns=function(t){switch(t){case ht.PINNED_LEFT:return this.getDisplayedLeftColumns();case ht.PINNED_RIGHT:return this.getDisplayedRightColumns();default:return this.getDisplayedCenterColumns()}},i.prototype.getAllPrimaryColumns=function(){return this.primaryColumns?this.primaryColumns.slice():null},i.prototype.getSecondaryColumns=function(){return this.secondaryColumns?this.secondaryColumns.slice():null},i.prototype.getAllColumnsForQuickFilter=function(){return this.columnsForQuickFilter},i.prototype.getAllGridColumns=function(){return this.gridColumns},i.prototype.isEmpty=function(){return n(this.gridColumns)},i.prototype.isRowGroupEmpty=function(){return n(this.rowGroupColumns)},i.prototype.setColumnVisible=function(t,e,o){void 0===o&&(o="api"),this.setColumnsVisible([t],e,o)},i.prototype.setColumnsVisible=function(t,e,o){var n=this;void 0===e&&(e=!1),void 0===o&&(o="api"),this.columnAnimationService.start(),this.actionOnGridColumns(t,(function(t){return t.isVisible()!==e&&(t.setVisible(e,o),!0)}),o,(function(){return{type:Wt.EVENT_COLUMN_VISIBLE,visible:e,column:null,columns:null,api:n.gridApi,columnApi:n.columnApi,source:o}})),this.columnAnimationService.finish()},i.prototype.setColumnPinned=function(t,e,o){void 0===o&&(o="api"),t&&this.setColumnsPinned([t],e,o)},i.prototype.setColumnsPinned=function(t,e,o){var n,i=this;(void 0===o&&(o="api"),"print"!==this.gridOptionsWrapper.getDomLayout())?(this.columnAnimationService.start(),n=!0===e||e===ht.PINNED_LEFT?ht.PINNED_LEFT:e===ht.PINNED_RIGHT?ht.PINNED_RIGHT:null,this.actionOnGridColumns(t,(function(t){return t.getPinned()!==n&&(t.setPinned(n),!0)}),o,(function(){return{type:Wt.EVENT_COLUMN_PINNED,pinned:n,column:null,columns:null,api:i.gridApi,columnApi:i.columnApi,source:o}})),this.columnAnimationService.finish()):console.warn("Changing the column pinning status is not allowed with domLayout='print'")},i.prototype.actionOnGridColumns=function(t,o,i,r){var s=this;if(!n(t)){var a=[];if(t.forEach((function(t){var e=s.getGridColumn(t);e&&(!1!==o(e)&&a.push(e))})),a.length&&(this.updateDisplayedColumns(i),e(r)&&r)){var l=r();l.columns=a,l.column=1===a.length?a[0]:null,this.eventService.dispatchEvent(l)}}},i.prototype.getDisplayedColBefore=function(t){var e=this.getAllDisplayedColumns(),o=e.indexOf(t);return o>0?e[o-1]:null},i.prototype.getDisplayedColAfter=function(t){var e=this.getAllDisplayedColumns(),o=e.indexOf(t);return o<e.length-1?e[o+1]:null},i.prototype.getDisplayedGroupAfter=function(t){return this.getDisplayedGroupAtDirection(t,"After")},i.prototype.getDisplayedGroupBefore=function(t){return this.getDisplayedGroupAtDirection(t,"Before")},i.prototype.getDisplayedGroupAtDirection=function(t,e){for(var o=t.getOriginalColumnGroup().getLevel()+t.getPaddingLevel(),n=t.getDisplayedLeafColumns(),i="After"===e?d(n):n[0],r="getDisplayedCol"+e;;){var s=this[r](i);if(!s)return null;var a=this.getColumnGroupAtLevel(s,o);if(a!==t)return a}},i.prototype.getColumnGroupAtLevel=function(t,e){for(var o=t.getParent();;){if(o.getOriginalColumnGroup().getLevel()+o.getPaddingLevel()<=e)break;o=o.getParent()}return o},i.prototype.isPinningLeft=function(){return this.displayedColumnsLeft.length>0},i.prototype.isPinningRight=function(){return this.displayedColumnsRight.length>0},i.prototype.getPrimaryAndSecondaryAndAutoColumns=function(){var t=this.primaryColumns?this.primaryColumns.slice(0):[];return this.groupAutoColumns&&e(this.groupAutoColumns)&&this.groupAutoColumns.forEach((function(e){return t.push(e)})),this.secondaryColumnsPresent&&this.secondaryColumns&&this.secondaryColumns.forEach((function(e){return t.push(e)})),t},i.prototype.createStateItemFromColumn=function(t){var e=t.isRowGroupActive()?this.rowGroupColumns.indexOf(t):null,o=t.isPivotActive()?this.pivotColumns.indexOf(t):null,n=t.isValueActive()?t.getAggFunc():null,i=null!=t.getSort()?t.getSort():null,r=null!=t.getSortIndex()?t.getSortIndex():null,s=null!=t.getFlex()&&t.getFlex()>0?t.getFlex():null;return{colId:t.getColId(),width:t.getActualWidth(),hide:!t.isVisible(),pinned:t.getPinned(),sort:i,sortIndex:r,aggFunc:n,rowGroup:t.isRowGroupActive(),rowGroupIndex:e,pivot:t.isPivotActive(),pivotIndex:o,flex:s}},i.prototype.getColumnState=function(){if(o(this.primaryColumns)||!this.isAlive())return[];var t=this.primaryColumns.map(this.createStateItemFromColumn.bind(this)),e=(this.groupAutoColumns?this.groupAutoColumns.map(this.createStateItemFromColumn.bind(this)):[]).concat(t);return this.pivotMode||this.orderColumnStateList(e),e},i.prototype.orderColumnStateList=function(t){var e=new Map(this.gridColumns.map((function(t,e){return[t.getColId(),e]})));t.sort((function(t,o){return(e.has(t.colId)?e.get(t.colId):-1)-(e.has(o.colId)?e.get(o.colId):-1)}))},i.prototype.resetColumnState=function(t){void 0===t&&(t="api");var e=this.getColumnsFromTree(this.primaryColumnTree),n=[],i=1e3,r=1e3,s=[];this.groupAutoColumns&&(s=s.concat(this.groupAutoColumns)),e&&(s=s.concat(e)),s.forEach((function(t){var e=t.getColDef(),s=null!=e.sort?e.sort:null,a=e.sortIndex,l=!!e.hide,p=e.pinned?e.pinned:null,u=e.width,c=null!=e.flex?e.flex:null,d=e.rowGroupIndex,h=e.rowGroup;null!=d||null!=h&&0!=h||(d=null,h=null);var f=e.pivotIndex,g=e.pivot;null!=f||null!=g&&0!=g||(f=null,g=null);var y=null!=e.aggFunc?e.aggFunc:null,v={colId:t.getColId(),sort:s,sortIndex:a,hide:l,pinned:p,width:u,flex:c,rowGroup:h,rowGroupIndex:d,pivot:g,pivotIndex:f,aggFunc:y};o(d)&&h&&(v.rowGroupIndex=i++),o(f)&&g&&(v.pivotIndex=r++),n.push(v)})),this.applyColumnState({state:n,applyOrder:!0},t)},i.prototype.applyColumnState=function(t,e){var o=this;if(void 0===e&&(e="api"),n(this.primaryColumns))return!1;if(t&&t.state&&!t.state.forEach)return console.warn("AG Grid: applyColumnState() - the state attribute should be an array, however an array was not found. Please provide an array of items (one for each col you want to change) for state."),!1;this.columnAnimationService.start();var i=this.compareColumnStatesAndRaiseEvents(e);this.autoGroupsNeedBuilding=!0;var r=this.primaryColumns.slice(),s=!0,a={},l={},p=[],u=this.rowGroupColumns.slice(),c=this.pivotColumns.slice();t.state&&t.state.forEach((function(n){var i=ht.GROUP_AUTO_COLUMN_ID,u=n.colId||"";if(qt(u,i))p.push(n);else{var c=o.getPrimaryColumn(u);c?(o.syncColumnWithStateItem(c,n,t.defaultState,a,l,!1,e),g(r,c)):s=!1}})),r.forEach((function(n){o.syncColumnWithStateItem(n,null,t.defaultState,a,l,!1,e)}));var d=function(t,e,o,n){var i=t[o.getId()],r=t[n.getId()],s=null!=i,a=null!=r;if(s&&a)return i-r;if(s)return-1;if(a)return 1;var l=e.indexOf(o),p=e.indexOf(n),u=l>=0;return u&&p>=0?l-p:u?-1:1};return this.rowGroupColumns.sort(d.bind(this,a,u)),this.pivotColumns.sort(d.bind(this,l,c)),this.updateGridColumns(),p.forEach((function(n){var i=o.getAutoColumn(n.colId);o.syncColumnWithStateItem(i,n,t.defaultState,null,null,!0,e)})),this.applyOrderAfterApplyState(t),this.updateDisplayedColumns(e),this.dispatchEverythingChanged(e),i(),this.columnAnimationService.finish(),s},i.prototype.applyOrderAfterApplyState=function(t){var e=this;if(this.gridColsArePrimary&&t.applyOrder&&t.state){var o=[],n={};t.state.forEach((function(t){if(t.colId&&!n[t.colId]){var i=e.primaryColumnsMap[t.colId];i&&(o.push(i),n[t.colId]=!0)}})),this.gridColumns.forEach((function(t){n[t.getColId()]||o.push(t)})),o=this.putFixedColumnsFirst(o),this.doesMovePassMarryChildren(o)?this.gridColumns=o:console.warn("AG Grid: Applying column order broke a group where columns should be married together. Applying new order has been discarded.")}},i.prototype.compareColumnStatesAndRaiseEvents=function(t){var e=this;if(!!!this.columnDefs)return function(){};var o={rowGroupColumns:this.rowGroupColumns.slice(),pivotColumns:this.pivotColumns.slice(),valueColumns:this.valueColumns.slice()},n=this.getColumnState(),i={};return n.forEach((function(t){i[t.colId]=t})),function(){if(!e.gridOptionsWrapper.isSuppressColumnStateEvents()){var r=function(o,n,i,r){if(!h(n.map(r).sort(),i.map(r).sort())){var s={type:o,columns:i,column:1===i.length?i[0]:null,api:e.gridApi,columnApi:e.columnApi,source:t};e.eventService.dispatchEvent(s)}},s=function(t){var o=[];return e.gridColumns.forEach((function(e){var n=i[e.getColId()];n&&t(n,e)&&o.push(e)})),o},a=function(t){return t.getColId()};r(Wt.EVENT_COLUMN_ROW_GROUP_CHANGED,o.rowGroupColumns,e.rowGroupColumns,a),r(Wt.EVENT_COLUMN_PIVOT_CHANGED,o.pivotColumns,e.pivotColumns,a),r(Wt.EVENT_COLUMN_VALUE_CHANGED,o.valueColumns,e.valueColumns,a);e.fireColumnResizedEvent(s((function(t,e){return t.width!=e.getActualWidth()})),!0,t);e.raiseColumnPinnedEvent(s((function(t,e){return t.pinned!=e.getPinned()})),t);e.raiseColumnVisibleEvent(s((function(t,e){return t.hide==e.isVisible()})),t);s((function(t,e){return t.sort!=e.getSort()||t.sortIndex!=e.getSortIndex()})).length>0&&e.sortController.dispatchSortChangedEvents(),e.raiseColumnMovedEvent(n,t)}}},i.prototype.raiseColumnPinnedEvent=function(t,e){if(t.length){var o={type:Wt.EVENT_COLUMN_PINNED,pinned:null,columns:t,column:null,api:this.gridApi,columnApi:this.columnApi,source:e};this.eventService.dispatchEvent(o)}},i.prototype.raiseColumnVisibleEvent=function(t,e){if(t.length){var o={type:Wt.EVENT_COLUMN_VISIBLE,visible:void 0,columns:t,column:null,api:this.gridApi,columnApi:this.columnApi,source:e};this.eventService.dispatchEvent(o)}},i.prototype.raiseColumnMovedEvent=function(t,e){var o=this,n=this.getColumnState(),i={};n.forEach((function(t){return i[t.colId]=t}));var r={};t.forEach((function(t){i[t.colId]&&(r[t.colId]=!0)}));var s=b(t,(function(t){return r[t.colId]})),a=b(n,(function(t){return r[t.colId]})),l=[];if(a.forEach((function(t,e){var n=s&&s[e];if(n&&n.colId!==t.colId){var i=o.getGridColumn(n.colId);i&&l.push(i)}})),l.length){var p={type:Wt.EVENT_COLUMN_MOVED,columns:l,column:null,api:this.gridApi,columnApi:this.columnApi,source:e};this.eventService.dispatchEvent(p)}},i.prototype.syncColumnWithStateItem=function(t,o,n,i,r,s,a){if(t){var l=function(t,i){var r=o,s=n,a={value1:void 0,value2:void 0},l=!1;return r&&(void 0!==r[t]&&(a.value1=r[t],l=!0),e(i)&&void 0!==r[i]&&(a.value2=r[i],l=!0)),!l&&s&&(void 0!==s[t]&&(a.value1=s[t]),e(i)&&void 0!==s[i]&&(a.value2=s[i])),a},p=l("hide").value1;void 0!==p&&t.setVisible(!p,a);var u=l("pinned").value1;void 0!==u&&t.setPinned(u);var c=this.gridOptionsWrapper.getMinColWidth(),d=l("flex").value1;if(void 0!==d&&t.setFlex(d),t.getFlex()<=0){var h=l("width").value1;null!=h&&c&&h>=c&&t.setActualWidth(h,a)}var f=l("sort").value1;void 0!==f&&(f===ht.SORT_DESC||f===ht.SORT_ASC?t.setSort(f):t.setSort(void 0));var y=l("sortIndex").value1;if(void 0!==y&&t.setSortIndex(y),!s){var v=l("aggFunc").value1;void 0!==v&&("string"==typeof v?(t.setAggFunc(v),t.isValueActive()||(t.setValueActive(!0,a),this.valueColumns.push(t))):(e(v)&&console.warn("AG Grid: stateItem.aggFunc must be a string. if using your own aggregation functions, register the functions first before using them in get/set state. This is because it is intended for the column state to be stored and retrieved as simple JSON."),t.setAggFunc(null),t.isValueActive()&&(t.setValueActive(!1,a),g(this.valueColumns,t))));var m=l("rowGroup","rowGroupIndex"),C=m.value1,w=m.value2;void 0===C&&void 0===w||("number"==typeof w||C?(t.isRowGroupActive()||(t.setRowGroupActive(!0,a),this.rowGroupColumns.push(t)),i&&"number"==typeof w&&(i[t.getId()]=w)):t.isRowGroupActive()&&(t.setRowGroupActive(!1,a),g(this.rowGroupColumns,t)));var E=l("pivot","pivotIndex"),R=E.value1,O=E.value2;void 0===R&&void 0===O||("number"==typeof O||R?(t.isPivotActive()||(t.setPivotActive(!0,a),this.pivotColumns.push(t)),r&&"number"==typeof O&&(r[t.getId()]=O)):t.isPivotActive()&&(t.setPivotActive(!1,a),g(this.pivotColumns,t)))}}},i.prototype.getGridColumns=function(t){return this.getColumns(t,this.getGridColumn.bind(this))},i.prototype.getColumns=function(t,e){var o=[];return t&&t.forEach((function(t){var n=e(t);n&&o.push(n)})),o},i.prototype.getColumnWithValidation=function(t){if(null==t)return null;var e=this.getGridColumn(t);return e||console.warn("AG Grid: could not find column "+t),e},i.prototype.getPrimaryColumn=function(t){return this.getColumn(t,this.primaryColumns,this.primaryColumnsMap)},i.prototype.getGridColumn=function(t){return this.getColumn(t,this.gridColumns,this.gridColumnsMap)},i.prototype.getColumn=function(t,e,o){if(!t)return null;if("string"==typeof t&&o[t])return o[t];for(var n=0;n<e.length;n++)if(this.columnsMatch(e[n],t))return e[n];return this.getAutoColumn(t)},i.prototype.getAutoColumn=function(t){var n=this;return this.groupAutoColumns&&e(this.groupAutoColumns)&&!o(this.groupAutoColumns)?a(this.groupAutoColumns,(function(e){return n.columnsMatch(e,t)})):null},i.prototype.columnsMatch=function(t,e){var o=t===e,n=t.getColDef()===e,i=t.getColId()==e;return o||n||i},i.prototype.getDisplayNameForColumn=function(t,e,o){if(void 0===o&&(o=!1),!t)return null;var n=this.getHeaderName(t.getColDef(),t,null,null,e);return o?this.wrapHeaderNameWithAggFunc(t,n):n},i.prototype.getDisplayNameForOriginalColumnGroup=function(t,e,o){var n=e?e.getColGroupDef():null;return n?this.getHeaderName(n,null,t,e,o):null},i.prototype.getDisplayNameForColumnGroup=function(t,e){return this.getDisplayNameForOriginalColumnGroup(t,t.getOriginalColumnGroup(),e)},i.prototype.getHeaderName=function(t,e,o,n,i){var r=t.headerValueGetter;if(r){var s={colDef:t,column:e,columnGroup:o,originalColumnGroup:n,location:i,api:this.gridOptionsWrapper.getApi(),context:this.gridOptionsWrapper.getContext()};return"function"==typeof r?r(s):"string"==typeof r?this.expressionService.evaluate(r,s):(console.warn("ag-grid: headerValueGetter must be a function or a string"),"")}return null!=t.headerName?t.headerName:t.field?Yt(t.field):""},i.prototype.wrapHeaderNameWithAggFunc=function(t,o){if(this.gridOptionsWrapper.isSuppressAggFuncInHeader())return o;var n,i=t.getColDef().pivotValueColumn,r=null;if(e(i))r=i?i.getAggFunc():null,n=!0;else{var s=t.isValueActive(),a=this.pivotMode||!this.isRowGroupEmpty();s&&a?(r=t.getAggFunc(),n=!0):n=!1}if(n){var l="string"==typeof r?r:"func";return this.gridOptionsWrapper.getLocaleTextFunc()(l,l)+"("+o+")"}return o},i.prototype.getColumnGroup=function(t,e){if(!t)return null;if(t instanceof mt)return t;var o=this.getAllDisplayedTrees(),n="number"==typeof e,i=null;return this.columnUtils.depthFirstAllColumnTreeSearch(o,(function(o){if(o instanceof mt){var r=o;(n?t===r.getGroupId()&&e===r.getInstanceId():t===r.getGroupId())&&(i=r)}})),i},i.prototype.isReady=function(){return this.ready},i.prototype.extractValueColumns=function(t,e){this.valueColumns=this.extractColumns(e,this.valueColumns,(function(e,o){return e.setValueActive(o,t)}),(function(){}),(function(){}),(function(t){var e=t.aggFunc;return null===e||""===e?null:void 0!==e?!!e:void 0}),(function(t){return null!=t.initialAggFunc&&""!=t.initialAggFunc})),this.valueColumns.forEach((function(t){var e=t.getColDef();null!=e.aggFunc&&""!=e.aggFunc?t.setAggFunc(e.aggFunc):t.getAggFunc()||t.setAggFunc(e.initialAggFunc)}))},i.prototype.extractRowGroupColumns=function(t,e){this.rowGroupColumns=this.extractColumns(e,this.rowGroupColumns,(function(e,o){return e.setRowGroupActive(o,t)}),(function(t){return t.rowGroupIndex}),(function(t){return t.initialRowGroupIndex}),(function(t){return t.rowGroup}),(function(t){return t.initialRowGroup}))},i.prototype.extractColumns=function(t,e,o,n,i,a,l){void 0===t&&(t=[]),void 0===e&&(e=[]);var p=[],u=[];this.primaryColumns.forEach((function(o){var c,d=t.indexOf(o)<0,h=o.getColDef(),f=s(a(h)),g=s(l(h)),y=r(n(h)),v=r(i(h));d?c=void 0!==f||void 0!==y?void 0!==f?f:y>=0:g||v>=0:c=void 0!==f?f:void 0!==y?null!==y&&y>=0:e.indexOf(o)>=0;c&&((d?null!=y||null!=v:null!=y)?p.push(o):u.push(o))}));var c=function(t){var e=n(t.getColDef()),o=i(t.getColDef());return null!=e?e:o};p.sort((function(t,e){var o=c(t),n=c(e);return o===n?0:o<n?-1:1}));var d=[].concat(p);return e.forEach((function(t){u.indexOf(t)>=0&&d.push(t)})),u.forEach((function(t){d.indexOf(t)<0&&d.push(t)})),e.forEach((function(t){d.indexOf(t)<0&&o(t,!1)})),d.forEach((function(t){e.indexOf(t)<0&&o(t,!0)})),d},i.prototype.extractPivotColumns=function(t,e){this.pivotColumns=this.extractColumns(e,this.pivotColumns,(function(e,o){return e.setPivotActive(o,t)}),(function(t){return t.pivotIndex}),(function(t){return t.initialPivotIndex}),(function(t){return t.pivot}),(function(t){return t.initialPivot}))},i.prototype.resetColumnGroupState=function(t){void 0===t&&(t="api");var e=[];this.columnUtils.depthFirstOriginalTreeSearch(null,this.primaryColumnTree,(function(t){if(t instanceof Ct){var o=t.getColGroupDef(),n={groupId:t.getGroupId(),open:o?o.openByDefault:void 0};e.push(n)}})),this.setColumnGroupState(e,t)},i.prototype.getColumnGroupState=function(){var t=[];return this.columnUtils.depthFirstOriginalTreeSearch(null,this.gridBalancedTree,(function(e){if(e instanceof Ct){var o=e;t.push({groupId:o.getGroupId(),open:o.isExpanded()})}})),t},i.prototype.setColumnGroupState=function(t,e){var o=this;void 0===e&&(e="api"),this.columnAnimationService.start();var n=[];t.forEach((function(t){var e=t.groupId,i=t.open,r=o.getOriginalColumnGroup(e);r&&r.isExpanded()!==i&&(o.logger.log("columnGroupOpened("+r.getGroupId()+","+i+")"),r.setExpanded(i),n.push(r))})),this.updateGroupsAndDisplayedColumns(e),this.setFirstRightAndLastLeftPinned(e),n.forEach((function(t){var e={type:Wt.EVENT_COLUMN_GROUP_OPENED,columnGroup:t,api:o.gridApi,columnApi:o.columnApi};o.eventService.dispatchEvent(e)})),this.columnAnimationService.finish()},i.prototype.setColumnGroupOpened=function(t,e,o){var n;void 0===o&&(o="api"),n=t instanceof Ct?t.getId():t||"",this.setColumnGroupState([{groupId:n,open:e}],o)},i.prototype.getOriginalColumnGroup=function(t){if(t instanceof Ct)return t;"string"!=typeof t&&console.error("AG Grid: group key must be a string");var e=null;return this.columnUtils.depthFirstOriginalTreeSearch(null,this.gridBalancedTree,(function(o){if(o instanceof Ct){var n=o;n.getId()===t&&(e=n)}})),e},i.prototype.calculateColumnsForDisplay=function(){var t=this;return this.pivotMode&&!this.secondaryColumnsPresent?this.gridColumns.filter((function(e){var o=t.groupAutoColumns&&C(t.groupAutoColumns,e),n=t.valueColumns&&C(t.valueColumns,e);return o||n})):this.gridColumns.filter((function(e){return t.groupAutoColumns&&C(t.groupAutoColumns,e)||e.isVisible()}))},i.prototype.checkColSpanActiveInCols=function(t){var o=!1;return t.forEach((function(t){e(t.getColDef().colSpan)&&(o=!0)})),o},i.prototype.calculateColumnsForGroupDisplay=function(){var t=this;this.groupDisplayColumns=[];var o=function(o){var n=o.getColDef();n&&e(n.showRowGroup)&&t.groupDisplayColumns.push(o)};this.gridColumns.forEach(o),this.groupAutoColumns&&this.groupAutoColumns.forEach(o)},i.prototype.getGroupDisplayColumns=function(){return this.groupDisplayColumns},i.prototype.updateDisplayedColumns=function(t){var e=this.calculateColumnsForDisplay();this.buildDisplayedTrees(e),this.calculateColumnsForGroupDisplay(),this.updateGroupsAndDisplayedColumns(t),this.setFirstRightAndLastLeftPinned(t)},i.prototype.isSecondaryColumnsPresent=function(){return this.secondaryColumnsPresent},i.prototype.setSecondaryColumns=function(t,e){void 0===e&&(e="api");var o=t&&t.length>0;if(o||this.secondaryColumnsPresent){if(o){this.processSecondaryColumnDefinitions(t);var n=this.columnFactory.createColumnTree(t,!1);this.secondaryBalancedTree=n.columnTree,this.secondaryHeaderRowCount=n.treeDept+1,this.secondaryColumns=this.getColumnsFromTree(this.secondaryBalancedTree),this.secondaryColumnsPresent=!0}else this.secondaryBalancedTree=null,this.secondaryHeaderRowCount=-1,this.secondaryColumns=null,this.secondaryColumnsPresent=!1;this.updateGridColumns(),this.updateDisplayedColumns(e)}},i.prototype.processSecondaryColumnDefinitions=function(t){var o=this.gridOptionsWrapper.getProcessSecondaryColDefFunc(),n=this.gridOptionsWrapper.getProcessSecondaryColGroupDefFunc();if(o||n){var i=function(t){t.forEach((function(t){if(e(t.children)){var r=t;n&&n(r),i(r.children)}else{o&&o(t)}}))};t&&i(t)}},i.prototype.updateGridColumns=function(){var t=this;this.gridColsArePrimary&&(this.lastPrimaryOrder=this.gridColumns),this.secondaryColumns&&this.secondaryBalancedTree?(this.gridBalancedTree=this.secondaryBalancedTree.slice(),this.gridHeaderRowCount=this.secondaryHeaderRowCount,this.gridColumns=this.secondaryColumns.slice(),this.gridColsArePrimary=!1):(this.gridBalancedTree=this.primaryColumnTree.slice(),this.gridHeaderRowCount=this.primaryHeaderRowCount,this.gridColumns=this.primaryColumns.slice(),this.gridColsArePrimary=!0,this.orderGridColsLikeLastPrimary()),this.addAutoGroupToGridColumns(),this.autoRowHeightColumns=this.gridColumns.filter((function(t){return t.getColDef().autoHeight})),this.gridColumns=this.putFixedColumnsFirst(this.gridColumns),this.setupQuickFilterColumns(),this.clearDisplayedAndViewportColumns(),this.colSpanActive=this.checkColSpanActiveInCols(this.gridColumns),this.gridColumnsMap={},this.gridColumns.forEach((function(e){return t.gridColumnsMap[e.getId()]=e}));var e={type:Wt.EVENT_GRID_COLUMNS_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(e)},i.prototype.orderGridColsLikeLastPrimary=function(){if(!o(this.lastPrimaryOrder)){var t=new Map(this.lastPrimaryOrder.map((function(t,e){return[t,e]}))),e=!0;if(this.gridColumns.forEach((function(o){t.has(o)&&(e=!1)})),!e){var n=new Map(this.gridColumns.map((function(t){return[t,!0]}))),i=this.lastPrimaryOrder.filter((function(t){return n.has(t)})),r=new Map(i.map((function(t){return[t,!0]}))),s=this.gridColumns.filter((function(t){return!r.has(t)})),a=i.slice();s.forEach((function(t){var e=t.getOriginalParent();if(e){for(var o=[];!o.length&&e;){e.getLeafColumns().forEach((function(t){var e=a.indexOf(t)>=0,n=o.indexOf(t)<0;e&&n&&o.push(t)})),e=e.getOriginalParent()}if(o.length){var n=o.map((function(t){return a.indexOf(t)})),i=Math.max.apply(Math,n);v(a,t,i+1)}else a.push(t)}else a.push(t)})),this.gridColumns=a}}},i.prototype.isPrimaryColumnGroupsPresent=function(){return this.primaryHeaderRowCount>1},i.prototype.setupQuickFilterColumns=function(){this.groupAutoColumns?this.columnsForQuickFilter=this.primaryColumns.concat(this.groupAutoColumns):this.columnsForQuickFilter=this.primaryColumns},i.prototype.putFixedColumnsFirst=function(t){var e=t.filter((function(t){return t.getColDef().lockPosition})),o=t.filter((function(t){return!t.getColDef().lockPosition}));return e.concat(o)},i.prototype.addAutoGroupToGridColumns=function(){if(this.createGroupAutoColumnsIfNeeded(),!o(this.groupAutoColumns)){this.gridColumns=this.groupAutoColumns?this.groupAutoColumns.concat(this.gridColumns):this.gridColumns;var t=this.columnFactory.createForAutoGroups(this.groupAutoColumns,this.gridBalancedTree);this.gridBalancedTree=t.concat(this.gridBalancedTree)}},i.prototype.clearDisplayedAndViewportColumns=function(){this.displayedTreeLeft=[],this.displayedTreeRight=[],this.displayedTreeCentre=[],this.viewportRowLeft={},this.viewportRowRight={},this.viewportRowCenter={},this.displayedColumnsLeft=[],this.displayedColumnsRight=[],this.displayedColumnsCenter=[],this.displayedColumns=[],this.viewportColumns=[]},i.prototype.updateGroupsAndDisplayedColumns=function(t){this.updateOpenClosedVisibilityInColumnGroups(),this.deriveDisplayedColumns(t),this.refreshFlexedColumns(),this.extractViewport(),this.updateBodyWidths();var e={type:Wt.EVENT_DISPLAYED_COLUMNS_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(e)},i.prototype.deriveDisplayedColumns=function(t){this.derivedDisplayedColumnsFromDisplayedTree(this.displayedTreeLeft,this.displayedColumnsLeft),this.derivedDisplayedColumnsFromDisplayedTree(this.displayedTreeCentre,this.displayedColumnsCenter),this.derivedDisplayedColumnsFromDisplayedTree(this.displayedTreeRight,this.displayedColumnsRight),this.joinDisplayedColumns(),this.setLeftValues(t)},i.prototype.joinDisplayedColumns=function(){this.gridOptionsWrapper.isEnableRtl()?this.displayedColumns=this.displayedColumnsRight.concat(this.displayedColumnsCenter).concat(this.displayedColumnsLeft):this.displayedColumns=this.displayedColumnsLeft.concat(this.displayedColumnsCenter).concat(this.displayedColumnsRight)},i.prototype.setLeftValues=function(t){this.setLeftValuesOfColumns(t),this.setLeftValuesOfGroups()},i.prototype.setLeftValuesOfColumns=function(t){var e=this,o=this.primaryColumns.slice(0),n=this.gridOptionsWrapper.isEnableRtl();[this.displayedColumnsLeft,this.displayedColumnsRight,this.displayedColumnsCenter].forEach((function(i){if(n){var r=e.getWidthOfColsInList(i);i.forEach((function(e){r-=e.getActualWidth(),e.setLeft(r,t)}))}else{var s=0;i.forEach((function(e){e.setLeft(s,t),s+=e.getActualWidth()}))}y(o,i)})),o.forEach((function(e){e.setLeft(null,t)}))},i.prototype.setLeftValuesOfGroups=function(){[this.displayedTreeLeft,this.displayedTreeRight,this.displayedTreeCentre].forEach((function(t){t.forEach((function(t){t instanceof mt&&t.checkLeft()}))}))},i.prototype.derivedDisplayedColumnsFromDisplayedTree=function(t,e){e.length=0,this.columnUtils.depthFirstDisplayedColumnTreeSearch(t,(function(t){t instanceof yt&&e.push(t)}))},i.prototype.extractViewportColumns=function(){this.suppressColumnVirtualisation?this.viewportColumnsCenter=this.displayedColumnsCenter:this.viewportColumnsCenter=this.filterOutColumnsWithinViewport(),this.viewportColumns=this.viewportColumnsCenter.concat(this.displayedColumnsLeft).concat(this.displayedColumnsRight)},i.prototype.getVirtualHeaderGroupRow=function(t,e){var n;switch(t){case ht.PINNED_LEFT:n=this.viewportRowLeft[e];break;case ht.PINNED_RIGHT:n=this.viewportRowRight[e];break;default:n=this.viewportRowCenter[e]}return o(n)&&(n=[]),n},i.prototype.extractViewportRows=function(){this.viewportRowLeft={},this.viewportRowRight={},this.viewportRowCenter={};var t={};this.viewportColumns.forEach((function(e){return t[e.getId()]=!0}));var e=function(o,n,i){for(var r=!1,s=0;s<o.length;s++){var a=o[s],l=!1;if(a instanceof yt)l=!0===t[a.getId()];else{var p=a.getDisplayedChildren();p&&(l=e(p,n,i+1))}l&&(r=!0,n[i]||(n[i]=[]),n[i].push(a))}return r};e(this.displayedTreeLeft,this.viewportRowLeft,0),e(this.displayedTreeRight,this.viewportRowRight,0),e(this.displayedTreeCentre,this.viewportRowCenter,0)},i.prototype.extractViewport=function(){this.extractViewportColumns(),this.extractViewportRows()},i.prototype.filterOutColumnsWithinViewport=function(){return this.displayedColumnsCenter.filter(this.isColumnInViewport.bind(this))},i.prototype.refreshFlexedColumns=function(t){var o=this;void 0===t&&(t={});var n=t.source?t.source:"flex";if(null!=t.viewportWidth&&(this.flexViewportWidth=t.viewportWidth),!this.flexViewportWidth)return[];var i=-1;t.resizingCols&&t.resizingCols.forEach((function(t){var e=o.displayedColumnsCenter.indexOf(t);i<e&&(i=e)}));var r=function(t){var e=o.displayedColumnsCenter.indexOf(t)>i;return t.getFlex()&&e},s=this.displayedColumnsCenter.filter((function(t){return!r(t)})),a=this.displayedColumnsCenter.filter((function(t){return r(t)})),l=[];if(!a.length)return[];var p,u=[];t:for(;;){var c=a.reduce((function(t,e){return t+e.getFlex()}),0);p=this.flexViewportWidth-this.getWidthOfColsInList(s);for(var d=0;d<a.length;d++){var h=a[d],f=p*h.getFlex()/c,y=0,v=h.getMinWidth(),m=h.getMaxWidth();if(e(v)&&f<v?y=v:e(m)&&f>m&&(y=m),y){h.setActualWidth(y,n),g(a,h),l.push(h),s.push(h);continue t}u[d]=Math.round(f)}break}var C=p;return a.forEach((function(t,e){t.setActualWidth(Math.min(u[e],C),n),l.push(t),C-=u[e]})),t.skipSetLeft||this.setLeftValues(n),t.updateBodyWidths&&this.updateBodyWidths(),t.fireResizedEvent&&this.fireColumnResizedEvent(l,!0,n,a),this.flexColsCalculatedAtLestOnce||(this.gridOptionsWrapper.isRowModelDefault()&&this.rowModel.resetRowHeights(),this.flexColsCalculatedAtLestOnce=!0),a},i.prototype.sizeColumnsToFit=function(t,o,n){void 0===o&&(o="sizeColumnsToFit");var i=this.getAllDisplayedColumns();if(!(t<=0)&&i.length){var r=[],s=[];i.forEach((function(t){!0===t.getColDef().suppressSizeToFit?s.push(t):r.push(t)}));var a=r.slice(0),l=!1,p=function(t){g(r,t),s.push(t)};for(r.forEach((function(t){return t.resetActualWidth(o)}));!l;){l=!0;var u=t-this.getWidthOfColsInList(s);if(u<=0)r.forEach((function(t){t.setMinimum(o)}));else for(var c=u/this.getWidthOfColsInList(r),d=u,h=r.length-1;h>=0;h--){var f=r[h],y=f.getMinWidth(),v=f.getMaxWidth(),m=Math.round(f.getActualWidth()*c);e(y)&&m<y?(m=y,p(f),l=!1):e(v)&&f.isGreaterThanMax(m)?(m=v,p(f),l=!1):0===h&&(m=d),f.setActualWidth(m,o,!0),d-=m}}a.forEach((function(t){t.fireColumnWidthChangedEvent(o)})),this.setLeftValues(o),this.updateBodyWidths(),n||this.fireColumnResizedEvent(a,!0,o)}},i.prototype.buildDisplayedTrees=function(t){var e=[],o=[],n=[];t.forEach((function(t){switch(t.getPinned()){case"left":e.push(t);break;case"right":o.push(t);break;default:n.push(t)}}));var i=new kt;this.displayedTreeLeft=this.displayedGroupCreator.createDisplayedGroups(e,this.gridBalancedTree,i,ht.PINNED_LEFT,this.displayedTreeLeft),this.displayedTreeRight=this.displayedGroupCreator.createDisplayedGroups(o,this.gridBalancedTree,i,ht.PINNED_RIGHT,this.displayedTreeRight),this.displayedTreeCentre=this.displayedGroupCreator.createDisplayedGroups(n,this.gridBalancedTree,i,null,this.displayedTreeCentre),this.updateDisplayedMap()},i.prototype.updateDisplayedMap=function(){var t=this;this.displayedColumnsAndGroupsMap={};var e=function(e){t.displayedColumnsAndGroupsMap[e.getUniqueId()]=e};this.columnUtils.depthFirstAllColumnTreeSearch(this.displayedTreeCentre,e),this.columnUtils.depthFirstAllColumnTreeSearch(this.displayedTreeLeft,e),this.columnUtils.depthFirstAllColumnTreeSearch(this.displayedTreeRight,e)},i.prototype.isDisplayed=function(t){return this.displayedColumnsAndGroupsMap[t.getUniqueId()]===t},i.prototype.updateOpenClosedVisibilityInColumnGroups=function(){var t=this.getAllDisplayedTrees();this.columnUtils.depthFirstAllColumnTreeSearch(t,(function(t){t instanceof mt&&t.calculateDisplayedColumns()}))},i.prototype.getGroupAutoColumns=function(){return this.groupAutoColumns},i.prototype.createGroupAutoColumnsIfNeeded=function(){if(this.autoGroupsNeedBuilding){this.autoGroupsNeedBuilding=!1;var t=this.gridOptionsWrapper.isGroupUseEntireRow(this.pivotMode),e=this.pivotMode?this.gridOptionsWrapper.isPivotSuppressAutoColumn():this.gridOptionsWrapper.isGroupSuppressAutoColumn();if((this.rowGroupColumns.length>0||this.usingTreeData)&&!e&&!t){var o=this.autoGroupColService.createAutoGroupColumns(this.rowGroupColumns);(!this.autoColsEqual(o,this.groupAutoColumns)||this.forceRecreateAutoGroups)&&(this.groupAutoColumns=o)}else this.groupAutoColumns=null}},i.prototype.autoColsEqual=function(t,e){return h(t,e,(function(t,e){return t.getColId()===e.getColId()}))},i.prototype.getWidthOfColsInList=function(t){return t.reduce((function(t,e){return t+e.getActualWidth()}),0)},i.prototype.getGridBalancedTree=function(){return this.gridBalancedTree},i.prototype.hasFloatingFilters=function(){var t=this.gridOptionsWrapper.getDefaultColDef();return null!=t&&!0===t.floatingFilter||null!=this.columnDefs&&this.columnDefs.some((function(t){return!0===t.floatingFilter}))},i.prototype.getFirstDisplayedColumn=function(){var t=this.gridOptionsWrapper.isEnableRtl(),e=["getDisplayedLeftColumns","getDisplayedCenterColumns","getDisplayedRightColumns"];t&&e.reverse();for(var o=0;o<e.length;o++){var n=this[e[o]]();if(n.length)return t?d(n):n[0]}return null},$t([it("expressionService")],i.prototype,"expressionService",void 0),$t([it("columnFactory")],i.prototype,"columnFactory",void 0),$t([it("displayedGroupCreator")],i.prototype,"displayedGroupCreator",void 0),$t([it("autoWidthCalculator")],i.prototype,"autoWidthCalculator",void 0),$t([it("columnUtils")],i.prototype,"columnUtils",void 0),$t([it("columnAnimationService")],i.prototype,"columnAnimationService",void 0),$t([it("autoGroupColService")],i.prototype,"autoGroupColService",void 0),$t([rt("aggFuncService")],i.prototype,"aggFuncService",void 0),$t([rt("valueCache")],i.prototype,"valueCache",void 0),$t([rt("animationFrameService")],i.prototype,"animationFrameService",void 0),$t([it("rowModel")],i.prototype,"rowModel",void 0),$t([it("columnApi")],i.prototype,"columnApi",void 0),$t([it("gridApi")],i.prototype,"gridApi",void 0),$t([it("sortController")],i.prototype,"sortController",void 0),$t([it("columnDefFactory")],i.prototype,"columnDefFactory",void 0),$t([et],i.prototype,"init",null),$t([Zt(0,at("loggerFactory"))],i.prototype,"setBeans",null),i=$t([nt("columnController")],i)}(Mt);
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
function Jt(t,e){for(var o=""+t;o.length<e;)o="0"+o;return o}function te(t,e){for(var o=[],n=t;n<=e;n++)o.push(n);return o}function ee(t){return""!==t&&!isNaN(parseFloat(t))&&isFinite(t)}function oe(){return Number.MAX_SAFE_INTEGER||9007199254740991}function ne(t){return"number"!=typeof t?"":t.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1,")}var ie=Object.freeze({__proto__:null,padStart:Jt,createArrayOfNumbers:te,isNumeric:ee,getMaxSafeInteger:oe,cleanNumber:function(t){return"string"==typeof t&&(t=parseInt(t,10)),"number"==typeof t?Math.floor(t):null},decToHex:function(t,e){for(var o="",n=0;n<e;n++)o+=String.fromCharCode(255&t),t>>>=8;return o},formatNumberTwoDecimalPlacesAndCommas:function(t){return"number"!=typeof t?"":ne(Math.round(100*t)/100)},formatNumberCommas:ne,sum:function(t){return null==t?null:t.reduce((function(t,e){return t+e}),0)}}),re=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),se=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},ae=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}re(e,t),e.prototype.calculateColInitialWidth=function(t){var e,o=this.gridOptionsWrapper,n=null!=t.minWidth?t.minWidth:o.getMinColWidth(),i=null!=t.maxWidth?t.maxWidth:o.getMaxColWidth()||oe(),s=r(t.width),a=r(t.initialWidth);return e=null!=s?s:null!=a?a:o.getColWidth(),Math.max(Math.min(e,i),n)},e.prototype.getOriginalPathForColumn=function(t,e){var o=[],n=!1,i=function(e,r){for(var s=0;s<e.length;s++){if(n)return;var a=e[s];if(a instanceof Ct)i(a.getChildren(),r+1),o[r]=a;else a===t&&(n=!0)}};return i(e,0),n?o:null},e.prototype.depthFirstOriginalTreeSearch=function(t,e,o){var n=this;e&&e.forEach((function(e){e instanceof Ct&&n.depthFirstOriginalTreeSearch(e,e.getChildren(),o),o(e,t)}))},e.prototype.depthFirstAllColumnTreeSearch=function(t,e){var o=this;t&&t.forEach((function(t){t instanceof mt&&o.depthFirstAllColumnTreeSearch(t.getChildren(),e),e(t)}))},e.prototype.depthFirstDisplayedColumnTreeSearch=function(t,e){var o=this;t&&t.forEach((function(t){t instanceof mt&&o.depthFirstDisplayedColumnTreeSearch(t.getDisplayedChildren(),e),e(t)}))},e=se([nt("columnUtils")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),le=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},pe=(function(t){function o(){return null!==t&&t.apply(this,arguments)||this}ae(o,t),o.prototype.createDisplayedGroups=function(t,e,o,n,i){var r,s,a=this,l=[],p=this.mapOldGroupsById(i);return t.forEach((function(t){for(var i=a.getOriginalPathForColumn(e,t),u=[],c=!s,h=0;h<i.length;h++)if(c||i[h]!==s[h]){var f=a.createColumnGroup(i[h],o,p,n);u[h]=f,0==h?l.push(f):u[h-1].addChild(f)}else u[h]=r[h];0===u.length?l.push(t):d(u).addChild(t);r=u,s=i})),this.setupParentsIntoColumns(l,null),l},o.prototype.createColumnGroup=function(t,o,n,i){var r=t.getGroupId(),s=o.getInstanceIdForKey(r),a=n[mt.createUniqueId(r,s)];return a&&a.getOriginalColumnGroup()!==t&&(a=null),e(a)?a.reset():(a=new mt(t,r,s,i),this.context.createBean(a)),a},o.prototype.mapOldGroupsById=function(t){var e={},o=function(t){t.forEach((function(t){if(t instanceof mt){var n=t;e[t.getUniqueId()]=n,o(n.getChildren())}}))};return t&&o(t),e},o.prototype.setupParentsIntoColumns=function(t,e){var o=this;t.forEach((function(t){if(t.setParent(e),t instanceof mt){var n=t;o.setupParentsIntoColumns(n.getChildren(),n)}}))},o.prototype.getOriginalPathForColumn=function(t,e){var o=[],n=!1,i=function(t,r){for(var s=0;s<t.length;s++){if(n)return;var a=t[s];if(a instanceof Ct)i(a.getChildren(),r+1),o[r]=a;else a===e&&(n=!0)}};return i(t,0),n?o:(console.warn("could not get path"),null)},le([it("columnUtils")],o.prototype,"columnUtils",void 0),o=le([nt("displayedGroupCreator")],o)}(Mt),function(){for(var t=0,e=0,o=arguments.length;e<o;e++)t+=arguments[e].length;var n=Array(t),i=0;for(e=0;e<o;e++)for(var r=arguments[e],s=0,a=r.length;s<a;s++,i++)n[i]=r[s];return n}),ue=function(){function t(){}return t.STRING_PROPERTIES=["sortingOrder","rowClass","rowSelection","overlayLoadingTemplate","overlayNoRowsTemplate","quickFilterText","rowModelType","editType","domLayout","clipboardDeliminator","rowGroupPanelShow","multiSortKey","pivotColumnGroupTotals","pivotRowTotals","pivotPanelShow","fillHandleDirection","serverSideStoreType"],t.OBJECT_PROPERTIES=["components","frameworkComponents","rowStyle","context","autoGroupColumnDef","localeText","icons","datasource","serverSideDatasource","viewportDatasource","groupRowRendererParams","aggFuncs","fullWidthCellRendererParams","defaultColGroupDef","defaultColDef","defaultExportParams","columnTypes","rowClassRules","detailGridOptions","detailCellRendererParams","loadingCellRendererParams","loadingOverlayComponentParams","noRowsOverlayComponentParams","popupParent","colResizeDefault","reduxStore","statusBar","sideBar","chartThemeOverrides","customChartThemes"],t.ARRAY_PROPERTIES=["alignedGrids","rowData","columnDefs","excelStyles","pinnedTopRowData","pinnedBottomRowData","chartThemes"],t.NUMBER_PROPERTIES=["rowHeight","detailRowHeight","rowBuffer","colWidth","headerHeight","groupHeaderHeight","floatingFiltersHeight","pivotHeaderHeight","pivotGroupHeaderHeight","groupDefaultExpanded","minColWidth","maxColWidth","viewportRowModelPageSize","viewportRowModelBufferSize","autoSizePadding","maxBlocksInCache","maxConcurrentDatasourceRequests","tooltipShowDelay","cacheOverflowSize","paginationPageSize","cacheBlockSize","infiniteInitialRowCount","scrollbarWidth","batchUpdateWaitMillis","asyncTransactionWaitMillis","blockLoadDebounceMillis","keepDetailRowsCount","undoRedoCellEditingLimit","cellFlashDelay","cellFadeDelay"],t.BOOLEAN_PROPERTIES=["suppressMakeColumnVisibleAfterUnGroup","suppressRowClickSelection","suppressCellSelection","suppressHorizontalScroll","alwaysShowHorizontalScroll","alwaysShowVerticalScroll","debug","enableBrowserTooltips","enableCellExpressions","angularCompileRows","angularCompileFilters","groupSuppressAutoColumn","groupSelectsChildren","groupIncludeFooter","groupIncludeTotalFooter","groupUseEntireRow","groupSuppressBlankHeader","suppressMenuHide","suppressRowDeselection","unSortIcon","suppressMultiSort","singleClickEdit","suppressLoadingOverlay","suppressNoRowsOverlay","suppressAutoSize","skipHeaderOnAutoSize","suppressParentsInRowNodes","suppressColumnMoveAnimation","suppressMovableColumns","suppressFieldDotNotation","enableRangeSelection","enableRangeHandle","enableFillHandle","suppressClearOnFillReduction","deltaSort","suppressTouch","suppressAsyncEvents","allowContextMenuWithControlKey","suppressContextMenu","rememberGroupStateWhenNewData","enableCellChangeFlash","suppressDragLeaveHidesColumns","suppressMiddleClickScrolls","suppressPreventDefaultOnMouseWheel","suppressCopyRowsToClipboard","copyHeadersToClipboard","pivotMode","suppressAggFuncInHeader","suppressColumnVirtualisation","suppressAggAtRootLevel","suppressFocusAfterRefresh","functionsPassive","functionsReadOnly","animateRows","groupSelectsFiltered","groupRemoveSingleChildren","groupRemoveLowestSingleChildren","enableRtl","suppressClickEdit","rowDragManaged","suppressRowDrag","suppressMoveWhenRowDragging","enableMultiRowDragging","enableGroupEdit","embedFullWidthRows","deprecatedEmbedFullWidthRows","suppressPaginationPanel","floatingFilter","groupHideOpenParents","groupMultiAutoColumn","pagination","stopEditingWhenGridLosesFocus","paginationAutoPageSize","suppressScrollOnNewData","purgeClosedRowNodes","cacheQuickFilter","deltaRowDataMode","ensureDomOrder","accentedSort","suppressChangeDetection","valueCache","valueCacheNeverExpires","aggregateOnlyChangedColumns","suppressAnimationFrame","suppressExcelExport","suppressCsvExport","treeData","masterDetail","suppressMultiRangeSelection","enterMovesDownAfterEdit","enterMovesDown","suppressPropertyNamesCheck","rowMultiSelectWithClick","suppressEnterpriseResetOnNewColumns","enableOldSetFilterModel","suppressRowHoverHighlight","suppressRowTransform","suppressClipboardPaste","suppressLastEmptyLineOnPaste","serverSideSortingAlwaysResets","reactNext","suppressSetColumnStateEvents","suppressColumnStateEvents","enableCharts","deltaColumnMode","suppressMaintainUnsortedOrder","enableCellTextSelection","suppressBrowserResizeObserver","suppressMaxRenderedRowRestriction","excludeChildrenWhenTreeDataFiltering","tooltipMouseTrack","keepDetailRows","paginateChildRows","preventDefaultOnContextMenu","undoRedoCellEditing","allowDragFromColumnsToolPanel","immutableData","immutableColumns","pivotSuppressAutoColumn","suppressExpandablePivotGroups","applyColumnDefOrder","debounceVerticalScrollbar","detailRowAutoHeight","serverSideFilteringAlwaysResets","suppressAggFilteredOnly","showOpenedGroup","suppressClipboardApi","suppressModelUpdateAfterUpdateTransaction"],t.FUNCTION_PROPERTIES=["localeTextFunc","groupRowInnerRenderer","groupRowInnerRendererFramework","dateComponent","dateComponentFramework","groupRowRenderer","groupRowRendererFramework","isExternalFilterPresent","getRowHeight","doesExternalFilterPass","getRowClass","getRowStyle","getRowClassRules","traverseNode","getContextMenuItems","getMainMenuItems","processRowPostCreate","processCellForClipboard","groupRowAggNodes","getRowNodeId","isFullWidthCell","fullWidthCellRenderer","fullWidthCellRendererFramework","processSecondaryColDef","processSecondaryColGroupDef","getBusinessKeyForNode","sendToClipboard","navigateToNextHeader","tabToNextHeader","navigateToNextCell","tabToNextCell","getDetailRowData","processCellFromClipboard","getDocument","postProcessPopup","getChildCount","getDataPath","loadingCellRenderer","loadingCellRendererFramework","loadingOverlayComponent","loadingOverlayComponentFramework","noRowsOverlayComponent","noRowsOverlayComponentFramework","detailCellRenderer","detailCellRendererFramework","defaultGroupSortComparator","isRowMaster","isRowSelectable","postSort","processHeaderForClipboard","paginationNumberFormatter","processDataFromClipboard","getServerSideGroupKey","isServerSideGroup","suppressKeyboardEvent","createChartContainer","processChartOptions","getChartToolbarItems","fillOperation","isApplyServerSideTransaction","getServerSideStoreParams","isServerSideGroupOpenByDefault"],t.ALL_PROPERTIES=pe(t.ARRAY_PROPERTIES,t.OBJECT_PROPERTIES,t.STRING_PROPERTIES,t.NUMBER_PROPERTIES,t.FUNCTION_PROPERTIES,t.BOOLEAN_PROPERTIES),t.FRAMEWORK_PROPERTIES=["__ob__","__v_skip","__metadata__","mappedColumnProperties","hasChildColumns","toColDef","createColDefFromGridColumn"],t}(),ce=function(){for(var t=0,e=0,o=arguments.length;e<o;e++)t+=arguments[e].length;var n=Array(t),i=0;for(e=0;e<o;e++)for(var r=arguments[e],s=0,a=r.length;s<a;s++,i++)n[i]=r[s];return n},de=function(){function t(){}return t.getEventCallbacks=function(){return t.EVENT_CALLBACKS||(t.EVENT_CALLBACKS=t.EVENTS.map((function(e){return t.getCallbackForEvent(e)}))),t.EVENT_CALLBACKS},t.copyAttributesToGridOptions=function(e,o,n){"object"!=typeof e&&(e={});var i=e,r=function(t){return void 0!==o[t]};return ce(t.ARRAY_PROPERTIES,t.STRING_PROPERTIES,t.OBJECT_PROPERTIES,t.FUNCTION_PROPERTIES,t.getEventCallbacks()).filter(r).forEach((function(t){return i[t]=o[t]})),t.BOOLEAN_PROPERTIES.filter(r).forEach((function(e){return i[e]=t.toBoolean(o[e])})),t.NUMBER_PROPERTIES.filter(r).forEach((function(e){return i[e]=t.toNumber(o[e])})),e},t.getCallbackForEvent=function(t){return!t||t.length<2?t:"on"+t[0].toUpperCase()+t.substr(1)},t.processOnChange=function(e,o,n,i){if(e){var r=o,s=function(t){return e[t]};ce(t.ARRAY_PROPERTIES,t.OBJECT_PROPERTIES,t.STRING_PROPERTIES,t.getEventCallbacks()).filter(s).forEach((function(t){return r[t]=e[t].currentValue})),t.BOOLEAN_PROPERTIES.filter(s).forEach((function(o){return r[o]=t.toBoolean(e[o].currentValue)})),t.NUMBER_PROPERTIES.filter(s).forEach((function(o){return r[o]=t.toNumber(e[o].currentValue)})),e.enableCellTextSelection&&n.setEnableCellTextSelection(t.toBoolean(e.enableCellTextSelection.currentValue)),e.quickFilterText&&n.setQuickFilter(e.quickFilterText.currentValue),e.rowData&&n.setRowData(e.rowData.currentValue),e.pinnedTopRowData&&n.setPinnedTopRowData(e.pinnedTopRowData.currentValue),e.pinnedBottomRowData&&n.setPinnedBottomRowData(e.pinnedBottomRowData.currentValue),e.autoGroupColumnDef&&n.setAutoGroupColumnDef(e.autoGroupColumnDef.currentValue,"gridOptionsChanged"),e.columnDefs&&n.setColumnDefs(e.columnDefs.currentValue,"gridOptionsChanged"),e.datasource&&n.setDatasource(e.datasource.currentValue),e.headerHeight&&n.setHeaderHeight(t.toNumber(e.headerHeight.currentValue)),e.paginationPageSize&&n.paginationSetPageSize(t.toNumber(e.paginationPageSize.currentValue)),e.pivotMode&&i.setPivotMode(t.toBoolean(e.pivotMode.currentValue)),e.groupRemoveSingleChildren&&n.setGroupRemoveSingleChildren(t.toBoolean(e.groupRemoveSingleChildren.currentValue)),e.suppressRowDrag&&n.setSuppressRowDrag(t.toBoolean(e.suppressRowDrag.currentValue)),e.suppressMoveWhenRowDragging&&n.setSuppressMoveWhenRowDragging(t.toBoolean(e.suppressMoveWhenRowDragging.currentValue)),e.suppressRowClickSelection&&n.setSuppressRowClickSelection(t.toBoolean(e.suppressRowClickSelection.currentValue)),e.suppressClipboardPaste&&n.setSuppressClipboardPaste(t.toBoolean(e.suppressClipboardPaste.currentValue)),e.sideBar&&n.setSideBar(e.sideBar.currentValue);var a={type:Wt.EVENT_COMPONENT_STATE_CHANGED,api:o.api,columnApi:o.columnApi};A(e,(function(t,e){a[t]=e})),n.dispatchEvent(a)}},t.toBoolean=function(t){return"boolean"==typeof t?t:"string"==typeof t&&("TRUE"===t.toUpperCase()||""==t)},t.toNumber=function(t){return"number"==typeof t?t:"string"==typeof t?Number(t):void 0},t.EVENTS=[],t.STRING_PROPERTIES=ue.STRING_PROPERTIES,t.OBJECT_PROPERTIES=ue.OBJECT_PROPERTIES,t.ARRAY_PROPERTIES=ue.ARRAY_PROPERTIES,t.NUMBER_PROPERTIES=ue.NUMBER_PROPERTIES,t.BOOLEAN_PROPERTIES=ue.BOOLEAN_PROPERTIES,t.FUNCTION_PROPERTIES=ue.FUNCTION_PROPERTIES,t.ALL_PROPERTIES=ue.ALL_PROPERTIES,t}();
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/de.EVENTS=l(Wt);
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
var he=function(){for(var t=0,e=0,o=arguments.length;e<o;e++)t+=arguments[e].length;var n=Array(t),i=0;for(e=0;e<o;e++)for(var r=arguments[e],s=0,a=r.length;s<a;s++,i++)n[i]=r[s];return n},fe=function(){function t(){}return t.STRING_PROPERTIES=["headerName","columnGroupShow","headerClass","toolPanelClass","headerValueGetter","pivotKeys","groupId","colId","sort","initialSort","field","type","tooltipComponent","tooltipField","headerTooltip","cellClass","showRowGroup","template","templateUrl","filter","initialAggFunc","aggFunc","cellRenderer","cellEditor","pinned","initialPinned","chartDataType"],t.OBJECT_PROPERTIES=["headerGroupComponent","headerGroupComponentFramework","headerGroupComponentParams","cellStyle","cellRendererParams","cellEditorFramework","cellEditorParams","pinnedRowCellRendererFramework","pinnedRowCellRendererParams","filterFramework","filterParams","pivotValueColumn","headerComponent","headerComponentFramework","headerComponentParams","floatingFilterComponent","floatingFilterComponentParams","floatingFilterComponentFramework","tooltipComponent","tooltipComponentParams","tooltipComponentFramework","refData","columnsMenuParams"],t.ARRAY_PROPERTIES=["children","sortingOrder","allowedAggFuncs","menuTabs","pivotTotalColumnIds","cellClassRules","icons"],t.NUMBER_PROPERTIES=["sortedAt","sortIndex","initialSortIndex","flex","initialFlex","width","initialWidth","minWidth","maxWidth","rowGroupIndex","initialRowGroupIndex","pivotIndex","initialPivotIndex"],t.BOOLEAN_PROPERTIES=["suppressCellFlash","suppressColumnsToolPanel","suppressFiltersToolPanel","openByDefault","marryChildren","hide","initialHide","rowGroup","initialRowGroup","pivot","initialPivot","checkboxSelection","headerCheckboxSelection","headerCheckboxSelectionFilteredOnly","suppressMenu","suppressMovable","lockPosition","lockVisible","lockPinned","unSortIcon","suppressSizeToFit","suppressAutoSize","enableRowGroup","enablePivot","enableValue","editable","suppressPaste","suppressNavigable","enableCellChangeFlash","rowDrag","dndSource","autoHeight","wrapText","sortable","resizable","singleClickEdit","floatingFilter"],t.FUNCTION_PROPERTIES=["dndSourceOnRowDrag","valueGetter","valueSetter","filterValueGetter","keyCreator","cellRenderer","cellRendererFramework","pinnedRowCellRenderer","valueFormatter","pinnedRowValueFormatter","valueParser","comparator","equals","pivotComparator","suppressKeyboardEvent","suppressHeaderKeyboardEvent","colSpan","rowSpan","getQuickFilterText","newValueHandler","onCellValueChanged","onCellClicked","onCellDoubleClicked","onCellContextMenu","rowDragText","tooltipValueGetter","tooltipComponent","tooltipComponentFramework","cellRendererSelector","cellEditorSelector"],t.ALL_PROPERTIES=he(t.ARRAY_PROPERTIES,t.OBJECT_PROPERTIES,t.STRING_PROPERTIES,t.NUMBER_PROPERTIES,t.FUNCTION_PROPERTIES,t.BOOLEAN_PROPERTIES),t.FRAMEWORK_PROPERTIES=["__ob__","__v_skip","__metadata__","mappedColumnProperties","hasChildColumns","toColDef","createColDefFromGridColumn"],t}(),ge=function(){function t(t,e,o,n){void 0===n&&(n=1),this.r=Math.min(1,Math.max(0,t||0)),this.g=Math.min(1,Math.max(0,e||0)),this.b=Math.min(1,Math.max(0,o||0)),this.a=Math.min(1,Math.max(0,n||0))}return t.fromString=function(e){if(e.indexOf("#")>=0)return t.fromHexString(e);var o=t.nameToHex[e];if(o)return t.fromHexString(o);if(e.indexOf("rgb")>=0)return t.fromRgbaString(e);throw new Error("Invalid color string: '"+e+"'")},t.fromHexString=function(e){var o=e.match(t.hexRe);if(o)return new t((n=parseInt(o[1],16))/255,(i=parseInt(o[2],16))/255,(r=parseInt(o[3],16))/255,(s=void 0!==o[4]?parseInt(o[4],16):255)/255);if(o=e.match(t.shortHexRe)){var n=parseInt(o[1],16),i=parseInt(o[2],16),r=parseInt(o[3],16),s=void 0!==o[4]?parseInt(o[4],16):15;return new t((n+=16*n)/255,(i+=16*i)/255,(r+=16*r)/255,(s+=16*s)/255)}throw new Error("Malformed hexadecimal color string: '"+e+"'")},t.fromRgbaString=function(e){var o=e.match(t.rgbRe);if(o)return new t(+o[1]/255,+o[2]/255,+o[3]/255);if(o=e.match(t.rgbaRe))return new t(+o[1]/255,+o[2]/255,+o[3]/255,+o[4]);throw new Error("Malformed rgb/rgba color string: '"+e+"'")},t.fromArray=function(e){if(4===e.length)return new t(e[0],e[1],e[2],e[3]);if(3===e.length)return new t(e[0],e[1],e[2]);throw new Error("The given array should contain 3 or 4 color components (numbers).")},t.fromHSB=function(e,o,n,i){void 0===i&&(i=1);var r=t.HSBtoRGB(e,o,n);return new t(r[0],r[1],r[2],i)},t.padHex=function(t){return 1===t.length?"0"+t:t},t.prototype.toHexString=function(){var e="#"+t.padHex(Math.round(255*this.r).toString(16))+t.padHex(Math.round(255*this.g).toString(16))+t.padHex(Math.round(255*this.b).toString(16));return this.a<1&&(e+=t.padHex(Math.round(255*this.a).toString(16))),e},t.prototype.toRgbaString=function(t){void 0===t&&(t=3);var e=[Math.round(255*this.r),Math.round(255*this.g),Math.round(255*this.b)],o=Math.pow(10,t);return 1!==this.a?(e.push(Math.round(this.a*o)/o),"rgba("+e.join(", ")+")"):"rgb("+e.join(", ")+")"},t.prototype.toString=function(){return 1===this.a?this.toHexString():this.toRgbaString()},t.prototype.toHSB=function(){return t.RGBtoHSB(this.r,this.g,this.b)},t.RGBtoHSB=function(t,e,o){var n=Math.min(t,e,o),i=Math.max(t,e,o),r=NaN;if(n!==i){var s=i-n,a=(i-t)/s,l=(i-e)/s,p=(i-o)/s;r=t===i?p-l:e===i?2+a-p:4+l-a,(r/=6)<0&&(r+=1)}return[360*r,0!==i?(i-n)/i:0,i]},t.HSBtoRGB=function(t,e,o){isNaN(t)&&(t=0),t=(t%360+360)%360/360;var n=0,i=0,r=0;if(0===e)n=i=r=o;else{var s=6*(t-Math.floor(t)),a=s-Math.floor(s),l=o*(1-e),p=o*(1-e*a),u=o*(1-e*(1-a));switch(s>>0){case 0:n=o,i=u,r=l;break;case 1:n=p,i=o,r=l;break;case 2:n=l,i=o,r=u;break;case 3:n=l,i=p,r=o;break;case 4:n=u,i=l,r=o;break;case 5:n=o,i=l,r=p}}return[n,i,r]},t.prototype.derive=function(e,o,n,i){var r=t.RGBtoHSB(this.r,this.g,this.b),s=r[2];0==s&&n>1&&(s=.05);var a=((r[0]+e)%360+360)%360,l=Math.max(Math.min(r[1]*o,1),0);s=Math.max(Math.min(s*n,1),0);var p=Math.max(Math.min(this.a*i,1),0),u=t.HSBtoRGB(a,l,s);return u.push(p),t.fromArray(u)},t.prototype.brighter=function(){return this.derive(0,1,1/.7,1)},t.prototype.darker=function(){return this.derive(0,1,.7,1)},t.hexRe=/\s*#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})?\s*$/,t.shortHexRe=/\s*#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])?\s*$/,t.rgbRe=/\s*rgb\((\d+),\s*(\d+),\s*(\d+)\)\s*/,t.rgbaRe=/\s*rgba\((\d+),\s*(\d+),\s*(\d+),\s*([.\d]+)\)\s*/,t.nameToHex=Object.freeze({aliceblue:"#F0F8FF",antiquewhite:"#FAEBD7",aqua:"#00FFFF",aquamarine:"#7FFFD4",azure:"#F0FFFF",beige:"#F5F5DC",bisque:"#FFE4C4",black:"#000000",blanchedalmond:"#FFEBCD",blue:"#0000FF",blueviolet:"#8A2BE2",brown:"#A52A2A",burlywood:"#DEB887",cadetblue:"#5F9EA0",chartreuse:"#7FFF00",chocolate:"#D2691E",coral:"#FF7F50",cornflowerblue:"#6495ED",cornsilk:"#FFF8DC",crimson:"#DC143C",cyan:"#00FFFF",darkblue:"#00008B",darkcyan:"#008B8B",darkgoldenrod:"#B8860B",darkgray:"#A9A9A9",darkgreen:"#006400",darkgrey:"#A9A9A9",darkkhaki:"#BDB76B",darkmagenta:"#8B008B",darkolivegreen:"#556B2F",darkorange:"#FF8C00",darkorchid:"#9932CC",darkred:"#8B0000",darksalmon:"#E9967A",darkseagreen:"#8FBC8F",darkslateblue:"#483D8B",darkslategray:"#2F4F4F",darkslategrey:"#2F4F4F",darkturquoise:"#00CED1",darkviolet:"#9400D3",deeppink:"#FF1493",deepskyblue:"#00BFFF",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1E90FF",firebrick:"#B22222",floralwhite:"#FFFAF0",forestgreen:"#228B22",fuchsia:"#FF00FF",gainsboro:"#DCDCDC",ghostwhite:"#F8F8FF",gold:"#FFD700",goldenrod:"#DAA520",gray:"#808080",green:"#008000",greenyellow:"#ADFF2F",grey:"#808080",honeydew:"#F0FFF0",hotpink:"#FF69B4",indianred:"#CD5C5C",indigo:"#4B0082",ivory:"#FFFFF0",khaki:"#F0E68C",lavender:"#E6E6FA",lavenderblush:"#FFF0F5",lawngreen:"#7CFC00",lemonchiffon:"#FFFACD",lightblue:"#ADD8E6",lightcoral:"#F08080",lightcyan:"#E0FFFF",lightgoldenrodyellow:"#FAFAD2",lightgray:"#D3D3D3",lightgreen:"#90EE90",lightgrey:"#D3D3D3",lightpink:"#FFB6C1",lightsalmon:"#FFA07A",lightseagreen:"#20B2AA",lightskyblue:"#87CEFA",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#B0C4DE",lightyellow:"#FFFFE0",lime:"#00FF00",limegreen:"#32CD32",linen:"#FAF0E6",magenta:"#FF00FF",maroon:"#800000",mediumaquamarine:"#66CDAA",mediumblue:"#0000CD",mediumorchid:"#BA55D3",mediumpurple:"#9370DB",mediumseagreen:"#3CB371",mediumslateblue:"#7B68EE",mediumspringgreen:"#00FA9A",mediumturquoise:"#48D1CC",mediumvioletred:"#C71585",midnightblue:"#191970",mintcream:"#F5FFFA",mistyrose:"#FFE4E1",moccasin:"#FFE4B5",navajowhite:"#FFDEAD",navy:"#000080",oldlace:"#FDF5E6",olive:"#808000",olivedrab:"#6B8E23",orange:"#FFA500",orangered:"#FF4500",orchid:"#DA70D6",palegoldenrod:"#EEE8AA",palegreen:"#98FB98",paleturquoise:"#AFEEEE",palevioletred:"#DB7093",papayawhip:"#FFEFD5",peachpuff:"#FFDAB9",peru:"#CD853F",pink:"#FFC0CB",plum:"#DDA0DD",powderblue:"#B0E0E6",purple:"#800080",rebeccapurple:"#663399",red:"#FF0000",rosybrown:"#BC8F8F",royalblue:"#4169E1",saddlebrown:"#8B4513",salmon:"#FA8072",sandybrown:"#F4A460",seagreen:"#2E8B57",seashell:"#FFF5EE",sienna:"#A0522D",silver:"#C0C0C0",skyblue:"#87CEEB",slateblue:"#6A5ACD",slategray:"#708090",slategrey:"#708090",snow:"#FFFAFA",springgreen:"#00FF7F",steelblue:"#4682B4",tan:"#D2B48C",teal:"#008080",thistle:"#D8BFD8",tomato:"#FF6347",turquoise:"#40E0D0",violet:"#EE82EE",wheat:"#F5DEB3",white:"#FFFFFF",whitesmoke:"#F5F5F5",yellow:"#FFFF00",yellowgreen:"#9ACD32"}),t}();var ye,ve,me,Ce,we,Ee,Re=Object.freeze({__proto__:null,stringToArray:
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
function(t,e){void 0===e&&(e=",");var o=[],n=function(t){return"\r"===t||"\n"===t},i=!1;if(""===t)return[[""]];for(var r,s,a,l=function(l,p,u){var c=t[u-1],d=t[u],h=t[u+1],f=function(){o[l]||(o[l]=[]),o[l][p]||(o[l][p]="")};if(f(),'"'===d){if(i)return'"'===h?(o[l][p]+='"',u++):i=!1,r=l,s=p,a=u,"continue";if(void 0===c||c===e||n(c))return i=!0,r=l,s=p,a=u,"continue"}if(!i){if(d===e)return p++,f(),r=l,s=p,a=u,"continue";if(n(d))return p=0,l++,f(),"\r"===d&&"\n"===h&&u++,r=l,s=p,a=u,"continue"}o[l][p]+=d,r=l,s=p,a=u},p=0,u=0,c=0;c<t.length;c++)l(p,u,c),p=r,u=s,c=a;return o}});
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/function Oe(){return void 0===ve&&(ve=/*@cc_on!@*/!!document.documentMode),ve}function Pe(){return void 0===me&&(me=!Oe()&&!!window.StyleMedia),me}function Se(){return void 0===ye&&(ye=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),ye}function be(){if(void 0===Ce){var t=window;Ce=!!t.chrome&&(!!t.chrome.webstore||!!t.chrome.runtime)||/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)}return Ce}function De(){if(void 0===we){var t=window;we=void 0!==t.InstallTrigger}return we}function Ae(){return void 0===Ee&&(Ee=(/iPad|iPhone|iPod/.test(navigator.platform)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1)&&!window.MSStream),Ee}function Te(t){if(!t)return null;var e=t.tabIndex,o=t.getAttribute("tabIndex");if(Oe()&&0===e&&null===o){return!0==={a:!0,body:!0,button:!0,frame:!0,iframe:!0,img:!0,input:!0,isindex:!0,object:!0,select:!0,textarea:!0}[t.nodeName.toLowerCase()]?"0":null}return-1!==e||null!==o&&(""!==o||De())?e.toString():null}function _e(){if(!document.body)return-1;var t=1e6,e=navigator.userAgent.toLowerCase().match(/firefox/)?6e6:1e9,o=document.createElement("div");for(document.body.appendChild(o);;){var n=2*t;if(o.style.height=n+"px",n>e||o.clientHeight!==n)break;t=n}return document.body.removeChild(o),t}function Fe(){var t=document.body,e=document.createElement("div");e.style.width=e.style.height="100px",e.style.opacity="0",e.style.overflow="scroll",e.style.msOverflowStyle="scrollbar",e.style.position="absolute",t.appendChild(e);var o=e.offsetWidth-e.clientWidth;return 0===o&&0===e.clientWidth?null:(e.parentNode&&e.parentNode.removeChild(e),o)}function Ne(){return document.body?document.body.clientWidth:window.innerHeight?window.innerWidth:document.documentElement&&document.documentElement.clientWidth?document.documentElement.clientWidth:-1}function Le(){return document.body?document.body.clientHeight:window.innerHeight?window.innerHeight:document.documentElement&&document.documentElement.clientHeight?document.documentElement.clientHeight:-1}var Ie,Ge=Object.freeze({__proto__:null,isBrowserIE:Oe,isBrowserEdge:Pe,isBrowserSafari:Se,isBrowserChrome:be,isBrowserFirefox:De,isIOSUserAgent:Ae,getTabIndex:Te,getMaxDivHeight:_e,getScrollbarWidth:Fe,hasOverflowScrolling:function(){var t=["webkit","moz","o","ms"],e=document.createElement("div"),o=!1;document.getElementsByTagName("body")[0].appendChild(e),e.setAttribute("style",t.map((function(t){return"-"+t+"-overflow-scrolling: touch"})).concat("overflow-scrolling: touch").join(";"));var n=window.getComputedStyle(e);if("touch"===n.overflowScrolling&&(o=!0),!o)for(var i=0,r=t;i<r.length;i++)if("touch"===n[r[i]+"OverflowScrolling"]){o=!0;break}return e.parentNode&&e.parentNode.removeChild(e),o},getBodyWidth:Ne,getBodyHeight:Le});
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/function Me(t,e){if(t&&e&&0!==e.length){if(!(e.indexOf(" ")>=0)){if(t.classList)t.classList.add(e);else if(t.className&&t.className.length>0){var o=t.className.split(" ");o.indexOf(e)<0&&(o.push(e),t.setAttribute("class",o.join(" ")))}else t.setAttribute("class",e);return t}e.split(" ").forEach((function(e){return Me(t,e)}))}}function xe(t,e){if(t&&e&&0!==e.length)if(e.indexOf(" ")>=0)e.split(" ").forEach((function(e){return xe(t,e)}));else if(t.classList)t.classList.remove(e);else if(t.className&&t.className.length>0){var o=t.className.split(" ").filter((function(t){return t!==e})).join(" ");t.setAttribute("class",o)}}function Ve(t,e,o){o?Me(t,e):xe(t,e)}function He(t,e){if(t.classList)return t.classList.contains(e);if(t.className){var o=t.className===e,n=t.className.indexOf(" "+e+" ")>=0,i=0===t.className.indexOf(e+" "),r=t.className.lastIndexOf(" "+e)===t.className.length-e.length-1;return o||n||i||r}return!1}function We(t){var e=Element.prototype.matches||Element.prototype.msMatchesSelector,o=e.call(t,ht.INPUT_SELECTOR),n=e.call(t,ht.FOCUSABLE_EXCLUDE),i=eo(t);return o&&!n&&i}function ke(t,e){Ve(t,"ag-hidden",!e)}function Be(t,e){Ve(t,"ag-invisible",!e)}function je(t,e){var o=e?function(t){return t.setAttribute("disabled","")}:function(t){return t.removeAttribute("disabled")};o(t),Oo(t.querySelectorAll("input"),(function(t){return o(t)}))}function Ue(t,e,o){for(var n=0;t;){if(He(t,e))return!0;if(t=t.parentElement,o&&++n>o)break}return!1}function ze(t){var e=window.getComputedStyle(t),o=e.height,n=e.width,i=e.paddingTop,r=e.paddingRight,s=e.paddingBottom,a=e.paddingLeft,l=e.marginTop,p=e.marginRight,u=e.marginBottom,c=e.marginLeft,d=e.boxSizing;return{height:parseFloat(o),width:parseFloat(n),paddingTop:parseFloat(i),paddingRight:parseFloat(r),paddingBottom:parseFloat(s),paddingLeft:parseFloat(a),marginTop:parseFloat(l),marginRight:parseFloat(p),marginBottom:parseFloat(u),marginLeft:parseFloat(c),boxSizing:d}}function Ke(t){var e=ze(t);return"border-box"===e.boxSizing?e.height-e.paddingTop-e.paddingBottom:e.height}function Ye(t){var e=ze(t);return"border-box"===e.boxSizing?e.width-e.paddingLeft-e.paddingRight:e.width}function qe(t){var e=ze(t),o=e.marginBottom+e.marginTop;return Math.ceil(t.offsetHeight+o)}function Xe(t){var e=ze(t),o=e.marginLeft+e.marginRight;return Math.ceil(t.offsetWidth+o)}function Qe(){if("boolean"==typeof Ie)return Ie;var t=document.createElement("div");return t.style.direction="rtl",t.style.width="1px",t.style.height="1px",t.style.position="fixed",t.style.top="0px",t.style.overflow="hidden",t.dir="rtl",t.innerHTML='<div style="width: 2px">\n <span style="display: inline-block; width: 1px"></span>\n <span style="display: inline-block; width: 1px"></span>\n </div>',document.body.appendChild(t),t.scrollLeft=1,Ie=0===Math.floor(t.scrollLeft),document.body.removeChild(t),Ie}function $e(t,e){var o=t.scrollLeft;return e&&(o=Math.abs(o),be()&&!Qe()&&(o=t.scrollWidth-t.clientWidth-o)),o}function Ze(t,e,o){o&&(Qe()?e*=-1:(Se()||be())&&(e=t.scrollWidth-t.clientWidth-e)),t.scrollLeft=e}function Je(t){for(;t&&t.firstChild;)t.removeChild(t.firstChild)}function to(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function eo(t){return null!==t.offsetParent}function oo(t){var e=document.createElement("div");return e.innerHTML=(t||"").trim(),e.firstChild}function no(t,e){t.lastChild?t.insertAdjacentHTML("afterbegin",e):t.innerHTML=e}function io(t){return t&&t.clientHeight?t.clientHeight:0}function ro(t){return t&&t.clientWidth?t.clientWidth:0}function so(t,e,o){o&&o.nextSibling===e||(o?o.nextSibling?t.insertBefore(e,o.nextSibling):t.appendChild(e):t.firstChild&&t.firstChild!==e&&t.insertAdjacentElement("afterbegin",e))}function ao(t,e){for(var o=0;o<e.length;o++){var n=e[o],i=t.children[o];i!==n&&t.insertBefore(n,i)}}function lo(t,e,o){var n;return o?(o.insertAdjacentHTML("afterend",e),n=o.nextSibling):(t.firstChild?t.insertAdjacentHTML("afterbegin",e):t.innerHTML=e,n=t.firstChild),n}function po(t,e){e&&Object.keys(e).forEach((function(o){var n=zt(o);n&&(t.style[n]=e[o])}))}function uo(t){return t.clientWidth<t.scrollWidth}function co(t){return t.clientHeight<t.scrollHeight}function ho(t,e){"flex"===e?(t.style.removeProperty("width"),t.style.removeProperty("minWidth"),t.style.removeProperty("maxWidth"),t.style.flex="1 1 auto"):fo(t,e)}function fo(t,e){e=yo(e),t.style.width=e.toString(),t.style.maxWidth=e.toString(),t.style.minWidth=e.toString()}function go(t,e){e=yo(e),t.style.height=e.toString(),t.style.maxHeight=e.toString(),t.style.minHeight=e.toString()}function yo(t){return"number"==typeof t?t+"px":t}function vo(t){return"function"==typeof Node?t instanceof Node:t&&"object"==typeof t&&"number"==typeof t.nodeType&&"string"==typeof t.nodeName}function mo(t){return"function"==typeof HTMLElement?t instanceof HTMLElement:t&&W(t)&&1===t.nodeType&&"string"==typeof t.nodeName}function Co(t){return vo(t)||mo(t)}function wo(t){if(null==t)return[];var e=[];return Oo(t,(function(t){return e.push(t)})),e}function Eo(t,e){if(t)for(var o=0;o<t.length;o++){var n=t[o];e(n.name,n.value)}}function Ro(t,e,o){null==o?t.removeAttribute(e):t.setAttribute(e,o.toString())}function Oo(t,e){if(null!=t)for(var o=0;o<t.length;o++)e(t[o])}var Po=Object.freeze({__proto__:null,addCssClass:Me,removeCssClass:xe,addOrRemoveCssClass:Ve,radioCssClass:function(t,e,o){for(var n=t.parentElement,i=n&&n.firstChild;i;)e&&Ve(i,e,i===t),o&&Ve(i,o,i!==t),i=i.nextSibling},containsClass:He,isFocusableFormField:We,setDisplayed:ke,setVisible:Be,setDisabled:je,isElementChildOfClass:Ue,getElementSize:ze,getInnerHeight:Ke,getInnerWidth:Ye,getAbsoluteHeight:qe,getAbsoluteWidth:Xe,isRtlNegativeScroll:Qe,getScrollLeft:$e,setScrollLeft:Ze,clearElement:Je,removeElement:function(t,e){to(t.querySelector(e))},removeFromParent:to,isVisible:eo,loadTemplate:oo,appendHtml:no,getElementAttribute:function(t,e){return t.attributes&&t.attributes[e]?t.attributes[e].value:null},offsetHeight:io,offsetWidth:ro,ensureDomOrder:so,setDomChildOrder:ao,insertTemplateWithDomOrder:lo,prependDC:function(t,o){e(t.firstChild)?t.insertBefore(o,t.firstChild):t.appendChild(o)},addStylesToElement:po,isHorizontalScrollShowing:uo,isVerticalScrollShowing:co,setElementWidth:ho,setFixedWidth:fo,setElementHeight:function(t,e){"flex"===e?(t.style.removeProperty("height"),t.style.removeProperty("minHeight"),t.style.removeProperty("maxHeight"),t.style.flex="1 1 auto"):go(t,e)},setFixedHeight:go,formatSize:yo,isNode:vo,isElement:mo,isNodeOrElement:Co,copyNodeList:wo,iterateNamedNodeMap:Eo,setCheckboxState:function(t,e){"boolean"==typeof e?(t.checked=e,t.indeterminate=!1):t.indeterminate=!0},addOrRemoveAttribute:Ro,nodeListForEach:Oo});
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/function So(t){if(!t)return"";var e=[];return A(t,(function(t,o){var n=Ut(t);e.push(n+": "+o+";")})),e.join(" ")}function bo(t,e){t.then((function(t){var o=t.getGui();null!=o&&("object"==typeof o?e.appendChild(o):e.innerHTML=o)}))}var Do=Object.freeze({__proto__:null,getNameOfClass:function(t){var e=t.toString(),o=/function (.{1,})\(/.exec(e);return o&&o.length>1?o[1]:""},findLineByLeastSquares:function(t){var e=t.length,o=0;if(e<=1)return t;for(var n=0;n<t.length;n++){var i=t[n];Math.floor(i)!==i&&(o=Math.max(o,i.toString().split(".")[1].length))}for(var r=0,s=0,a=0,l=0,p=0,u=0;u<e;u++)r+=u,s+=p=t[u],l+=u*u,a+=u*p;var c=(e*a-r*s)/(e*l-r*r),d=s/e-c*r/e,h=[];for(u=0;u<=e;u++)h.push(parseFloat((u*c+d).toFixed(o)));return h},cssStyleObjectToMarkup:So,message:function(t){var e=document.createElement("div"),o=document.querySelector("#__ag__message");if(e.innerHTML=t,!o){o=oo('<div id="__ag__message" style="display: inline-block; position: absolute; top: 0px; left: 0px; color: white; background-color: black; z-index: 20; padding: 2px; border: 1px solid darkred; height: 200px; overflow-y: auto;"></div>'),document.body&&document.body.appendChild(o)}o.insertBefore(e,o.children[0])},bindCellRendererToHtmlElement:bo});
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/function Ao(t,e,o){t.setAttribute(_o(e),o.toString())}function To(t,e){t.removeAttribute(_o(e))}function _o(t){return"aria-"+t}function Fo(t){return t.isSortAscending()?"ascending":t.isSortDescending()?"descending":"none"}function No(t){return parseInt(t.getAttribute("aria-posinset"),10)}function Lo(t){return t.getAttribute("aria-describedby")||""}function Io(t,e){Ao(t,"label",e)}function Go(t,e){Ao(t,"labelledby",e)}function Mo(t,e){Ao(t,"describedby",e)}function xo(t,e){Ao(t,"disabled",e)}function Vo(t,e){Ao(t,"expanded",e)}function Ho(t){To(t,"expanded")}function Wo(t,e){Ao(t,"setsize",e)}function ko(t,e){Ao(t,"posinset",e)}function Bo(t,e){Ao(t,"multiselectable",e)}function jo(t,e){Ao(t,"rowcount",e)}function Uo(t,e){Ao(t,"rowindex",e)}function zo(t,e){Ao(t,"colcount",e)}function Ko(t,e){Ao(t,"colindex",e)}function Yo(t,e){Ao(t,"colspan",e)}function qo(t,e){Ao(t,"sort",e)}function Xo(t){To(t,"sort")}function Qo(t,e){e?Ao(t,"selected",e):To(t,"selected")}function $o(t,e){Ao(t,"checked",void 0===e?"mixed":e)}var Zo=Object.freeze({__proto__:null,getAriaSortState:Fo,getAriaLevel:function(t){return parseInt(t.getAttribute("aria-level"),10)},getAriaPosInSet:No,getAriaDescribedBy:Lo,setAriaLabel:Io,setAriaLabelledBy:Go,setAriaDescribedBy:Mo,setAriaLevel:function(t,e){Ao(t,"level",e)},setAriaDisabled:xo,setAriaExpanded:Vo,removeAriaExpanded:Ho,setAriaSetSize:Wo,setAriaPosInSet:ko,setAriaMultiSelectable:Bo,setAriaRowCount:jo,setAriaRowIndex:Uo,setAriaColCount:zo,setAriaColIndex:Ko,setAriaColSpan:Yo,setAriaSort:qo,removeAriaSort:Xo,setAriaSelected:Qo,setAriaChecked:$o});
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/function Jo(t,e,o){if(void 0===e&&(e=!0),void 0===o&&(o="-"),!t)return null;var n=[t.getFullYear(),t.getMonth()+1,t.getDate()].map((function(t){return Jt(t,2)})).join(o);return e&&(n+=" "+[t.getHours(),t.getMinutes(),t.getSeconds()].map((function(t){return Jt(t,2)})).join(":")),n}function tn(t){if(!t)return null;var e=t.split(" "),o=e[0],n=e[1];if(!o)return null;var i=o.split("-").map((function(t){return parseInt(t,10)}));if(3!==i.filter((function(t){return!isNaN(t)})).length)return null;var r=i[0],s=i[1],a=i[2],l=new Date(r,s-1,a);if(l.getFullYear()!==r||l.getMonth()!==s-1||l.getDate()!==a)return null;if(!n||"00:00:00"===n)return l;var p=n.split(":").map((function(t){return parseInt(t,10)})),u=p[0],c=p[1],d=p[2];return u>=0&&u<24&&l.setHours(u),c>=0&&c<60&&l.setMinutes(c),d>=0&&d<60&&l.setSeconds(d),l}var en=Object.freeze({__proto__:null,serialiseDate:Jo,parseDateTimeFromString:tn});
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/function on(t,e,o){var n={},i=t.filter((function(t){return!e.some((function(e){return e===t}))}));return i.length>0&&i.forEach((function(t){return n[t]=nn(t,o)})),n}function nn(t,e,o,n){var i=n?an:sn,r=e.map((function(e){return{value:e,relevance:i(t.toLowerCase(),e.toLocaleLowerCase())}}));return r.sort((function(t,e){return e.relevance-t.relevance})),o&&(r=r.filter((function(t){return 0!==t.relevance}))),r.map((function(t){return t.value}))}function rn(t){var e,o,n,i=t.toLowerCase(),r=new Array(i.length-1);for(e=o=0,n=r.length;o<=n;e=o+=1)r[e]=i.slice(e,e+2);return r}function sn(t,e){if(0===t.length&&0===e.length)return 0;var o,n,i=rn(t),r=rn(e),s=i.length+r.length,a=0;for(o=0,n=i.length;o<n;o++){var l,p=i[o],u=void 0;for(u=0,l=r.length;u<l;u++){p===r[u]&&a++}}return a>0?2*a/s:0}function an(t,e){for(var o=t.replace(/\s/g,""),n=e.replace(/\s/g,""),i=0,r=0,s=0;s<o.length;s++){var a=n.indexOf(o[s]);-1!==a&&(r=a,i+=100*(n.length-r)/n.length,i*=i)}return i}var ln=Object.freeze({__proto__:null,fuzzyCheckStrings:on,fuzzySuggestions:nn,get_bigrams:rn,string_distances:sn,string_weighted_distances:an}),pn={columnGroupOpened:"expanded",columnGroupClosed:"contracted",columnSelectClosed:"tree-closed",columnSelectOpen:"tree-open",columnSelectIndeterminate:"tree-indeterminate",columnMovePin:"pin",columnMoveHide:"eye-slash",columnMoveMove:"arrows",columnMoveLeft:"left",columnMoveRight:"right",columnMoveGroup:"group",columnMoveValue:"aggregation",columnMovePivot:"pivot",dropNotAllowed:"not-allowed",groupContracted:"tree-closed",groupExpanded:"tree-open",chart:"chart",close:"cross",cancel:"cancel",check:"tick",first:"first",previous:"previous",next:"next",last:"last",linked:"linked",unlinked:"unlinked",colorPicker:"color-picker",groupLoading:"loading",menu:"menu",filter:"filter",columns:"columns",maximize:"maximize",minimize:"minimize",menuPin:"pin",menuValue:"aggregation",menuAddRowGroup:"group",menuRemoveRowGroup:"group",clipboardCopy:"copy",clipboardPaste:"paste",pivotPanel:"pivot",rowGroupPanel:"group",valuePanel:"aggregation",columnDrag:"grip",rowDrag:"grip",save:"save",smallDown:"small-down",smallLeft:"small-left",smallRight:"small-right",smallUp:"small-up",sortAscending:"asc",sortDescending:"desc",sortUnSort:"none"};
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/function un(t,e,o){var n=cn(t,e,o);if(n&&n.className.indexOf("ag-icon")>-1)return n;var i=document.createElement("span");return i.appendChild(n),i}function cn(t,e,o,n){var i=null,r=o&&o.getColDef().icons;if(r&&(i=r[t]),e&&!i){var s=e.getIcons();s&&(i=s[t])}if(!i){var a=document.createElement("span"),l=pn[t];return l||(n?l=t:(console.warn("AG Grid: Did not find icon "+t),l="")),a.setAttribute("class","ag-icon ag-icon-"+l),a.setAttribute("unselectable","on"),a.setAttribute("role","presentation"),a}var p=void 0;if("function"==typeof i)p=i();else{if("string"!=typeof i)throw new Error("icon from grid options needs to be a string or a function");p=i}return"string"==typeof p?oo(p):Co(p)?p:void console.warn("AG Grid: iconRenderer should return back a string or a dom object")}var dn=Object.freeze({__proto__:null,iconNameClassMap:pn,createIcon:un,createIconNoSpan:cn});
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/function hn(t,e){return(t.which||t.keyCode)===e}function fn(t){if(t.altKey||t.ctrlKey||t.metaKey)return!1;var e=1===t.key.length,o=function(t){return(Pe()||Oe())&&"Del"===t.key&&46===t.charCode}(t);return e||o}function gn(t,e,o,n,i){var r=t.getSuppressKeyboardEventFunc(),s=n?n.getColDef().suppressKeyboardEvent:void 0;if(!r&&!s)return!1;var a={event:e,editing:i,column:n,api:t.getApi(),node:o,data:o.data,colDef:n.getColDef(),context:t.getContext(),columnApi:t.getColumnApi()};if(s&&s(a))return!0;return!!r&&r(a)}function yn(t,o,n,i){var r=i.getDefinition(),s=r&&r.suppressHeaderKeyboardEvent;return!!e(s)&&!!s({api:t.getApi(),columnApi:t.getColumnApi(),context:t.getContext(),colDef:r,column:i,headerRowIndex:n,event:o})}var vn=Object.freeze({__proto__:null,isKeyPressed:hn,isEventFromPrintableCharacter:fn,isUserSuppressingKeyboardEvent:gn,isUserSuppressingHeaderKeyboardEvent:yn});
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/var mn=Object.freeze({__proto__:null,keys:function(t){var e=[];return t.forEach((function(t,o){return e.push(o)})),e}});
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/function Cn(t,e,o){if(0===o)return!1;var n=Math.abs(t.clientX-e.clientX),i=Math.abs(t.clientY-e.clientY);return Math.max(n,i)<=o}var wn=Object.freeze({__proto__:null,normalizeWheel:function(t){var e=0,o=0,n=0,i=0;return"detail"in t&&(o=t.detail),"wheelDelta"in t&&(o=-t.wheelDelta/120),"wheelDeltaY"in t&&(o=-t.wheelDeltaY/120),"wheelDeltaX"in t&&(e=-t.wheelDeltaX/120),"axis"in t&&t.axis===t.HORIZONTAL_AXIS&&(e=o,o=0),n=10*e,i=10*o,"deltaY"in t&&(i=t.deltaY),"deltaX"in t&&(n=t.deltaX),(n||i)&&t.deltaMode&&(1==t.deltaMode?(n*=40,i*=40):(n*=800,i*=800)),n&&!e&&(e=n<1?-1:1),i&&!o&&(o=i<1?-1:1),{spinX:e,spinY:o,pixelX:n,pixelY:i}},isLeftClick:function(t){return"buttons"in t?1==t.buttons:1==(t.which||t.button)},areEventsNear:Cn});
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/var En=Object.freeze({__proto__:null,sortRowNodesByOrder:function(t,e){if(t){for(var o=function(t,o){var n=e[t.id],i=e[o.id],r=void 0!==n,s=void 0!==i;return r&&s?n-i:!r&&!s?t.__objectId-o.__objectId:r?1:-1},n=!1,i=0;i<t.length-1;i++)if(o(t[i],t[i+1])>0){n=!0;break}n&&t.sort(o)}},traverseNodesWithKey:function(t,e){var o=[];!function t(n){if(!n)return;n.forEach((function(n){if(n.group||n.hasChildren()){o.push(n.key);var i=o.join("|");e(n,i),t(n.childrenAfterGroup),o.pop()}}))}(t)}});
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/function Rn(t){var e=new Set;return t.forEach((function(t){return e.add(t)})),e}var On,Pn=Object.freeze({__proto__:null,convertToSet:Rn}),Sn=function(){return(Sn=Object.assign||function(t){for(var e,o=1,n=arguments.length;o<n;o++)for(var i in e=arguments[o])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)},bn=Sn(Sn(Sn(Sn(Sn(Sn(Sn(Sn(Sn(Sn(Sn(Sn(Sn(Sn(Sn(Sn(Sn(Sn(Sn(Sn({},Do),Zo),D),Ge),Re),en),Po),It),J),ln),p),dn),vn),mn),wn),ie),k),En),Pn),Xt),Dn=function(){function t(t,e){void 0===t&&(t=0),void 0===e&&(e=1),this.nextValue=t,this.step=e}return t.prototype.next=function(){var t=this.nextValue;return this.nextValue+=this.step,t},t.prototype.peek=function(){return this.nextValue},t.prototype.skip=function(t){this.nextValue+=t},t}();
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/!function(t){t[t.IN_PROGRESS=0]="IN_PROGRESS",t[t.RESOLVED=1]="RESOLVED"}(On||(On={}));var An,Tn=function(){function t(t){var e=this;this.status=On.IN_PROGRESS,this.resolution=null,this.waiters=[],t((function(t){return e.onDone(t)}),(function(t){return e.onReject(t)}))}return t.all=function(e){return new t((function(t){var o=e.length,n=new Array(o);P(e,(function(e,i){e.then((function(e){n[i]=e,0===--o&&t(n)}))}))}))},t.resolve=function(e){return void 0===e&&(e=null),new t((function(t){return t(e)}))},t.prototype.then=function(e){var o=this;return new t((function(t){o.status===On.RESOLVED?t(e(o.resolution)):o.waiters.push((function(o){return t(e(o))}))}))},t.prototype.resolveNow=function(t,e){return this.status===On.RESOLVED?e(this.resolution):t},t.prototype.onDone=function(t){this.status=On.RESOLVED,this.resolution=t,P(this.waiters,(function(e){return e(t)}))},t.prototype.onReject=function(t){console.warn("TBI")},t}(),_n=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Fn=function(){return(Fn=Object.assign||function(t){for(var e,o=1,n=arguments.length;o<n;o++)for(var i in e=arguments[o])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)},Nn=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s};
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/!function(t){t[t.NOTHING=0]="NOTHING",t[t.WAITING_TO_SHOW=1]="WAITING_TO_SHOW",t[t.SHOWING=2]="SHOWING"}(An||(An={}));var Ln=function(t){function o(e){var o=t.call(this)||this;return o.DEFAULT_HIDE_TOOLTIP_TIMEOUT=1e4,o.SHOW_QUICK_TOOLTIP_DIFF=1e3,o.FADE_OUT_TOOLTIP_TIMEOUT=1e3,o.state=An.NOTHING,o.tooltipInstanceCount=0,o.tooltipMouseTrack=!1,o.parentComp=e,o}return _n(o,t),o.prototype.postConstruct=function(){this.tooltipShowDelay=this.gridOptionsWrapper.getTooltipShowDelay()||2e3,this.tooltipMouseTrack=this.gridOptionsWrapper.isTooltipMouseTrack();var t=this.parentComp.getGui();this.addManagedListener(t,"mouseenter",this.onMouseEnter.bind(this)),this.addManagedListener(t,"mouseleave",this.onMouseLeave.bind(this)),this.addManagedListener(t,"mousemove",this.onMouseMove.bind(this)),this.addManagedListener(t,"mousedown",this.onMouseDown.bind(this)),this.addManagedListener(t,"keydown",this.onKeyDown.bind(this))},o.prototype.destroy=function(){this.setToDoNothing(),t.prototype.destroy.call(this)},o.prototype.onMouseEnter=function(t){if(this.state==An.NOTHING){var e=this.isLastTooltipHiddenRecently()?200:this.tooltipShowDelay;this.showTooltipTimeoutId=window.setTimeout(this.showTooltip.bind(this),e),this.lastMouseEvent=t,this.state=An.WAITING_TO_SHOW}},o.prototype.onMouseLeave=function(){this.setToDoNothing()},o.prototype.onKeyDown=function(){this.setToDoNothing()},o.prototype.setToDoNothing=function(){this.state===An.SHOWING&&this.hideTooltip(),this.clearTimeouts(),this.state=An.NOTHING},o.prototype.onMouseMove=function(t){this.lastMouseEvent=t,this.tooltipMouseTrack&&this.state===An.SHOWING&&this.tooltipComp&&this.positionTooltipUnderLastMouseEvent()},o.prototype.onMouseDown=function(){this.setToDoNothing()},o.prototype.hideTooltip=function(){this.tooltipComp&&(this.destroyTooltipComp(),o.lastTooltipHideTime=(new Date).getTime()),this.state=An.NOTHING},o.prototype.destroyTooltipComp=function(){var t=this;Me(this.tooltipComp.getGui(),"ag-tooltip-hiding");var e=this.tooltipPopupDestroyFunc,o=this.tooltipComp;window.setTimeout((function(){e(),t.getContext().destroyBean(o)}),this.FADE_OUT_TOOLTIP_TIMEOUT),this.tooltipPopupDestroyFunc=void 0,this.tooltipComp=void 0},o.prototype.isLastTooltipHiddenRecently=function(){return(new Date).getTime()-o.lastTooltipHideTime<this.SHOW_QUICK_TOOLTIP_DIFF},o.prototype.showTooltip=function(){var t=Fn({api:this.gridApi,columnApi:this.columnApi,context:this.gridOptionsWrapper.getContext()},this.parentComp.getTooltipParams());if(e(t.value)){this.state=An.SHOWING,this.tooltipInstanceCount++;var o=this.newTooltipComponentCallback.bind(this,this.tooltipInstanceCount);this.userComponentFactory.newTooltipComponent(t).then(o)}else this.setToDoNothing()},o.prototype.newTooltipComponentCallback=function(t,e){if(this.state!==An.SHOWING||this.tooltipInstanceCount!==t)this.getContext().destroyBean(e);else{var o=e.getGui();this.tooltipComp=e,He(o,"ag-tooltip")||Me(o,"ag-tooltip-custom");var n=this.popupService.addPopup({eChild:o});n&&(this.tooltipPopupDestroyFunc=n.hideFunc),this.positionTooltipUnderLastMouseEvent(),this.hideTooltipTimeoutId=window.setTimeout(this.hideTooltip.bind(this),this.DEFAULT_HIDE_TOOLTIP_TIMEOUT)}},o.prototype.positionTooltipUnderLastMouseEvent=function(){this.popupService.positionPopupUnderMouseEvent({type:"tooltip",mouseEvent:this.lastMouseEvent,ePopup:this.tooltipComp.getGui(),nudgeY:18})},o.prototype.clearTimeouts=function(){this.showTooltipTimeoutId&&(window.clearTimeout(this.showTooltipTimeoutId),this.showTooltipTimeoutId=void 0),this.hideTooltipTimeoutId&&(window.clearTimeout(this.hideTooltipTimeoutId),this.hideTooltipTimeoutId=void 0)},Nn([it("popupService")],o.prototype,"popupService",void 0),Nn([it("userComponentFactory")],o.prototype,"userComponentFactory",void 0),Nn([it("columnApi")],o.prototype,"columnApi",void 0),Nn([it("gridApi")],o.prototype,"gridApi",void 0),Nn([et],o.prototype,"postConstruct",null),o}(Mt),In=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Gn=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Mn=new Dn,xn=function(t){function e(e){var o=t.call(this)||this;return o.annotatedGuiListeners=[],o.displayed=!0,o.visible=!0,o.compId=Mn.next(),o.cssClassStates={},e&&o.setTemplate(e),o}return In(e,t),e.prototype.preConstructOnComponent=function(){this.usingBrowserTooltips=this.gridOptionsWrapper.isEnableBrowserTooltips()},e.prototype.getCompId=function(){return this.compId},e.prototype.getTooltipParams=function(){return{value:this.tooltipText,location:"UNKNOWN"}},e.prototype.setTooltip=function(t){var e=this;this.tooltipText!=t&&(this.tooltipText&&(e.usingBrowserTooltips?e.getGui().removeAttribute("title"):e.tooltipFeature=e.destroyBean(e.tooltipFeature)),this.tooltipText=t,this.tooltipText&&(e.usingBrowserTooltips?e.getGui().setAttribute("title",e.tooltipText):e.tooltipFeature=e.createBean(new Ln(e))))},e.prototype.createChildComponentsFromTags=function(t,e){var o=this;P(wo(t.childNodes),(function(n){if(n instanceof HTMLElement){var i=o.createComponentFromElement(n,(function(t){o.copyAttributesFromNode(n,t.getGui())}),e);if(i){if(i.addItems&&n.children.length){o.createChildComponentsFromTags(n,e);var r=Array.prototype.slice.call(n.children);i.addItems(r)}o.swapComponentForNode(i,t,n)}else n.childNodes&&o.createChildComponentsFromTags(n,e)}}))},e.prototype.createComponentFromElement=function(t,e,o){var n=t.nodeName,i=o?o[t.getAttribute("ref")]:void 0,r=this.agStackComponentsRegistry.getComponentClass(n);if(r){var s=new r(i);return this.createBean(s,null,e),s}return null},e.prototype.copyAttributesFromNode=function(t,e){Eo(t.attributes,(function(t,o){return e.setAttribute(t,o)}))},e.prototype.swapComponentForNode=function(t,e,o){var n=t.getGui();e.replaceChild(n,o),e.insertBefore(document.createComment(o.nodeName),n),this.addDestroyFunc(this.destroyBean.bind(this,t)),this.swapInComponentForQuerySelectors(t,o)},e.prototype.swapInComponentForQuerySelectors=function(t,e){var o=this;this.iterateOverQuerySelectors((function(n){o[n.attributeName]===e&&(o[n.attributeName]=t)}))},e.prototype.iterateOverQuerySelectors=function(t){for(var e=Object.getPrototypeOf(this);null!=e;){var o=e.__agComponentMetaData,n=K(e.constructor);o&&o[n]&&o[n].querySelectors&&P(o[n].querySelectors,(function(e){return t(e)})),e=Object.getPrototypeOf(e)}},e.prototype.setTemplate=function(t,e){var o=oo(t);this.setTemplateFromElement(o,e)},e.prototype.setTemplateFromElement=function(t,e){this.eGui=t,this.eGui.__agComponent=this,this.addAnnotatedGuiEventListeners(),this.wireQuerySelectors(),this.getContext()&&this.createChildComponentsFromTags(this.getGui(),e)},e.prototype.createChildComponentsPreConstruct=function(){this.getGui()&&this.createChildComponentsFromTags(this.getGui())},e.prototype.wireQuerySelectors=function(){var t=this;if(this.eGui){var e=this;this.iterateOverQuerySelectors((function(o){var n=t.eGui.querySelector(o.querySelector);n&&(e[o.attributeName]=n.__agComponent||n)}))}},e.prototype.addAnnotatedGuiEventListeners=function(){var t=this;if(this.removeAnnotatedGuiEventListeners(),this.eGui){var e=this.getAgComponentMetaData("guiListenerMethods");e&&(this.annotatedGuiListeners||(this.annotatedGuiListeners=[]),e.forEach((function(e){var o=t.getRefElement(e.ref);if(o){var n=t[e.methodName].bind(t);o.addEventListener(e.eventName,n),t.annotatedGuiListeners.push({eventName:e.eventName,listener:n,element:o})}})))}},e.prototype.addAnnotatedGridEventListeners=function(){var t=this,e=this.getAgComponentMetaData("gridListenerMethods");e&&e.forEach((function(e){var o=t[e.methodName].bind(t);t.addManagedListener(t.eventService,e.eventName,o)}))},e.prototype.getAgComponentMetaData=function(t){for(var e=[],o=Object.getPrototypeOf(this);null!=o;){var n=o.__agComponentMetaData,i=K(o.constructor);n&&n[i]&&n[i][t]&&(e=e.concat(n[i][t])),o=Object.getPrototypeOf(o)}return e},e.prototype.removeAnnotatedGuiEventListeners=function(){this.annotatedGuiListeners&&(P(this.annotatedGuiListeners,(function(t){t.element.removeEventListener(t.eventName,t.listener)})),this.annotatedGuiListeners=[])},e.prototype.getGui=function(){return this.eGui},e.prototype.getFocusableElement=function(){return this.eGui},e.prototype.setParentComponent=function(t){this.parentComponent=t},e.prototype.getParentComponent=function(){return this.parentComponent},e.prototype.setGui=function(t){this.eGui=t},e.prototype.queryForHtmlElement=function(t){return this.eGui.querySelector(t)},e.prototype.queryForHtmlInputElement=function(t){return this.eGui.querySelector(t)},e.prototype.appendChild=function(t,e){if(e||(e=this.eGui),null!=t)if(Co(t))e.appendChild(t);else{var o=t;e.appendChild(o.getGui()),this.addDestroyFunc(this.destroyBean.bind(this,o))}},e.prototype.isDisplayed=function(){return this.displayed},e.prototype.setVisible=function(t){t!==this.visible&&(this.visible=t,Be(this.eGui,t))},e.prototype.setDisplayed=function(t){if(t!==this.displayed){this.displayed=t,ke(this.eGui,t);var o={type:e.EVENT_DISPLAYED_CHANGED,visible:this.displayed};this.dispatchEvent(o)}},e.prototype.destroy=function(){this.removeAnnotatedGuiEventListeners(),this.tooltipFeature&&(this.tooltipFeature=this.destroyBean(this.tooltipFeature)),t.prototype.destroy.call(this)},e.prototype.addGuiEventListener=function(t,e){var o=this;this.eGui.addEventListener(t,e),this.addDestroyFunc((function(){return o.eGui.removeEventListener(t,e)}))},e.prototype.addCssClass=function(t){!0!==this.cssClassStates[t]&&(Me(this.eGui,t),this.cssClassStates[t]=!0)},e.prototype.removeCssClass=function(t){!1!==this.cssClassStates[t]&&(xe(this.eGui,t),this.cssClassStates[t]=!1)},e.prototype.addOrRemoveCssClass=function(t,e){this.cssClassStates[t]!==e&&(Ve(this.eGui,t,e),this.cssClassStates[t]=e)},e.prototype.getAttribute=function(t){var e=this.eGui;return e?e.getAttribute(t):null},e.prototype.getRefElement=function(t){return this.queryForHtmlElement('[ref="'+t+'"]')},e.EVENT_DISPLAYED_CHANGED="displayedChanged",Gn([it("agStackComponentsRegistry")],e.prototype,"agStackComponentsRegistry",void 0),Gn([tt],e.prototype,"preConstructOnComponent",null),Gn([tt],e.prototype,"createChildComponentsPreConstruct",null),Gn([et],e.prototype,"addAnnotatedGridEventListeners",null),e}(Mt),Vn=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Hn=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Vn(e,t),e.prototype.isPopup=function(){return!0},e.prototype.setParentComponent=function(e){Me(e.getGui(),"ag-has-popup"),t.prototype.setParentComponent.call(this,e)},e.prototype.destroy=function(){var e=this.parentComponent;e&&e.isAlive()&&xe(e.getGui(),"ag-has-popup"),t.prototype.destroy.call(this)},e}(xn);
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
function Wn(t){return kn.bind(this,"[ref="+t+"]")}function kn(t,e,o,n){null!==t?"number"!=typeof n?function(t,e,o){var n=function(t,e){t.__agComponentMetaData||(t.__agComponentMetaData={});t.__agComponentMetaData[e]||(t.__agComponentMetaData[e]={});return t.__agComponentMetaData[e]}
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/(t,K(t.constructor));n[e]||(n[e]=[]);n[e].push(o)}(e,"querySelectors",{attributeName:o,querySelector:t}):console.error("AG Grid: QuerySelector should be on an attribute"):console.error("AG Grid: QuerySelector selector should not be null")}var Bn,jn=function(){function t(){}return t.BACKSPACE=8,t.TAB=9,t.ENTER=13,t.SHIFT=16,t.ESCAPE=27,t.SPACE=32,t.LEFT=37,t.UP=38,t.RIGHT=39,t.DOWN=40,t.DELETE=46,t.A=65,t.C=67,t.V=86,t.D=68,t.Z=90,t.Y=89,t.F2=113,t.PAGE_UP=33,t.PAGE_DOWN=34,t.PAGE_HOME=36,t.PAGE_END=35,t}(),Un=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),zn=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Kn=function(t){function o(){return t.call(this,o.TEMPLATE)||this}return Un(o,t),o.prototype.init=function(t){this.params=t;var o,n=this.eInput;t.cellStartedEdit?(this.focusAfterAttached=!0,t.keyPress===jn.BACKSPACE||t.keyPress===jn.DELETE?o="":t.charPress?o=t.charPress:(o=this.getStartValue(t),t.keyPress!==jn.F2&&(this.highlightAllOnFocus=!0))):(this.focusAfterAttached=!1,o=this.getStartValue(t)),e(o)&&n.setValue(o,!0),this.addManagedListener(n.getGui(),"keydown",(function(t){var e=t.keyCode;e!==jn.PAGE_UP&&e!==jn.PAGE_DOWN||t.preventDefault()}))},o.prototype.afterGuiAttached=function(){var t=this.gridOptionsWrapper.getLocaleTextFunc(),o=this.eInput;if(o.setInputAriaLabel(t("ariaInputEditor","Input Editor")),this.focusAfterAttached){Se()||o.getFocusableElement().focus();var n=o.getInputElement();if(this.highlightAllOnFocus)n.select();else{var i=o.getValue(),r=e(i)&&i.length||0;r&&n.setSelectionRange(r,r)}}},o.prototype.focusIn=function(){var t=this.eInput,e=t.getFocusableElement(),o=t.getInputElement();e.focus(),o.select()},o.prototype.focusOut=function(){var t=this.eInput.getInputElement();Oe()&&t.setSelectionRange(0,0)},o.prototype.getValue=function(){var t=this.eInput;return this.params.parseValue(t.getValue())},o.prototype.getStartValue=function(t){return t.useFormatter||t.column.getColDef().refData?t.formatValue(t.value):t.value},o.prototype.isPopup=function(){return!1},o.TEMPLATE='<div class="ag-cell-edit-wrapper"><ag-input-text-field class="ag-cell-editor" ref="eInput"></ag-input-text-field></div>',zn([Wn("eInput")],o.prototype,"eInput",void 0),o}(Hn),Yn=function(){function t(t,e,o,n){var i=this;this.alive=!0,this.context=t,e.newDateComponent(o).then((function(e){i.alive?(i.dateComp=e,e&&(n.appendChild(e.getGui()),e.afterGuiAttached&&e.afterGuiAttached(),i.tempValue&&e.setDate(i.tempValue))):t.destroyBean(e)}))}return t.prototype.destroy=function(){this.alive=!1,this.dateComp=this.context.destroyBean(this.dateComp)},t.prototype.getDate=function(){return this.dateComp?this.dateComp.getDate():this.tempValue},t.prototype.setDate=function(t){this.dateComp?this.dateComp.setDate(t):this.tempValue=t},t.prototype.setInputPlaceholder=function(t){this.dateComp&&this.dateComp.setInputPlaceholder&&this.dateComp.setInputPlaceholder(t)},t.prototype.setInputAriaLabel=function(t){this.dateComp&&this.dateComp.setInputAriaLabel&&this.dateComp.setInputAriaLabel(t)},t.prototype.afterGuiAttached=function(t){this.dateComp&&"function"==typeof this.dateComp.afterGuiAttached&&this.dateComp.afterGuiAttached(t)},t}(),qn=function(){function t(){this.customFilterOptions={}}return t.prototype.init=function(t,e){this.filterOptions=t.filterOptions||e,this.mapCustomOptions(),this.selectDefaultItem(t)},t.prototype.getFilterOptions=function(){return this.filterOptions},t.prototype.mapCustomOptions=function(){var t=this;this.filterOptions&&this.filterOptions.forEach((function(e){if("string"!=typeof e){R(["displayKey","displayName","test"],(function(t){return!!e[t]||(console.warn("AG Grid: ignoring FilterOptionDef as it doesn't contain a '"+t+"'"),!1)}))&&(t.customFilterOptions[e.displayKey]=e)}}))},t.prototype.selectDefaultItem=function(t){if(t.defaultOption)this.defaultOption=t.defaultOption;else if(this.filterOptions.length>=1){var e=this.filterOptions[0];"string"==typeof e?this.defaultOption=e:e.displayKey?this.defaultOption=e.displayKey:console.warn("AG Grid: invalid FilterOptionDef supplied as it doesn't contain a 'displayKey'")}else console.warn("AG Grid: no filter options for filter")},t.prototype.getDefaultOption=function(){return this.defaultOption},t.prototype.getCustomOption=function(t){return this.customFilterOptions[t]},t}(),Xn={applyFilter:"Apply",clearFilter:"Clear",resetFilter:"Reset",cancelFilter:"Cancel",textFilter:"Text Filter",numberFilter:"Number Filter",dateFilter:"Date Filter",setFilter:"Set Filter",filterOoo:"Filter...",empty:"Choose One",equals:"Equals",notEqual:"Not equal",lessThan:"Less than",greaterThan:"Greater than",inRange:"In range",inRangeStart:"From",inRangeEnd:"To",lessThanOrEqual:"Less than or equals",greaterThanOrEqual:"Greater than or equals",contains:"Contains",notContains:"Not contains",startsWith:"Starts with",endsWith:"Ends with",andCondition:"AND",orCondition:"OR",dateFormatOoo:"yyyy-mm-dd"},Qn=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),$n=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Zn=function(t){function e(e,o){void 0===o&&(o=!1);var n=t.call(this,e)||this;return n.isFocusableContainer=o,n.skipTabGuardFocus=!1,n}return Qn(e,t),e.prototype.postConstruct=function(){var t=this,o=this.getFocusableElement();o&&(Me(o,e.FOCUS_MANAGED_CLASS),this.isFocusableContainer&&(this.topTabGuard=this.createTabGuard("top"),this.bottomTabGuard=this.createTabGuard("bottom"),this.addTabGuards(),this.activateTabGuards(),this.forEachTabGuard((function(e){return t.addManagedListener(e,"focus",t.onFocus.bind(t))}))),this.addKeyDownListeners(o),this.addManagedListener(o,"focusin",this.onFocusIn.bind(this)),this.addManagedListener(o,"focusout",this.onFocusOut.bind(this)))},e.prototype.focusInnerElement=function(t){void 0===t&&(t=!1);var e=this.focusController.findFocusableElements(this.getFocusableElement());this.isFocusableContainer&&this.tabGuardsAreActive()&&(e.splice(0,1),e.splice(e.length-1,1)),e.length&&e[t?e.length-1:0].focus()},e.prototype.onTabKeyDown=function(t){var e=this;if(!t.defaultPrevented){var o=this.tabGuardsAreActive();this.isFocusableContainer&&o&&this.deactivateTabGuards();var n=this.focusController.findNextFocusableElement(this.getFocusableElement(),!1,t.shiftKey);this.isFocusableContainer&&o&&setTimeout((function(){return e.activateTabGuards()}),0),n&&(n.focus(),t.preventDefault())}},e.prototype.onFocusIn=function(t){this.isFocusableContainer&&this.deactivateTabGuards()},e.prototype.onFocusOut=function(t){this.isFocusableContainer&&!this.getFocusableElement().contains(t.relatedTarget)&&this.activateTabGuards()},e.prototype.forceFocusOutOfContainer=function(t){if(void 0===t&&(t=!1),this.isFocusableContainer){this.activateTabGuards(),this.skipTabGuardFocus=!0;var e=t?this.topTabGuard:this.bottomTabGuard;e&&e.focus()}},e.prototype.appendChild=function(e,o){if(this.isFocusableContainer){Co(e)||(e=e.getGui());var n=this.bottomTabGuard;n?n.insertAdjacentElement("beforebegin",e):t.prototype.appendChild.call(this,e,o)}else t.prototype.appendChild.call(this,e,o)},e.prototype.createTabGuard=function(t){var e=document.createElement("div");return e.classList.add("ag-tab-guard"),e.classList.add("ag-tab-guard-"+t),e.setAttribute("role","presentation"),e},e.prototype.addTabGuards=function(){var t=this.getFocusableElement();t.insertAdjacentElement("afterbegin",this.topTabGuard),t.insertAdjacentElement("beforeend",this.bottomTabGuard)},e.prototype.forEachTabGuard=function(t){this.topTabGuard&&t(this.topTabGuard),this.bottomTabGuard&&t(this.bottomTabGuard)},e.prototype.addKeyDownListeners=function(t){var e=this;this.addManagedListener(t,"keydown",(function(t){t.defaultPrevented||Pt(t)||(e.shouldStopEventPropagation(t)?Ot(t):t.keyCode===jn.TAB?e.onTabKeyDown(t):e.handleKeyDown&&e.handleKeyDown(t))}))},e.prototype.shouldStopEventPropagation=function(t){return!1},e.prototype.onFocus=function(t){this.skipTabGuardFocus?this.skipTabGuardFocus=!1:this.focusInnerElement(t.target===this.bottomTabGuard)},e.prototype.activateTabGuards=function(){this.forEachTabGuard((function(t){return t.setAttribute("tabIndex","0")}))},e.prototype.deactivateTabGuards=function(){this.forEachTabGuard((function(t){return t.removeAttribute("tabIndex")}))},e.prototype.tabGuardsAreActive=function(){return!!this.topTabGuard&&this.topTabGuard.hasAttribute("tabIndex")},e.prototype.clearGui=function(){var t=this.tabGuardsAreActive();Je(this.getFocusableElement()),this.isFocusableContainer&&(this.addTabGuards(),t&&this.activateTabGuards())},e.FOCUS_MANAGED_CLASS="ag-focus-managed",$n([it("focusController")],e.prototype,"focusController",void 0),$n([et],e.prototype,"postConstruct",null),e}(xn),Jn=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),ti=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},ei=function(t){function e(e){var o=t.call(this)||this;return o.filterNameKey=e,o.applyActive=!1,o.hidePopup=null,o.appliedModel=null,o}return Jn(e,t),e.prototype.getFilterTitle=function(){return this.translate(this.filterNameKey)},e.prototype.onFilterChanged=function(){console.warn("AG Grid: you should not call onFilterChanged() directly on the filter, please call\n gridApi.onFilterChanged() instead. onFilterChanged is not part of the exposed filter interface (it was\n a method that existed on an old version of the filters that was not intended for public use."),this.providedFilterParams.filterChangedCallback()},e.prototype.isFilterActive=function(){return!!this.appliedModel},e.prototype.postConstruct=function(){this.resetTemplate(),t.prototype.postConstruct.call(this)},e.prototype.resetTemplate=function(t){var e='\n <div class="ag-filter-wrapper">\n <div class="ag-filter-body-wrapper ag-'+this.getCssIdentifier()+'-body-wrapper">\n '+this.createBodyTemplate()+"\n </div>\n </div>";this.setTemplate(e,t)},e.prototype.init=function(t){var e=this;this.setParams(t),this.resetUiToDefaults(!0).then((function(){e.updateUiVisibility(),e.setupOnBtApplyDebounce()}))},e.prototype.setParams=function(t){if(e.checkForDeprecatedParams(t),this.providedFilterParams=t,"keep"===t.newRowsAction)this.newRowsActionKeep=!0;else if("clear"===t.newRowsAction)this.newRowsActionKeep=!1;else{var o=[ht.ROW_MODEL_TYPE_SERVER_SIDE,ht.ROW_MODEL_TYPE_INFINITE];this.newRowsActionKeep=o.indexOf(this.rowModel.getType())>=0}this.applyActive=e.isUseApplyButton(t),this.createButtonPanel()},e.prototype.createButtonPanel=function(){var t=this,e=this.providedFilterParams.buttons;if(e&&!(e.length<1)){var o=document.createElement("div");Me(o,"ag-filter-apply-panel");Rn(e).forEach((function(e){return function(e){var n,i;switch(e){case"apply":n=t.translate("applyFilter"),i=function(e){return t.onBtApply(!1,!1,e)};break;case"clear":n=t.translate("clearFilter"),i=function(){return t.onBtClear()};break;case"reset":n=t.translate("resetFilter"),i=function(){return t.onBtReset()};break;case"cancel":n=t.translate("cancelFilter"),i=function(e){t.onBtCancel(e)};break;default:return void console.warn("Unknown button type specified")}var r=oo('<button\n type="button"\n ref="'+e+'FilterButton"\n class="ag-standard-button ag-filter-apply-panel-button"\n >'+n+"\n </button>");o.appendChild(r),t.addManagedListener(r,"click",i)}(e)})),this.getGui().appendChild(o)}},e.checkForDeprecatedParams=function(t){var e=t.buttons||[];if(!(e.length>0)){var o=t.applyButton,n=t.resetButton;t.clearButton&&(console.warn("AG Grid: as of AG Grid v23.2, filterParams.clearButton is deprecated. Please use filterParams.buttons instead"),e.push("clear")),n&&(console.warn("AG Grid: as of AG Grid v23.2, filterParams.resetButton is deprecated. Please use filterParams.buttons instead"),e.push("reset")),o&&(console.warn("AG Grid: as of AG Grid v23.2, filterParams.applyButton is deprecated. Please use filterParams.buttons instead"),e.push("apply")),t.apply&&(console.warn("AG Grid: as of AG Grid v21, filterParams.apply is deprecated. Please use filterParams.buttons instead"),e.push("apply")),t.buttons=e}},e.prototype.getDefaultDebounceMs=function(){return 0},e.prototype.setupOnBtApplyDebounce=function(){var t=e.getDebounceMs(this.providedFilterParams,this.getDefaultDebounceMs());this.onBtApplyDebounce=$(this.onBtApply.bind(this),t)},e.prototype.getModel=function(){return this.appliedModel},e.prototype.setModel=function(t){var e=this;return(t?this.setModelIntoUi(t):this.resetUiToDefaults()).then((function(){e.updateUiVisibility(),e.applyModel()}))},e.prototype.onBtCancel=function(t){var e=this;this.setModelIntoUi(this.getModel()).then((function(){e.onUiChanged(!1,"prevent"),e.providedFilterParams.closeOnApply&&e.close(t)}))},e.prototype.onBtClear=function(){var t=this;this.resetUiToDefaults().then((function(){return t.onUiChanged()}))},e.prototype.onBtReset=function(){this.onBtClear(),this.onBtApply()},e.prototype.applyModel=function(){var t=this.getModelFromUi();if(!this.isModelValid(t))return!1;var e=this.appliedModel;return this.appliedModel=t,!this.areModelsEqual(e,t)},e.prototype.isModelValid=function(t){return!0},e.prototype.onBtApply=function(t,e,o){void 0===t&&(t=!1),void 0===e&&(e=!1),this.applyModel()&&this.providedFilterParams.filterChangedCallback({afterFloatingFilter:t,afterDataChange:e}),this.providedFilterParams.closeOnApply&&this.applyActive&&!t&&!e&&this.close(o)},e.prototype.onNewRowsLoaded=function(){var t=this;this.newRowsActionKeep||this.resetUiToDefaults().then((function(){return t.appliedModel=null}))},e.prototype.close=function(t){if(this.hidePopup){var e,o=t,n=o&&o.key;"Enter"!==n&&"Space"!==n||(e={keyboardEvent:o}),this.hidePopup(e),this.hidePopup=null}},e.prototype.isNewRowsActionKeep=function(){return this.newRowsActionKeep},e.prototype.onUiChanged=function(t,e){if(void 0===t&&(t=!1),this.updateUiVisibility(),this.providedFilterParams.filterModifiedCallback(),this.applyActive){var o=this.isModelValid(this.getModelFromUi());je(this.getRefElement("applyFilterButton"),!o)}t&&!e||"immediately"===e?this.onBtApply(t):(this.applyActive||e)&&"debounce"!==e||this.onBtApplyDebounce()},e.prototype.afterGuiAttached=function(t){null!=t&&(this.hidePopup=t.hidePopup)},e.getDebounceMs=function(t,o){return e.isUseApplyButton(t)?(null!=t.debounceMs&&console.warn("AG Grid: debounceMs is ignored when apply button is present"),0):null!=t.debounceMs?t.debounceMs:o},e.isUseApplyButton=function(t){return e.checkForDeprecatedParams(t),!!t.buttons&&t.buttons.indexOf("apply")>=0},e.prototype.destroy=function(){this.hidePopup=null,t.prototype.destroy.call(this)},e.prototype.translate=function(t){return this.gridOptionsWrapper.getLocaleTextFunc()(t,Xn[t])},ti([it("rowModel")],e.prototype,"rowModel",void 0),ti([et],e.prototype,"postConstruct",null),e}(Zn),oi=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),ni=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s};
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/!function(t){t[t.One=0]="One",t[t.Two=1]="Two"}(Bn||(Bn={}));var ii,ri=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return oi(e,t),e.prototype.showValueFrom=function(t){return!this.doesFilterHaveHiddenInput(t)&&t!==e.EMPTY},e.prototype.showValueTo=function(t){return t===e.IN_RANGE},e.prototype.onFloatingFilterChanged=function(t,e){this.setTypeFromFloatingFilter(t),this.setValueFromFloatingFilter(e),this.onUiChanged(!0)},e.prototype.setTypeFromFloatingFilter=function(t){this.eType1.setValue(t),this.eType2.setValue(this.optionsFactory.getDefaultOption()),(this.isDefaultOperator("AND")?this.eJoinOperatorAnd:this.eJoinOperatorOr).setValue(!0)},e.prototype.getModelFromUi=function(){return this.isConditionUiComplete(Bn.One)?this.isAllowTwoConditions()&&this.isConditionUiComplete(Bn.Two)?{filterType:this.getFilterType(),operator:this.getJoinOperator(),condition1:this.createCondition(Bn.One),condition2:this.createCondition(Bn.Two)}:this.createCondition(Bn.One):null},e.prototype.getCondition1Type=function(){return this.eType1.getValue()},e.prototype.getCondition2Type=function(){return this.eType2.getValue()},e.prototype.getJoinOperator=function(){return!0===this.eJoinOperatorOr.getValue()?"OR":"AND"},e.prototype.areModelsEqual=function(t,e){if(!t&&!e)return!0;if(!t&&e||t&&!e)return!1;var o,n=!t.operator,i=!e.operator;if(!n&&i||n&&!i)return!1;if(n){var r=t,s=e;o=this.areSimpleModelsEqual(r,s)}else{var a=t,l=e;o=a.operator===l.operator&&this.areSimpleModelsEqual(a.condition1,l.condition1)&&this.areSimpleModelsEqual(a.condition2,l.condition2)}return o},e.prototype.setModelIntoUi=function(t){if(t.operator){var e=t,o="OR"===e.operator;this.eJoinOperatorAnd.setValue(!o),this.eJoinOperatorOr.setValue(o),this.eType1.setValue(e.condition1.type),this.eType2.setValue(e.condition2.type),this.setConditionIntoUi(e.condition1,Bn.One),this.setConditionIntoUi(e.condition2,Bn.Two)}else{var n=t;this.eJoinOperatorAnd.setValue(this.isDefaultOperator("AND")),this.eJoinOperatorOr.setValue(this.isDefaultOperator("OR")),this.eType1.setValue(n.type),this.eType2.setValue(this.optionsFactory.getDefaultOption()),this.setConditionIntoUi(n,Bn.One),this.setConditionIntoUi(null,Bn.Two)}return Tn.resolve()},e.prototype.doesFilterPass=function(t){var e=this,o=this.getModel();if(null==o)return!0;var n=o.operator,i=[];if(n){var r=o;i.push(r.condition1,r.condition2)}else i.push(o);return(n&&"OR"===n?O:R)(i,(function(o){return e.individualConditionPasses(t,o)}))},e.prototype.setParams=function(e){t.prototype.setParams.call(this,e),this.optionsFactory=new qn,this.optionsFactory.init(e,this.getDefaultFilterOptions()),this.allowTwoConditions=!e.suppressAndOrCondition,this.alwaysShowBothConditions=!!e.alwaysShowBothConditions,this.defaultJoinOperator=this.getDefaultJoinOperator(e.defaultJoinOperator),this.putOptionsIntoDropdown(),this.addChangedListeners()},e.prototype.getDefaultJoinOperator=function(t){return C(["AND","OR"],t)?t:"AND"},e.prototype.putOptionsIntoDropdown=function(){var t=this,e=this.optionsFactory.getFilterOptions();P(e,(function(e){var o,n;if("string"==typeof e)o=e,n=t.translate(o);else{o=e.displayKey;var i=t.optionsFactory.getCustomOption(o);n=i?t.gridOptionsWrapper.getLocaleTextFunc()(i.displayKey,i.displayName):t.translate(o)}var r=function(){return{value:o,text:n}};t.eType1.addOption(r()),t.eType2.addOption(r())}));var o=e.length<=1;this.eType1.setDisabled(o),this.eType2.setDisabled(o)},e.prototype.isAllowTwoConditions=function(){return this.allowTwoConditions},e.prototype.createBodyTemplate=function(){return'\n <ag-select class="ag-filter-select" ref="eOptions1"></ag-select>\n '+this.createValueTemplate(Bn.One)+'\n <div class="ag-filter-condition" ref="eJoinOperatorPanel">\n <ag-radio-button ref="eJoinOperatorAnd" class="ag-filter-condition-operator ag-filter-condition-operator-and"></ag-radio-button>\n <ag-radio-button ref="eJoinOperatorOr" class="ag-filter-condition-operator ag-filter-condition-operator-or"></ag-radio-button>\n </div>\n <ag-select class="ag-filter-select" ref="eOptions2"></ag-select>\n '+this.createValueTemplate(Bn.Two)},e.prototype.getCssIdentifier=function(){return"simple-filter"},e.prototype.updateUiVisibility=function(){var t=this.isCondition2Enabled();this.alwaysShowBothConditions?(this.eJoinOperatorAnd.setDisabled(!t),this.eJoinOperatorOr.setDisabled(!t),this.eType2.setDisabled(!t),je(this.eCondition2Body,!t)):(ke(this.eJoinOperatorPanel,t),ke(this.eType2.getGui(),t),ke(this.eCondition2Body,t))},e.prototype.isCondition2Enabled=function(){return this.allowTwoConditions&&this.isConditionUiComplete(Bn.One)},e.prototype.resetUiToDefaults=function(t){var e=this.gridOptionsWrapper.getLocaleTextFunc()("ariaFilteringOperator","Filtering operator"),o="ag-simple-filter-and-or-"+this.getCompId(),n=this.optionsFactory.getDefaultOption();return this.eType1.setValue(n,t).setAriaLabel(e),this.eType2.setValue(n,t).setAriaLabel(e),this.eJoinOperatorAnd.setValue(this.isDefaultOperator("AND"),t).setName(o).setLabel(this.translate("andCondition")),this.eJoinOperatorOr.setValue(this.isDefaultOperator("OR"),t).setName(o).setLabel(this.translate("orCondition")),Tn.resolve()},e.prototype.isDefaultOperator=function(t){return t===this.defaultJoinOperator},e.prototype.addChangedListeners=function(){var t=this,e=function(){return t.onUiChanged()};this.eType1.onValueChange(e),this.eType2.onValueChange(e),this.eJoinOperatorOr.onValueChange(e),this.eJoinOperatorAnd.onValueChange(e)},e.prototype.doesFilterHaveHiddenInput=function(t){var e=this.optionsFactory.getCustomOption(t);return e&&e.hideFilterInput},e.EMPTY="empty",e.EQUALS="equals",e.NOT_EQUAL="notEqual",e.LESS_THAN="lessThan",e.LESS_THAN_OR_EQUAL="lessThanOrEqual",e.GREATER_THAN="greaterThan",e.GREATER_THAN_OR_EQUAL="greaterThanOrEqual",e.IN_RANGE="inRange",e.CONTAINS="contains",e.NOT_CONTAINS="notContains",e.STARTS_WITH="startsWith",e.ENDS_WITH="endsWith",ni([Wn("eOptions1")],e.prototype,"eType1",void 0),ni([Wn("eOptions2")],e.prototype,"eType2",void 0),ni([Wn("eJoinOperatorPanel")],e.prototype,"eJoinOperatorPanel",void 0),ni([Wn("eJoinOperatorAnd")],e.prototype,"eJoinOperatorAnd",void 0),ni([Wn("eJoinOperatorOr")],e.prototype,"eJoinOperatorOr",void 0),ni([Wn("eCondition1Body")],e.prototype,"eCondition1Body",void 0),ni([Wn("eCondition2Body")],e.prototype,"eCondition2Body",void 0),e}(ei),si=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),ai=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return si(e,t),e.prototype.setParams=function(e){t.prototype.setParams.call(this,e),this.scalarFilterParams=e,this.checkDeprecatedParams()},e.prototype.checkDeprecatedParams=function(){this.scalarFilterParams.nullComparator&&(console.warn("AG Grid: Since v21.0, the property filterParams.nullComparator is deprecated. Please use filterParams.includeBlanksInEquals, filterParams.includeBlanksInLessThan and filterParams.includeBlanksInGreaterThan instead."),this.scalarFilterParams.includeBlanksInEquals=this.scalarFilterParams.nullComparator.equals,this.scalarFilterParams.includeBlanksInLessThan=this.scalarFilterParams.nullComparator.lessThan,this.scalarFilterParams.includeBlanksInGreaterThan=this.scalarFilterParams.nullComparator.greaterThan)},e.prototype.individualConditionPasses=function(t,o){var n=this.scalarFilterParams.valueGetter(t.node),i=this.mapRangeFromModel(o),r=i.from,s=i.to,a=o.type,l=this.optionsFactory.getCustomOption(a);if(l&&(null!=r||l.hideFilterInput))return l.test(r,n);if(null==n){switch(a){case e.EQUALS:case e.NOT_EQUAL:if(this.scalarFilterParams.includeBlanksInEquals)return!0;break;case e.GREATER_THAN:case e.GREATER_THAN_OR_EQUAL:if(this.scalarFilterParams.includeBlanksInGreaterThan)return!0;break;case e.LESS_THAN:case e.LESS_THAN_OR_EQUAL:if(this.scalarFilterParams.includeBlanksInLessThan)return!0;break;case e.IN_RANGE:if(this.scalarFilterParams.includeBlanksInRange)return!0}return!1}var p=this.comparator(),u=p(r,n);switch(a){case e.EQUALS:return 0===u;case e.NOT_EQUAL:return 0!==u;case e.GREATER_THAN:return u>0;case e.GREATER_THAN_OR_EQUAL:return u>=0;case e.LESS_THAN:return u<0;case e.LESS_THAN_OR_EQUAL:return u<=0;case e.IN_RANGE:var c=p(s,n);return this.scalarFilterParams.inRangeInclusive?u>=0&&c<=0:u>0&&c<0;default:throw new Error("Unexpected type of filter: "+a)}},e}(ri),li=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),pi=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},ui=function(t){function e(){return t.call(this,"dateFilter")||this}return li(e,t),e.prototype.afterGuiAttached=function(e){t.prototype.afterGuiAttached.call(this,e),this.dateCondition1FromComp.afterGuiAttached(e)},e.prototype.mapRangeFromModel=function(t){return{from:tn(t.dateFrom),to:tn(t.dateTo)}},e.prototype.setValueFromFloatingFilter=function(t){this.dateCondition1FromComp.setDate(null==t?null:tn(t)),this.dateCondition1ToComp.setDate(null),this.dateCondition2FromComp.setDate(null),this.dateCondition2ToComp.setDate(null)},e.prototype.setConditionIntoUi=function(t,e){var o=t?[tn(t.dateFrom),tn(t.dateTo)]:[null,null],n=o[0],i=o[1],r=this.getFromToComponents(e),s=r[0],a=r[1];s.setDate(n),a.setDate(i)},e.prototype.resetUiToDefaults=function(e){var o=this;return t.prototype.resetUiToDefaults.call(this,e).then((function(){o.dateCondition1FromComp.setDate(null),o.dateCondition1ToComp.setDate(null),o.dateCondition2FromComp.setDate(null),o.dateCondition2ToComp.setDate(null)}))},e.prototype.comparator=function(){return this.dateFilterParams.comparator?this.dateFilterParams.comparator:this.defaultComparator.bind(this)},e.prototype.defaultComparator=function(t,e){return null==e||e<t?-1:e>t?1:0},e.prototype.setParams=function(e){t.prototype.setParams.call(this,e),this.dateFilterParams=e,this.createDateComponents()},e.prototype.createDateComponents=function(){var t=this,e=function(e){return new Yn(t.getContext(),t.userComponentFactory,{onDateChanged:function(){return t.onUiChanged()},filterParams:t.dateFilterParams},e)};this.dateCondition1FromComp=e(this.eCondition1PanelFrom),this.dateCondition1ToComp=e(this.eCondition1PanelTo),this.dateCondition2FromComp=e(this.eCondition2PanelFrom),this.dateCondition2ToComp=e(this.eCondition2PanelTo),this.addDestroyFunc((function(){t.dateCondition1FromComp.destroy(),t.dateCondition1ToComp.destroy(),t.dateCondition2FromComp.destroy(),t.dateCondition2ToComp.destroy()}))},e.prototype.getDefaultFilterOptions=function(){return e.DEFAULT_FILTER_OPTIONS},e.prototype.createValueTemplate=function(t){var e=t===Bn.One?"1":"2";return'\n <div class="ag-filter-body" ref="eCondition'+e+'Body">\n <div class="ag-filter-from ag-filter-date-from" ref="eCondition'+e+'PanelFrom"></div>\n <div class="ag-filter-to ag-filter-date-to" ref="eCondition'+e+'PanelTo"></div>\n </div>'},e.prototype.isConditionUiComplete=function(t){var e=t===Bn.One?this.getCondition1Type():this.getCondition2Type();if(e===ri.EMPTY)return!1;if(this.doesFilterHaveHiddenInput(e))return!0;var o=this.getFromToComponents(t),n=o[0],i=o[1],r=null==this.dateFilterParams.minValidYear?1e3:this.dateFilterParams.minValidYear,s=function(t){return null!=t&&t.getUTCFullYear()>r};return s(n.getDate())&&(!this.showValueTo(e)||s(i.getDate()))},e.prototype.areSimpleModelsEqual=function(t,e){return t.dateFrom===e.dateFrom&&t.dateTo===e.dateTo&&t.type===e.type},e.prototype.getFilterType=function(){return"date"},e.prototype.createCondition=function(t){var e=t===Bn.One?this.getCondition1Type():this.getCondition2Type(),o=this.getFromToComponents(t),n=o[0],i=o[1];return{dateFrom:Jo(n.getDate()),dateTo:Jo(i.getDate()),type:e,filterType:this.getFilterType()}},e.prototype.resetPlaceholder=function(){var t=this.gridOptionsWrapper.getLocaleTextFunc(),e=this.translate("dateFormatOoo"),o=t("ariaFilterValue","Filter Value");this.dateCondition1FromComp.setInputPlaceholder(e),this.dateCondition1FromComp.setInputAriaLabel(o),this.dateCondition1ToComp.setInputPlaceholder(e),this.dateCondition1ToComp.setInputAriaLabel(o),this.dateCondition2FromComp.setInputPlaceholder(e),this.dateCondition2FromComp.setInputAriaLabel(o),this.dateCondition2ToComp.setInputPlaceholder(e),this.dateCondition2ToComp.setInputAriaLabel(o)},e.prototype.updateUiVisibility=function(){t.prototype.updateUiVisibility.call(this),this.resetPlaceholder();var e=this.getCondition1Type();ke(this.eCondition1PanelFrom,this.showValueFrom(e)),ke(this.eCondition1PanelTo,this.showValueTo(e));var o=this.getCondition2Type();ke(this.eCondition2PanelFrom,this.showValueFrom(o)),ke(this.eCondition2PanelTo,this.showValueTo(o))},e.prototype.getFromToComponents=function(t){return t===Bn.One?[this.dateCondition1FromComp,this.dateCondition1ToComp]:[this.dateCondition2FromComp,this.dateCondition2ToComp]},e.DEFAULT_FILTER_OPTIONS=[ai.EQUALS,ai.GREATER_THAN,ai.LESS_THAN,ai.NOT_EQUAL,ai.IN_RANGE],pi([Wn("eCondition1PanelFrom")],e.prototype,"eCondition1PanelFrom",void 0),pi([Wn("eCondition1PanelTo")],e.prototype,"eCondition1PanelTo",void 0),pi([Wn("eCondition2PanelFrom")],e.prototype,"eCondition2PanelFrom",void 0),pi([Wn("eCondition2PanelTo")],e.prototype,"eCondition2PanelTo",void 0),pi([it("userComponentFactory")],e.prototype,"userComponentFactory",void 0),e}(ai),ci=function(){function t(t,e){var o=this;void 0===e&&(e=!1),this.destroyFuncs=[],this.touching=!1,this.eventService=new dt,this.eElement=t,this.preventMouseClick=e;var n=this.onTouchStart.bind(this),i=this.onTouchMove.bind(this),r=this.onTouchEnd.bind(this);this.eElement.addEventListener("touchstart",n,{passive:!0}),this.eElement.addEventListener("touchmove",i,{passive:!0}),this.eElement.addEventListener("touchend",r,{passive:!1}),this.destroyFuncs.push((function(){o.eElement.removeEventListener("touchstart",n,{passive:!0}),o.eElement.removeEventListener("touchmove",i,{passive:!0}),o.eElement.removeEventListener("touchend",r,{passive:!1})}))}return t.prototype.getActiveTouch=function(t){for(var e=0;e<t.length;e++){if(t[e].identifier===this.touchStart.identifier)return t[e]}return null},t.prototype.addEventListener=function(t,e){this.eventService.addEventListener(t,e)},t.prototype.removeEventListener=function(t,e){this.eventService.removeEventListener(t,e)},t.prototype.onTouchStart=function(e){var o=this;if(!this.touching){this.touchStart=e.touches[0],this.touching=!0,this.moved=!1;var n=this.touchStart;window.setTimeout((function(){var i=o.touchStart===n;if(o.touching&&i&&!o.moved){o.moved=!0;var r={type:t.EVENT_LONG_TAP,touchStart:o.touchStart,touchEvent:e};o.eventService.dispatchEvent(r)}}),500)}},t.prototype.onTouchMove=function(t){if(this.touching){var e=this.getActiveTouch(t.touches);if(e)!Cn(e,this.touchStart,4)&&(this.moved=!0)}},t.prototype.onTouchEnd=function(e){if(this.touching){if(!this.moved){var o={type:t.EVENT_TAP,touchStart:this.touchStart};this.eventService.dispatchEvent(o),this.checkForDoubleTap()}this.preventMouseClick&&e.preventDefault(),this.touching=!1}},t.prototype.checkForDoubleTap=function(){var e=(new Date).getTime();if(this.lastTapTime&&this.lastTapTime>0)if(e-this.lastTapTime>t.DOUBLE_TAP_MILLIS){var o={type:t.EVENT_DOUBLE_TAP,touchStart:this.touchStart};this.eventService.dispatchEvent(o),this.lastTapTime=null}else this.lastTapTime=e;else this.lastTapTime=e},t.prototype.destroy=function(){this.destroyFuncs.forEach((function(t){return t()}))},t.EVENT_TAP="tap",t.EVENT_DOUBLE_TAP="doubleTap",t.EVENT_LONG_TAP="longTap",t.DOUBLE_TAP_MILLIS=500,t}(),di=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),hi=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},fi=function(t){function o(){var e=null!==t&&t.apply(this,arguments)||this;return e.lastMovingChanged=0,e}return di(o,t),o.prototype.destroy=function(){t.prototype.destroy.call(this)},o.prototype.refresh=function(t){return this.params=t,this.workOutTemplate()==this.currentTemplate&&(this.workOutShowMenu()==this.currentShowMenu&&(this.workOutSort()==this.currentSort&&(this.setDisplayName(t),!0)))},o.prototype.workOutTemplate=function(){var t=c(this.params.template,o.TEMPLATE);return t=t&&t.trim?t.trim():t},o.prototype.init=function(t){this.params=t,this.currentTemplate=this.workOutTemplate(),this.setTemplate(this.currentTemplate),this.setupTap(),this.setupIcons(t.column),this.setMenu(),this.setupSort(),this.setupFilterIcon(),this.setDisplayName(t)},o.prototype.setDisplayName=function(t){if(this.currentDisplayName!=t.displayName){this.currentDisplayName=t.displayName;var e=Kt(this.currentDisplayName);this.eText&&(this.eText.innerHTML=e)}},o.prototype.setupIcons=function(t){this.addInIcon("sortAscending",this.eSortAsc,t),this.addInIcon("sortDescending",this.eSortDesc,t),this.addInIcon("sortUnSort",this.eSortNone,t),this.addInIcon("menu",this.eMenu,t),this.addInIcon("filter",this.eFilter,t)},o.prototype.addInIcon=function(t,e,o){if(null!=e){var n=cn(t,this.gridOptionsWrapper,o);n&&e.appendChild(n)}},o.prototype.setupTap=function(){var t=this,o=this.gridOptionsWrapper;if(!o.isSuppressTouch()){var n=new ci(this.getGui(),!0),i=o.isSuppressMenuHide(),r=i&&e(this.eMenu),s=r?new ci(this.eMenu,!0):n;if(this.params.enableMenu){var a=r?"EVENT_TAP":"EVENT_LONG_TAP";this.addManagedListener(s,ci[a],(function(e){o.getApi().showColumnMenuAfterMouseClick(t.params.column,e.touchStart)}))}if(this.params.enableSorting){this.addManagedListener(n,ci.EVENT_TAP,(function(e){var o=e.touchStart.target;i&&t.eMenu.contains(o)||t.sortController.progressSort(t.params.column,!1,"uiColumnSorted")}))}this.addDestroyFunc((function(){return n.destroy()})),r&&this.addDestroyFunc((function(){return s.destroy()}))}},o.prototype.workOutShowMenu=function(){var t=!this.gridOptionsWrapper.isSuppressMenuHide(),e=Ae()&&t;return this.params.enableMenu&&!e},o.prototype.setMenu=function(){var t=this;if(this.eMenu)if(this.currentShowMenu=this.workOutShowMenu(),this.currentShowMenu){var e=this.gridOptionsWrapper.isSuppressMenuHide();this.addManagedListener(this.eMenu,"click",(function(){return t.showMenu(t.eMenu)})),Ve(this.eMenu,"ag-header-menu-always-show",e)}else to(this.eMenu)},o.prototype.showMenu=function(t){t||(t=this.eMenu),this.menuFactory.showMenuAfterButtonClick(this.params.column,t)},o.prototype.removeSortIcons=function(){to(this.eSortAsc),to(this.eSortDesc),to(this.eSortNone),to(this.eSortOrder)},o.prototype.workOutSort=function(){return this.params.enableSorting},o.prototype.setupSort=function(){var t=this;if(this.currentSort=this.params.enableSorting,this.currentSort){var e=this.gridOptionsWrapper.isMultiSortKeyCtrl();this.addManagedListener(this.params.column,yt.EVENT_MOVING_CHANGED,(function(){t.lastMovingChanged=(new Date).getTime()})),this.eLabel&&this.addManagedListener(this.eLabel,"click",(function(o){var n=t.params.column.isMoving(),i=(new Date).getTime()-t.lastMovingChanged<50;if(!(n||i)){var r=e?o.ctrlKey||o.metaKey:o.shiftKey;t.params.progressSort(r)}})),this.addManagedListener(this.params.column,yt.EVENT_SORT_CHANGED,this.onSortChanged.bind(this)),this.onSortChanged(),this.addManagedListener(this.eventService,Wt.EVENT_SORT_CHANGED,this.setMultiSortOrder.bind(this)),this.setMultiSortOrder()}else this.removeSortIcons()},o.prototype.onSortChanged=function(){if(Ve(this.getGui(),"ag-header-cell-sorted-asc",this.params.column.isSortAscending()),Ve(this.getGui(),"ag-header-cell-sorted-desc",this.params.column.isSortDescending()),Ve(this.getGui(),"ag-header-cell-sorted-none",this.params.column.isSortNone()),this.eSortAsc&&Ve(this.eSortAsc,"ag-hidden",!this.params.column.isSortAscending()),this.eSortDesc&&Ve(this.eSortDesc,"ag-hidden",!this.params.column.isSortDescending()),this.eSortNone){var t=!this.params.column.getColDef().unSortIcon&&!this.gridOptionsWrapper.isUnSortIcon();Ve(this.eSortNone,"ag-hidden",t||!this.params.column.isSortNone())}},o.prototype.setMultiSortOrder=function(){if(this.eSortOrder){var t=this.params.column,e=this.sortController.getColumnsWithSortingOrdered(),o=e.indexOf(t),n=e.length>1,i=t.isSorting()&&n;ke(this.eSortOrder,i),o>=0?this.eSortOrder.innerHTML=(o+1).toString():Je(this.eSortOrder)}},o.prototype.setupFilterIcon=function(){this.eFilter&&(this.addManagedListener(this.params.column,yt.EVENT_FILTER_CHANGED,this.onFilterChanged.bind(this)),this.onFilterChanged())},o.prototype.onFilterChanged=function(){var t=this.params.column.isFilterActive();Ve(this.eFilter,"ag-hidden",!t)},o.TEMPLATE='<div class="ag-cell-label-container" role="presentation">\n <span ref="eMenu" class="ag-header-icon ag-header-cell-menu-button" aria-hidden="true"></span>\n <div ref="eLabel" class="ag-header-cell-label" role="presentation" unselectable="on">\n <span ref="eText" class="ag-header-cell-text" unselectable="on"></span>\n <span ref="eFilter" class="ag-header-icon ag-header-label-icon ag-filter-icon" aria-hidden="true"></span>\n <span ref="eSortOrder" class="ag-header-icon ag-header-label-icon ag-sort-order" aria-hidden="true"></span>\n <span ref="eSortAsc" class="ag-header-icon ag-header-label-icon ag-sort-ascending-icon" aria-hidden="true"></span>\n <span ref="eSortDesc" class="ag-header-icon ag-header-label-icon ag-sort-descending-icon" aria-hidden="true"></span>\n <span ref="eSortNone" class="ag-header-icon ag-header-label-icon ag-sort-none-icon" aria-hidden="true"></span>\n </div>\n </div>',hi([it("sortController")],o.prototype,"sortController",void 0),hi([it("menuFactory")],o.prototype,"menuFactory",void 0),hi([Wn("eFilter")],o.prototype,"eFilter",void 0),hi([Wn("eSortAsc")],o.prototype,"eSortAsc",void 0),hi([Wn("eSortDesc")],o.prototype,"eSortDesc",void 0),hi([Wn("eSortNone")],o.prototype,"eSortNone",void 0),hi([Wn("eSortOrder")],o.prototype,"eSortOrder",void 0),hi([Wn("eMenu")],o.prototype,"eMenu",void 0),hi([Wn("eLabel")],o.prototype,"eLabel",void 0),hi([Wn("eText")],o.prototype,"eText",void 0),o}(xn),gi=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),yi=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},vi=function(t){function o(){return t.call(this,o.TEMPLATE)||this}return gi(o,t),o.prototype.destroy=function(){t.prototype.destroy.call(this)},o.prototype.init=function(t){this.params=t,this.setupLabel(),this.addGroupExpandIcon(),this.setupExpandIcons()},o.prototype.setupExpandIcons=function(){var t=this;this.addInIcon("columnGroupOpened","agOpened"),this.addInIcon("columnGroupClosed","agClosed");var e=function(e){if(!Pt(e)){var o=!t.params.columnGroup.isExpanded();t.columnController.setColumnGroupOpened(t.params.columnGroup.getOriginalColumnGroup(),o,"uiColumnExpanded")}};this.addTouchAndClickListeners(this.eCloseIcon,e),this.addTouchAndClickListeners(this.eOpenIcon,e);var o=function(t){Ot(t)};this.addManagedListener(this.eCloseIcon,"dblclick",o),this.addManagedListener(this.eOpenIcon,"dblclick",o),this.addManagedListener(this.getGui(),"dblclick",e),this.updateIconVisibility();var n=this.params.columnGroup.getOriginalColumnGroup();this.addManagedListener(n,Ct.EVENT_EXPANDED_CHANGED,this.updateIconVisibility.bind(this)),this.addManagedListener(n,Ct.EVENT_EXPANDABLE_CHANGED,this.updateIconVisibility.bind(this))},o.prototype.addTouchAndClickListeners=function(t,e){var o=new ci(t,!0);this.addManagedListener(o,ci.EVENT_TAP,e),this.addDestroyFunc((function(){return o.destroy()})),this.addManagedListener(t,"click",e)},o.prototype.updateIconVisibility=function(){if(this.params.columnGroup.isExpandable()){var t=this.params.columnGroup.isExpanded();ke(this.eOpenIcon,t),ke(this.eCloseIcon,!t)}else ke(this.eOpenIcon,!1),ke(this.eCloseIcon,!1)},o.prototype.addInIcon=function(t,e){var o=cn(t,this.gridOptionsWrapper,null);o&&this.getRefElement(e).appendChild(o)},o.prototype.addGroupExpandIcon=function(){if(!this.params.columnGroup.isExpandable())return ke(this.eOpenIcon,!1),void ke(this.eCloseIcon,!1)},o.prototype.setupLabel=function(){var t=this.params.displayName;if(e(t)){var o=Kt(t);this.getRefElement("agLabel").innerHTML=o}},o.TEMPLATE='<div class="ag-header-group-cell-label" ref="agContainer" role="presentation">\n <span ref="agLabel" class="ag-header-group-text" role="presentation"></span>\n <span ref="agOpened" class="ag-header-icon ag-header-expand-icon ag-header-expand-icon-expanded"></span>\n <span ref="agClosed" class="ag-header-icon ag-header-expand-icon ag-header-expand-icon-collapsed"></span>\n </div>',yi([it("columnController")],o.prototype,"columnController",void 0),yi([Wn("agOpened")],o.prototype,"eOpenIcon",void 0),yi([Wn("agClosed")],o.prototype,"eCloseIcon",void 0),o}(xn),mi=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Ci=function(){function t(){this.rowIndex=null,this.childrenMapped={},this.displayed=!1,this.rowTop=null,this.oldRowTop=null,this.selectable=!0,this.__objectId=t.OBJECT_ID_SEQUENCE++,this.alreadyRendered=!1,this.highlighted=null,this.selected=!1}return t.prototype.setData=function(t){this.setDataCommon(t,!1)},t.prototype.updateData=function(t){this.setDataCommon(t,!0)},t.prototype.setDataCommon=function(t,e){var o=this.data;this.data=t,this.valueCache.onDataChanged(),this.updateDataOnDetailNode(),this.checkRowSelectable();var n=this.createDataChangedEvent(t,o,e);this.dispatchLocalEvent(n)},t.prototype.updateDataOnDetailNode=function(){this.detailNode&&(this.detailNode.data=this.data)},t.prototype.createDataChangedEvent=function(e,o,n){return{type:t.EVENT_DATA_CHANGED,node:this,oldData:o,newData:e,update:n}},t.prototype.createLocalRowEvent=function(t){return{type:t,node:this}},t.prototype.getRowIndexString=function(){return this.rowPinned===ht.PINNED_TOP?"t-"+this.rowIndex:this.rowPinned===ht.PINNED_BOTTOM?"b-"+this.rowIndex:this.rowIndex.toString()},t.prototype.createDaemonNode=function(){var e=new t;return this.context.createBean(e),e.id=this.id,e.data=this.data,e.daemon=!0,e.selected=this.selected,e.level=this.level,e},t.prototype.setDataAndId=function(t,o){var n=e(this.id)?this.createDaemonNode():null,i=this.data;this.data=t,this.updateDataOnDetailNode(),this.setId(o),this.selectionController.syncInRowNode(this,n),this.checkRowSelectable();var r=this.createDataChangedEvent(t,i,!1);this.dispatchLocalEvent(r)},t.prototype.checkRowSelectable=function(){var t=this.gridOptionsWrapper.getIsRowSelectableFunc(),o=t&&e(this);this.setRowSelectable(!o||t(this))},t.prototype.setRowSelectable=function(e){this.selectable!==e&&(this.selectable=e,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(t.EVENT_SELECTABLE_CHANGED)))},t.prototype.setId=function(e){var o=this.gridOptionsWrapper.getRowNodeIdFunc();o?this.data?(this.id=o(this.data),this.id&&this.id.startsWith&&this.id.startsWith(t.ID_PREFIX_ROW_GROUP)&&console.error("AG Grid: Row ID's cannot start with "+t.ID_PREFIX_ROW_GROUP+", this is a reserved prefix for AG Grid's row grouping feature.")):this.id=void 0:this.id=e},t.prototype.isPixelInRange=function(t){return!(!e(this.rowTop)||!e(this.rowHeight))&&(t>=this.rowTop&&t<this.rowTop+this.rowHeight)},t.prototype.setFirstChild=function(e){this.firstChild!==e&&(this.firstChild=e,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(t.EVENT_FIRST_CHILD_CHANGED)))},t.prototype.setLastChild=function(e){this.lastChild!==e&&(this.lastChild=e,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(t.EVENT_LAST_CHILD_CHANGED)))},t.prototype.setChildIndex=function(e){this.childIndex!==e&&(this.childIndex=e,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(t.EVENT_CHILD_INDEX_CHANGED)))},t.prototype.setRowTop=function(e){this.rowTop!==e&&(this.rowTop=e,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(t.EVENT_TOP_CHANGED)),this.setDisplayed(null!==e))},t.prototype.clearRowTopAndRowIndex=function(){this.oldRowTop=this.rowTop,this.setRowTop(null),this.setRowIndex(null)},t.prototype.setDisplayed=function(e){this.displayed!==e&&(this.displayed=e,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(t.EVENT_DISPLAYED_CHANGED)))},t.prototype.setDragging=function(e){this.dragging!==e&&(this.dragging=e,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(t.EVENT_DRAGGING_CHANGED)))},t.prototype.setHighlighted=function(e){e!==this.highlighted&&(this.highlighted=e,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(t.EVENT_HIGHLIGHT_CHANGED)))},t.prototype.setAllChildrenCount=function(e){this.allChildrenCount!==e&&(this.allChildrenCount=e,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(t.EVENT_ALL_CHILDREN_COUNT_CHANGED)))},t.prototype.setMaster=function(e){this.master!==e&&(this.master&&!e&&(this.expanded=!1),this.master=e,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(t.EVENT_MASTER_CHANGED)))},t.prototype.setRowHeight=function(e,o){void 0===o&&(o=!1),this.rowHeight=e,this.rowHeightEstimated=o,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(t.EVENT_HEIGHT_CHANGED))},t.prototype.setRowIndex=function(e){this.rowIndex=e,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(t.EVENT_ROW_INDEX_CHANGED))},t.prototype.setUiLevel=function(e){this.uiLevel!==e&&(this.uiLevel=e,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(t.EVENT_UI_LEVEL_CHANGED)))},t.prototype.setExpanded=function(e){if(this.expanded!==e){this.expanded=e,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(t.EVENT_EXPANDED_CHANGED));var o=M({},this.createGlobalRowEvent(Wt.EVENT_ROW_GROUP_OPENED),{expanded:e});this.mainEventService.dispatchEvent(o),this.gridOptionsWrapper.isGroupIncludeFooter()&&this.rowRenderer.refreshCells({rowNodes:[this]})}},t.prototype.createGlobalRowEvent=function(t){return{type:t,node:this,data:this.data,rowIndex:this.rowIndex,rowPinned:this.rowPinned,context:this.gridOptionsWrapper.getContext(),api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi()}},t.prototype.dispatchLocalEvent=function(t){this.eventService&&this.eventService.dispatchEvent(t)},t.prototype.setDataValue=function(t,e){var o=this.columnController.getPrimaryColumn(t),n=this.valueService.getValue(o,this);this.valueService.setValue(this,o,e),this.dispatchCellChangedEvent(o,e,n)},t.prototype.setGroupValue=function(t,e){var n=this.columnController.getGridColumn(t);o(this.groupData)&&(this.groupData={});var i=n.getColId(),r=this.groupData[i];r!==e&&(this.groupData[i]=e,this.dispatchCellChangedEvent(n,e,r))},t.prototype.setAggData=function(t){var e=this,o=I([this.aggData,t]),n=this.aggData;this.aggData=t,this.eventService&&o.forEach((function(t){var o=e.columnController.getGridColumn(t),i=e.aggData?e.aggData[t]:void 0,r=n?n[t]:void 0;e.dispatchCellChangedEvent(o,i,r)}))},t.prototype.updateHasChildren=function(){var e=this.group&&!this.footer||this.childrenAfterGroup&&this.childrenAfterGroup.length>0;e!==this.__hasChildren&&(this.__hasChildren=!!e,this.eventService&&this.eventService.dispatchEvent(this.createLocalRowEvent(t.EVENT_HAS_CHILDREN_CHANGED)))},t.prototype.hasChildren=function(){return null==this.__hasChildren&&this.updateHasChildren(),this.__hasChildren},t.prototype.isEmptyRowGroupNode=function(){return this.group&&n(this.childrenAfterGroup)},t.prototype.dispatchCellChangedEvent=function(e,o,n){var i={type:t.EVENT_CELL_CHANGED,node:this,column:e,newValue:o,oldValue:n};this.dispatchLocalEvent(i)},t.prototype.resetQuickFilterAggregateText=function(){this.quickFilterAggregateText=null},t.prototype.isExpandable=function(){return!(!this.hasChildren()&&!this.master)},t.prototype.isSelected=function(){return this.footer?this.sibling.isSelected():this.selected},t.prototype.depthFirstSearch=function(t){this.childrenAfterGroup&&this.childrenAfterGroup.forEach((function(e){return e.depthFirstSearch(t)})),t(this)},t.prototype.calculateSelectedFromChildren=function(){var t,e=!1,o=!1,n=!1;if(this.childrenAfterGroup)for(var i=0;i<this.childrenAfterGroup.length;i++){var r=this.childrenAfterGroup[i];if(r.selectable)switch(r.isSelected()){case!0:e=!0;break;case!1:o=!0;break;default:n=!0}}t=n?void 0:!(!e||o)||!(!e&&o)&&void 0,this.selectThisNode(t)},t.prototype.setSelectedInitialValue=function(t){this.selected=t},t.prototype.setSelected=function(t,e,o){void 0===e&&(e=!1),void 0===o&&(o=!1),this.setSelectedParams({newValue:t,clearSelection:e,suppressFinishActions:o,rangeSelect:!1})},t.prototype.isRowPinned=function(){return this.rowPinned===ht.PINNED_TOP||this.rowPinned===ht.PINNED_BOTTOM},t.prototype.setSelectedParams=function(t){var e=this.gridOptionsWrapper.isGroupSelectsChildren(),o=!0===t.newValue,n=!0===t.clearSelection,i=!0===t.suppressFinishActions,r=!0===t.rangeSelect,s=e&&!0===t.groupSelectsFiltered;if(void 0===this.id)return console.warn("AG Grid: cannot select node until id for node is known"),0;if(this.rowPinned)return console.warn("AG Grid: cannot select pinned rows"),0;if(this.footer)return this.sibling.setSelectedParams(t);if(r&&this.selectionController.getLastSelectedNode()){var a=this.selectionController.getLastSelectedNode()!==this,l=this.gridOptionsWrapper.isRowSelectionMulti();if(a&&l){var p=this.doRowRangeSelection(t.newValue);return this.selectionController.setLastSelectedNode(this),p}}var u=0;s&&this.group||this.selectThisNode(o)&&u++;if(e&&this.group&&(u+=this.selectChildNodes(o,s)),!i){if(o&&(n||!this.gridOptionsWrapper.isRowSelectionMulti())&&(u+=this.selectionController.clearOtherNodes(this)),u>0){this.selectionController.updateGroupsFromChildrenSelections();var c={type:Wt.EVENT_SELECTION_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.mainEventService.dispatchEvent(c)}o&&this.selectionController.setLastSelectedNode(this)}return u},t.prototype.doRowRangeSelection=function(t){var e=this;void 0===t&&(t=!0);var o=this.gridOptionsWrapper.isGroupSelectsChildren(),n=this.selectionController.getLastSelectedNode(),i=this.rowModel.getNodesInRangeForSelection(this,n),r=0;i.forEach((function(n){n.group&&o||!1===t&&e===n||n.selectThisNode(t)&&r++})),this.selectionController.updateGroupsFromChildrenSelections();var s={type:Wt.EVENT_SELECTION_CHANGED,api:this.gridApi,columnApi:this.columnApi};return this.mainEventService.dispatchEvent(s),r},t.prototype.isParentOfNode=function(t){for(var e=this.parent;e;){if(e===t)return!0;e=e.parent}return!1},t.prototype.selectThisNode=function(e){var o=!this.selectable&&e,n=this.selected===e;if(o||n)return!1;this.selected=e,this.eventService&&this.dispatchLocalEvent(this.createLocalRowEvent(t.EVENT_ROW_SELECTED));var i=this.createGlobalRowEvent(Wt.EVENT_ROW_SELECTED);return this.mainEventService.dispatchEvent(i),!0},t.prototype.selectChildNodes=function(t,e){var n=e?this.childrenAfterFilter:this.childrenAfterGroup;if(o(n))return 0;for(var i=0,r=0;r<n.length;r++)i+=n[r].setSelectedParams({newValue:t,clearSelection:!1,suppressFinishActions:!0,groupSelectsFiltered:e});return i},t.prototype.addEventListener=function(t,e){this.eventService||(this.eventService=new dt),this.eventService.addEventListener(t,e)},t.prototype.removeEventListener=function(t,e){this.eventService.removeEventListener(t,e)},t.prototype.onMouseEnter=function(){this.dispatchLocalEvent(this.createLocalRowEvent(t.EVENT_MOUSE_ENTER))},t.prototype.onMouseLeave=function(){this.dispatchLocalEvent(this.createLocalRowEvent(t.EVENT_MOUSE_LEAVE))},t.prototype.getFirstChildOfFirstChild=function(t){for(var o=this,n=!0,i=!1,r=null;n&&!i;){var s=o.parent;e(s)&&o.firstChild?s.rowGroupColumn===t&&(i=!0,r=s):n=!1,o=s}return i?r:null},t.prototype.isFullWidthCell=function(){var t=this.gridOptionsWrapper.getIsFullWidthCellFunc();return!!t&&t(this)},t.prototype.getRoute=function(){if(null!=this.key){for(var t=[],e=this;null!=e.key;)t.push(e.key),e=e.parent;return t.reverse()}},t.ID_PREFIX_ROW_GROUP="row-group-",t.ID_PREFIX_TOP_PINNED="t-",t.ID_PREFIX_BOTTOM_PINNED="b-",t.OBJECT_ID_SEQUENCE=0,t.EVENT_ROW_SELECTED="rowSelected",t.EVENT_DATA_CHANGED="dataChanged",t.EVENT_CELL_CHANGED="cellChanged",t.EVENT_ALL_CHILDREN_COUNT_CHANGED="allChildrenCountChanged",t.EVENT_MASTER_CHANGED="masterChanged",t.EVENT_MOUSE_ENTER="mouseEnter",t.EVENT_MOUSE_LEAVE="mouseLeave",t.EVENT_HEIGHT_CHANGED="heightChanged",t.EVENT_TOP_CHANGED="topChanged",t.EVENT_DISPLAYED_CHANGED="displayedChanged",t.EVENT_FIRST_CHILD_CHANGED="firstChildChanged",t.EVENT_LAST_CHILD_CHANGED="lastChildChanged",t.EVENT_CHILD_INDEX_CHANGED="childIndexChanged",t.EVENT_ROW_INDEX_CHANGED="rowIndexChanged",t.EVENT_EXPANDED_CHANGED="expandedChanged",t.EVENT_HAS_CHILDREN_CHANGED="hasChildrenChanged",t.EVENT_SELECTABLE_CHANGED="selectableChanged",t.EVENT_UI_LEVEL_CHANGED="uiLevelChanged",t.EVENT_HIGHLIGHT_CHANGED="rowHighlightChanged",t.EVENT_DRAGGING_CHANGED="draggingChanged",mi([it("eventService")],t.prototype,"mainEventService",void 0),mi([it("rowRenderer")],t.prototype,"rowRenderer",void 0),mi([it("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),mi([it("selectionController")],t.prototype,"selectionController",void 0),mi([it("columnController")],t.prototype,"columnController",void 0),mi([it("valueService")],t.prototype,"valueService",void 0),mi([it("rowModel")],t.prototype,"rowModel",void 0),mi([it("context")],t.prototype,"context",void 0),mi([it("valueCache")],t.prototype,"valueCache",void 0),mi([it("columnApi")],t.prototype,"columnApi",void 0),mi([it("gridApi")],t.prototype,"gridApi",void 0),t}(),wi=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Ei=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Ri=function(t){function e(){return t.call(this,'\n <div class="ag-selection-checkbox" role="presentation">\n <ag-checkbox role="presentation" ref="eCheckbox"></ag-checkbox>\n </div>')||this}return wi(e,t),e.prototype.postConstruct=function(){this.eCheckbox.setPassive(!0)},e.prototype.getCheckboxId=function(){return this.eCheckbox.getInputElement().id},e.prototype.onDataChanged=function(){this.onSelectionChanged()},e.prototype.onSelectableChanged=function(){this.showOrHideSelect()},e.prototype.onSelectionChanged=function(){var t=this.gridOptionsWrapper.getLocaleTextFunc(),e=this.rowNode.isSelected(),o=void 0===e?t("ariaIndeterminate","indeterminate"):!0===e?t("ariaChecked","checked"):t("ariaUnchecked","unchecked"),n=t("ariaRowToggleSelection","Press Space to toggle row selection");this.eCheckbox.setValue(e,!0),this.eCheckbox.setInputAriaLabel(n+" ("+o+")")},e.prototype.onCheckedClicked=function(t){var e=this.gridOptionsWrapper.isGroupSelectsFiltered();return this.rowNode.setSelectedParams({newValue:!1,rangeSelect:t.shiftKey,groupSelectsFiltered:e})},e.prototype.onUncheckedClicked=function(t){var e=this.gridOptionsWrapper.isGroupSelectsFiltered();return this.rowNode.setSelectedParams({newValue:!0,rangeSelect:t.shiftKey,groupSelectsFiltered:e})},e.prototype.init=function(t){var e=this;this.rowNode=t.rowNode,this.column=t.column,this.onSelectionChanged(),this.addGuiEventListener("click",(function(t){return Ot(t)})),this.addGuiEventListener("dblclick",(function(t){return Ot(t)})),this.addManagedListener(this.eCheckbox.getInputElement(),"click",(function(t){var o=e.eCheckbox.getValue();void 0===e.eCheckbox.getPreviousValue()?0===e.onUncheckedClicked(t||{})&&e.onCheckedClicked(t):o?e.onCheckedClicked(t):e.onUncheckedClicked(t||{})})),this.addManagedListener(this.rowNode,Ci.EVENT_ROW_SELECTED,this.onSelectionChanged.bind(this)),this.addManagedListener(this.rowNode,Ci.EVENT_DATA_CHANGED,this.onDataChanged.bind(this)),this.addManagedListener(this.rowNode,Ci.EVENT_SELECTABLE_CHANGED,this.onSelectableChanged.bind(this)),this.isRowSelectableFunc=this.gridOptionsWrapper.getIsRowSelectableFunc(),(this.isRowSelectableFunc||this.checkboxCallbackExists())&&(this.addManagedListener(this.eventService,Wt.EVENT_DISPLAYED_COLUMNS_CHANGED,this.showOrHideSelect.bind(this)),this.showOrHideSelect()),this.eCheckbox.getInputElement().setAttribute("tabindex","-1")},e.prototype.showOrHideSelect=function(){var t=this.rowNode.selectable;t&&this.checkboxCallbackExists()&&(t=this.column.isCellCheckboxSelection(this.rowNode)),this.setDisplayed(t)},e.prototype.checkboxCallbackExists=function(){var t=this.column?this.column.getColDef():null;return!!t&&"function"==typeof t.checkboxSelection},Ei([Wn("eCheckbox")],e.prototype,"eCheckbox",void 0),Ei([et],e.prototype,"postConstruct",null),e}(xn),Oi={propertyName:"dateComponent",isCellRenderer:function(){return!1}},Pi={propertyName:"headerComponent",isCellRenderer:function(){return!1}},Si={propertyName:"headerGroupComponent",isCellRenderer:function(){return!1}},bi={propertyName:"cellRenderer",isCellRenderer:function(){return!0}},Di={propertyName:"pinnedRowCellRenderer",isCellRenderer:function(){return!0}},Ai={propertyName:"cellEditor",isCellRenderer:function(){return!1}},Ti={propertyName:"innerRenderer",isCellRenderer:function(){return!0}},_i={propertyName:"loadingOverlayComponent",isCellRenderer:function(){return!1}},Fi={propertyName:"noRowsOverlayComponent",isCellRenderer:function(){return!1}},Ni={propertyName:"tooltipComponent",isCellRenderer:function(){return!1}},Li={propertyName:"filter",isCellRenderer:function(){return!1}},Ii={propertyName:"floatingFilterComponent",isCellRenderer:function(){return!1}},Gi={propertyName:"toolPanel",isCellRenderer:function(){return!1}},Mi={propertyName:"statusPanel",isCellRenderer:function(){return!1}},xi=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Vi=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s};
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/!function(t){t[t.DEFAULT=0]="DEFAULT",t[t.REGISTERED_BY_NAME=1]="REGISTERED_BY_NAME",t[t.HARDCODED=2]="HARDCODED"}(ii||(ii={}));!function(t){function e(){return null!==t&&t.apply(this,arguments)||this}xi(e,t),e.prototype.newDateComponent=function(t){return this.createAndInitUserComponent(this.gridOptions,t,Oi,"agDateInput")},e.prototype.newHeaderComponent=function(t){return this.createAndInitUserComponent(t.column.getColDef(),t,Pi,"agColumnHeader")},e.prototype.newHeaderGroupComponent=function(t){return this.createAndInitUserComponent(t.columnGroup.getColGroupDef(),t,Si,"agColumnGroupHeader")},e.prototype.newFullWidthGroupRowInnerCellRenderer=function(t){return this.createAndInitUserComponent(this.gridOptions.groupRowRendererParams,t,Ti,null,!0)},e.prototype.newFullWidthCellRenderer=function(t,e,o){return this.createAndInitUserComponent(null,t,{propertyName:e,isCellRenderer:function(){return!0}},o)},e.prototype.newCellRenderer=function(t,e,o){return void 0===o&&(o=!1),this.createAndInitUserComponent(t,e,o?Di:bi,null,!0)},e.prototype.newCellEditor=function(t,e){return this.createAndInitUserComponent(t,e,Ai,"agCellEditor")},e.prototype.newInnerCellRenderer=function(t,e){return this.createAndInitUserComponent(t,e,Ti,null)},e.prototype.newLoadingOverlayComponent=function(t){return this.createAndInitUserComponent(this.gridOptions,t,_i,"agLoadingOverlay")},e.prototype.newNoRowsOverlayComponent=function(t){return this.createAndInitUserComponent(this.gridOptions,t,Fi,"agNoRowsOverlay")},e.prototype.newTooltipComponent=function(t){return this.createAndInitUserComponent(t.colDef,t,Ni,"agTooltipComponent")},e.prototype.newFilterComponent=function(t,e,o){return this.createAndInitUserComponent(t,e,Li,o,!1)},e.prototype.newSetFilterCellRenderer=function(t,e){return this.createAndInitUserComponent(t,e,bi,null,!0)},e.prototype.newFloatingFilterComponent=function(t,e,o){return this.createAndInitUserComponent(t,e,Ii,o,!0)},e.prototype.newToolPanelComponent=function(t,e){return this.createAndInitUserComponent(t,e,Gi)},e.prototype.newStatusPanelComponent=function(t,e){return this.createAndInitUserComponent(t,e,Mi)},e.prototype.createAndInitUserComponent=function(t,e,o,n,i){void 0===i&&(i=!1),t||(t=this.gridOptions);var r=this.createComponentInstance(t,o,e,n,i);if(!r)return null;var s=r.componentInstance,a=this.createFinalParams(t,o.propertyName,e,r.paramsFromSelector);this.addReactHacks(a);var l=this.initComponent(s,a);return null==l?Tn.resolve(s):l.then((function(){return s}))},e.prototype.addReactHacks=function(t){var e=this.context.getBean("agGridReact");e&&(t.agGridReact=T(e));var o=this.context.getBean("frameworkComponentWrapper");o&&(t.frameworkComponentWrapper=o)},e.prototype.createUserComponentFromConcreteClass=function(t,e){var o=new t;return this.initComponent(o,e),o},e.prototype.lookupComponentClassDef=function(t,e,o,n){void 0===o&&(o=null);var i=null,r=null,s=null,a=null,l=null;if(null!=t){var p=t[e];null==p||!0===p||("string"==typeof p?i=p:"boolean"==typeof p||(this.agComponentUtils.doesImplementIComponent(p)?r=p:s=p)),a=t[e+"Framework"],l=t[e+"Selector"]}if(r&&a||i&&a||s&&a)throw Error("ag-grid: you are trying to specify: "+e+" twice as a component.");if(a&&!this.frameworkComponentWrapper)throw Error("ag-grid: you are specifying a framework component but you are not using a framework version of ag-grid for : "+e);if(l&&(i||r||s||a))throw Error("ag-grid: you can't specify both, the selector and the component of ag-grid for : "+e);if(a)return{componentFromFramework:!0,component:a,source:ii.HARDCODED,paramsFromSelector:null};if(r)return{componentFromFramework:!1,component:r,source:ii.HARDCODED,paramsFromSelector:null};if(s)return this.agComponentUtils.adaptFunction(e,s,!1,ii.HARDCODED);var u,c=l?l(o):null;if(!(u=c&&c.component?c.component:i||n))return null;var d=this.lookupFromRegisteredComponents(e,u);return d?{componentFromFramework:d.componentFromFramework,component:d.component,source:d.source,paramsFromSelector:c?c.params:null}:null},e.prototype.lookupFromRegisteredComponents=function(t,e){var o=null!=e?e:t,n=this.userComponentRegistry.retrieve(o);return null==n?null:n.componentFromFramework?{component:n.component,componentFromFramework:!0,source:ii.REGISTERED_BY_NAME,paramsFromSelector:null}:this.agComponentUtils.doesImplementIComponent(n.component)?{component:n.component,componentFromFramework:!1,source:n.source==Hi.REGISTERED?ii.REGISTERED_BY_NAME:ii.DEFAULT,paramsFromSelector:null}:this.agComponentUtils.adaptFunction(t,n.component,n.componentFromFramework,n.source==Hi.REGISTERED?ii.REGISTERED_BY_NAME:ii.DEFAULT)},e.prototype.createFinalParams=function(t,e,o,n){void 0===n&&(n=null);var i={};G(i,o);var r=t?t[e+"Params"]:null;null!=r&&("function"==typeof r?G(i,r(o)):"object"==typeof r&&G(i,r));return G(i,n),i},e.prototype.createComponentInstance=function(t,e,o,n,i){var r,s=e.propertyName,a=this.lookupComponentClassDef(t,s,o,n);if(!a||!a.component){var l=t?t[s]:n,p=l||n;return i||console.error("Could not find component "+p+", did you forget to configure this component?"),null}if(a.componentFromFramework){var u=a.component,c=this.componentMetadataProvider.retrieve(s);r=this.frameworkComponentWrapper.wrap(u,c.mandatoryMethodList,c.optionalMethodList,e,n)}else r=new a.component;return{componentInstance:r,paramsFromSelector:a.paramsFromSelector}},e.prototype.initComponent=function(t,e){if(this.context.createBean(t),null!=t.init)return t.init(e)},Vi([it("gridOptions")],e.prototype,"gridOptions",void 0),Vi([it("agComponentUtils")],e.prototype,"agComponentUtils",void 0),Vi([it("componentMetadataProvider")],e.prototype,"componentMetadataProvider",void 0),Vi([it("userComponentRegistry")],e.prototype,"userComponentRegistry",void 0),Vi([rt("frameworkComponentWrapper")],e.prototype,"frameworkComponentWrapper",void 0),e=Vi([nt("userComponentFactory")],e)}(Mt);
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/var Hi,Wi=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),ki=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Bi=function(t){function e(){return t.call(this,e.TEMPLATE)||this}return Wi(e,t),e.prototype.init=function(t){this.params=t,this.gridOptionsWrapper.isGroupIncludeTotalFooter()&&this.assignBlankValueToGroupFooterCell(t);var e=this.isEmbeddedRowMismatch(),o=null==t.value,n=!1;if(this.gridOptionsWrapper.isGroupIncludeFooter()&&this.gridOptionsWrapper.isGroupHideOpenParents()){var i=t.node;if(i.footer)n=(t.colDef&&t.colDef.showRowGroup)!==(i.rowGroupColumn&&i.rowGroupColumn.getColId())}this.cellIsBlank=e||o||n,this.cellIsBlank||(this.setupDragOpenParents(),this.addExpandAndContract(),this.addCheckboxIfNeeded(),this.addValueElement(),this.setupIndent())},e.prototype.assignBlankValueToGroupFooterCell=function(t){t.value||-1!=t.node.level||(t.value="")},e.prototype.isEmbeddedRowMismatch=function(){if(!this.params.fullWidth||!this.gridOptionsWrapper.isEmbedFullWidthRows())return!1;var t=this.params.pinned===ht.PINNED_LEFT,e=this.params.pinned===ht.PINNED_RIGHT,o=!t&&!e;return this.gridOptionsWrapper.isEnableRtl()?this.columnController.isPinningLeft()?!e:!o:this.columnController.isPinningLeft()?!t:!o},e.prototype.setIndent=function(){if(!this.gridOptionsWrapper.isGroupHideOpenParents()){var t=this.params,e=t.node,o=!!!t.colDef||!0===t.colDef.showRowGroup?e.uiLevel:0;t.padding>=0?this.setPaddingDeprecatedWay(o,t.padding):(this.indentClass&&this.removeCssClass(this.indentClass),this.indentClass="ag-row-group-indent-"+o,this.addCssClass(this.indentClass))}},e.prototype.setPaddingDeprecatedWay=function(t,e){z((function(){return console.warn("AG Grid: since v14.2, configuring padding for groupCellRenderer should be done with Sass variables and themes. Please see the AG Grid documentation page for Themes, in particular the property $row-group-indent-size.")}),"groupCellRenderer->doDeprecatedWay");var o=t*e,n=this.getGui(),i=this.gridOptionsWrapper.isEnableRtl()?"paddingRight":"paddingLeft";n.style[i]=o+"px"},e.prototype.setupIndent=function(){var t=this.params.node;this.params.suppressPadding||(this.addManagedListener(t,Ci.EVENT_UI_LEVEL_CHANGED,this.setIndent.bind(this)),this.setIndent())},e.prototype.addValueElement=function(){this.displayedGroup.footer?this.addFooterValue():(this.addGroupValue(),this.addChildCount())},e.prototype.addFooterValue=function(){var t,e=this.params.footerValueGetter;if(e){var o=T(this.params);o.value=this.params.value,"function"==typeof e?t=e(o):"string"==typeof e?t=this.expressionService.evaluate(e,o):console.warn("AG Grid: footerValueGetter should be either a function or a string (expression)")}else t="Total "+this.params.value;this.eValue.innerHTML=t},e.prototype.addGroupValue=function(){var t,e=this,o=this.params,n=this.displayedGroup.rowGroupColumn,i=n||o.column,r=this.params.value,s=i?this.valueFormatterService.formatValue(i,o.node,o.scope,r):null;o.valueFormatted=s,(t=o.fullWidth?this.useFullWidth(o):this.useInnerRenderer(this.params.colDef.cellRendererParams,i.getColDef(),o))&&t.then((function(t){e.innerCellRenderer=t}))},e.prototype.useInnerRenderer=function(t,e,o){var n=this,i=null,r=this.userComponentFactory.lookupComponentClassDef(t,"innerRenderer");if(r&&null!=r.component&&r.source!=ii.DEFAULT)i=this.userComponentFactory.newInnerCellRenderer(t,o);else{var s=this.userComponentFactory.lookupComponentClassDef(e,"cellRenderer");i=s&&s.source!=ii.DEFAULT?this.userComponentFactory.newCellRenderer(e,o):s&&s.source==ii.DEFAULT&&x(e,"cellRendererParams.innerRenderer",null)?this.userComponentFactory.newInnerCellRenderer(e.cellRendererParams,o):this.userComponentFactory.newCellRenderer({},o)}return null!=i?i.then((function(t){null!=t?bo(i,n.eValue):n.eValue.innerText=null!=o.valueFormatted?o.valueFormatted:o.value})):this.eValue.innerText=null!=o.valueFormatted?o.valueFormatted:o.value,i},e.prototype.useFullWidth=function(t){var e=this.userComponentFactory.newFullWidthGroupRowInnerCellRenderer(t);return null!=e?bo(e,this.eValue):this.eValue.innerText=null!=t.valueFormatted?t.valueFormatted:t.value,e},e.prototype.addChildCount=function(){this.params.suppressCount||(this.addManagedListener(this.displayedGroup,Ci.EVENT_ALL_CHILDREN_COUNT_CHANGED,this.updateChildCount.bind(this)),this.updateChildCount())},e.prototype.updateChildCount=function(){var t=this.displayedGroup.allChildrenCount,e=this.isShowRowGroupForThisRow()&&null!=t&&t>=0?"("+t+")":"";this.eChildCount.innerHTML=e},e.prototype.isUserWantsSelected=function(){var t=this.params.checkbox;return"function"==typeof t?t(this.params):!0===t},e.prototype.addCheckboxIfNeeded=function(){var t=this,e=this.displayedGroup,o=this.isUserWantsSelected()&&!e.footer&&!e.rowPinned&&!e.detail;if(o){var n=new Ri;this.getContext().createBean(n),n.init({rowNode:e,column:this.params.column}),this.eCheckbox.appendChild(n.getGui()),this.addDestroyFunc((function(){return t.getContext().destroyBean(n)}))}Ve(this.eCheckbox,"ag-invisible",!o)},e.prototype.addExpandAndContract=function(){var t=this.params,e=t.eGridCell,o=cn("groupExpanded",this.gridOptionsWrapper,null),n=cn("groupContracted",this.gridOptionsWrapper,null);Vo(e,!!t.node.expanded),o&&this.eExpanded.appendChild(o),n&&this.eContracted.appendChild(n),this.addManagedListener(this.eExpanded,"click",this.onExpandClicked.bind(this)),this.addManagedListener(this.eContracted,"click",this.onExpandClicked.bind(this)),this.addManagedListener(e,"keydown",this.onKeyDown.bind(this)),this.addManagedListener(t.node,Ci.EVENT_EXPANDED_CHANGED,this.showExpandAndContractIcons.bind(this)),this.showExpandAndContractIcons();var i=this.onRowNodeIsExpandableChanged.bind(this);this.addManagedListener(this.displayedGroup,Ci.EVENT_ALL_CHILDREN_COUNT_CHANGED,i),this.addManagedListener(this.displayedGroup,Ci.EVENT_MASTER_CHANGED,i),this.addManagedListener(this.displayedGroup,Ci.EVENT_HAS_CHILDREN_CHANGED,i),this.gridOptionsWrapper.isEnableGroupEdit()||!this.isExpandable()||t.suppressDoubleClickExpand||this.addManagedListener(e,"dblclick",this.onCellDblClicked.bind(this))},e.prototype.onRowNodeIsExpandableChanged=function(){this.showExpandAndContractIcons(),this.setIndent()},e.prototype.onKeyDown=function(t){hn(t,jn.ENTER)&&!this.params.suppressEnterExpand&&(this.params.column&&this.params.column.isCellEditable(this.params.node)||this.onExpandOrContract())},e.prototype.setupDragOpenParents=function(){var t=this.params.column,e=this.params.node;if(this.gridOptionsWrapper.isGroupHideOpenParents())if(e.hasChildren()){var n=e.rowGroupColumn;this.draggedFromHideOpenParents=!!n&&!t.isRowGroupDisplayed(n.getId())}else this.draggedFromHideOpenParents=!0;else this.draggedFromHideOpenParents=!1;if(this.draggedFromHideOpenParents)for(var i=e.parent;!o(i);){if(i.rowGroupColumn&&t.isRowGroupDisplayed(i.rowGroupColumn.getId())){this.displayedGroup=i;break}i=i.parent}o(this.displayedGroup)&&(this.displayedGroup=e)},e.prototype.onExpandClicked=function(t){Pt(t)||(Ot(t),this.onExpandOrContract())},e.prototype.onCellDblClicked=function(t){Pt(t)||(Tt(this.eExpanded,t)||Tt(this.eContracted,t)||this.onExpandOrContract())},e.prototype.onExpandOrContract=function(){var t=this.displayedGroup,e=this.params,o=!t.expanded;t.setExpanded(o),Vo(e.eGridCell,o)},e.prototype.isShowRowGroupForThisRow=function(){if(this.gridOptionsWrapper.isTreeData())return!0;var t=this.displayedGroup.rowGroupColumn;if(!t)return!1;var e=this.params.column;return null==e||e.isRowGroupDisplayed(t.getId())},e.prototype.isExpandable=function(){if(this.draggedFromHideOpenParents)return!0;var t=this.displayedGroup,e=this.columnController.isPivotMode()&&t.leafGroup;if(!(t.isExpandable()&&!t.footer&&!e))return!1;var o=this.params.column;return null==o||"string"!=typeof o.getColDef().showRowGroup||this.isShowRowGroupForThisRow()},e.prototype.showExpandAndContractIcons=function(){var t=this,e=t.eContracted,o=t.eExpanded,n=t.params,i=t.displayedGroup,r=t.columnController,s=n.eGridCell,a=n.node,l=this.isExpandable();if(l){var p=!!this.draggedFromHideOpenParents||a.expanded;ke(e,!p),ke(o,p)}else Ho(s),ke(o,!1),ke(e,!1);var u=r.isPivotMode(),c=u&&i.leafGroup,d=l&&!c,h=a.footer&&-1===a.level;this.addOrRemoveCssClass("ag-cell-expandable",d),this.addOrRemoveCssClass("ag-row-group",d),u?this.addOrRemoveCssClass("ag-pivot-leaf-group",c):h||this.addOrRemoveCssClass("ag-row-group-leaf-indent",!d)},e.prototype.destroy=function(){this.getContext().destroyBean(this.innerCellRenderer),t.prototype.destroy.call(this)},e.prototype.refresh=function(){return!1},e.TEMPLATE='<span class="ag-cell-wrapper">\n <span class="ag-group-expanded" ref="eExpanded"></span>\n <span class="ag-group-contracted" ref="eContracted"></span>\n <span class="ag-group-checkbox ag-invisible" ref="eCheckbox"></span>\n <span class="ag-group-value" ref="eValue"></span>\n <span class="ag-group-child-count" ref="eChildCount"></span>\n </span>',ki([it("expressionService")],e.prototype,"expressionService",void 0),ki([it("valueFormatterService")],e.prototype,"valueFormatterService",void 0),ki([it("columnController")],e.prototype,"columnController",void 0),ki([it("userComponentFactory")],e.prototype,"userComponentFactory",void 0),ki([Wn("eExpanded")],e.prototype,"eExpanded",void 0),ki([Wn("eContracted")],e.prototype,"eContracted",void 0),ki([Wn("eCheckbox")],e.prototype,"eCheckbox",void 0),ki([Wn("eValue")],e.prototype,"eValue",void 0),ki([Wn("eChildCount")],e.prototype,"eChildCount",void 0),e}(xn),ji=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Ui=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},zi=function(t){function o(){var e=t.call(this,o.TEMPLATE)||this;return e.refreshCount=0,e}return ji(o,t),o.prototype.init=function(t){this.eValue=this.queryForHtmlElement(".ag-value-change-value"),this.eDelta=this.queryForHtmlElement(".ag-value-change-delta"),this.refresh(t)},o.prototype.showDelta=function(t,o){var n=Math.abs(o),i=t.formatValue(n),r=e(i)?i:n,s=o>=0;this.eDelta.innerHTML=s?"\u2191"+r:"\u2193"+r,Ve(this.eDelta,"ag-value-change-delta-up",s),Ve(this.eDelta,"ag-value-change-delta-down",!s)},o.prototype.setTimerToRemoveDelta=function(){var t=this;this.refreshCount++;var e=this.refreshCount;window.setTimeout((function(){e===t.refreshCount&&t.hideDeltaValue()}),2e3)},o.prototype.hideDeltaValue=function(){xe(this.eValue,"ag-value-change-value-highlight"),Je(this.eDelta)},o.prototype.refresh=function(t){var o=t.value;if(o===this.lastValue)return!1;if(e(t.valueFormatted)?this.eValue.innerHTML=t.valueFormatted:e(t.value)?this.eValue.innerHTML=o:Je(this.eValue),this.filterManager.isSuppressFlashingCellsBecauseFiltering())return!1;if("number"==typeof o&&"number"==typeof this.lastValue){var n=o-this.lastValue;this.showDelta(t,n)}return this.lastValue&&Me(this.eValue,"ag-value-change-value-highlight"),this.setTimerToRemoveDelta(),this.lastValue=o,!0},o.TEMPLATE='<span><span class="ag-value-change-delta"></span><span class="ag-value-change-value"></span></span>',Ui([it("filterManager")],o.prototype,"filterManager",void 0),o}(xn),Ki=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Yi=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},qi=function(t){function n(){var e=t.call(this,n.TEMPLATE)||this;return e.refreshCount=0,e.eCurrent=e.queryForHtmlElement(".ag-value-slide-current"),e}return Ki(n,t),n.prototype.init=function(t){this.params=t,this.refresh(t)},n.prototype.addSlideAnimation=function(){var t=this;this.refreshCount++;var e=this.refreshCount;this.ePrevious&&this.getGui().removeChild(this.ePrevious),this.ePrevious=oo('<span class="ag-value-slide-previous ag-value-slide-out"></span>'),this.ePrevious.innerHTML=this.eCurrent.innerHTML,this.getGui().insertBefore(this.ePrevious,this.eCurrent),window.setTimeout((function(){e===t.refreshCount&&Me(t.ePrevious,"ag-value-slide-out-end")}),50),window.setTimeout((function(){e===t.refreshCount&&(t.getGui().removeChild(t.ePrevious),t.ePrevious=null)}),3e3)},n.prototype.refresh=function(t){var n=t.value;return o(n)&&(n=""),n!==this.lastValue&&(!this.filterManager.isSuppressFlashingCellsBecauseFiltering()&&(this.addSlideAnimation(),this.lastValue=n,e(t.valueFormatted)?this.eCurrent.innerHTML=t.valueFormatted:e(t.value)?this.eCurrent.innerHTML=n:Je(this.eCurrent),!0))},n.TEMPLATE='<span><span class="ag-value-slide-current"></span></span>',Yi([it("filterManager")],n.prototype,"filterManager",void 0),n}(xn),Xi=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Qi=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},$i=function(t){function e(){return t.call(this,e.TEMPLATE)||this}return Xi(e,t),e.prototype.init=function(t){t.node.failedLoad?this.setupFailed():this.setupLoading()},e.prototype.setupFailed=function(){this.eLoadingText.innerText="ERR"},e.prototype.setupLoading=function(){var t=cn("groupLoading",this.gridOptionsWrapper,null);t&&this.eLoadingIcon.appendChild(t);var e=this.gridOptionsWrapper.getLocaleTextFunc();this.eLoadingText.innerText=e("loadingOoo","Loading")},e.prototype.refresh=function(t){return!1},e.TEMPLATE='<div class="ag-loading">\n <span class="ag-loading-icon" ref="eLoadingIcon"></span>\n <span class="ag-loading-text" ref="eLoadingText"></span>\n </div>',Qi([Wn("eLoadingIcon")],e.prototype,"eLoadingIcon",void 0),Qi([Wn("eLoadingText")],e.prototype,"eLoadingText",void 0),e}(xn),Zi=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Ji=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},tr=function(t){function e(){var e=t.call(this,'<div class="ag-cell-edit-wrapper"><ag-select class="ag-cell-editor" ref="eSelect"></ag-select></div>')||this;return e.startedByEnter=!1,e}return Zi(e,t),e.prototype.init=function(t){var e=this;if(this.focusAfterAttached=t.cellStartedEdit,o(t.values))console.warn("AG Grid: no values found for select cellEditor");else{this.startedByEnter=t.keyPress===jn.ENTER;var n=!1;t.values.forEach((function(o){var i={value:o},r=e.valueFormatterService.formatValue(t.column,null,null,o),s=null!=r;i.text=s?r:o,e.eSelect.addOption(i),n=n||t.value===o})),n?this.eSelect.setValue(t.value,!0):t.values.length&&this.eSelect.setValue(t.values[0],!0),this.gridOptionsWrapper.isFullRowEdit()||this.eSelect.onValueChange((function(){return t.stopEditing()}))}},e.prototype.afterGuiAttached=function(){this.focusAfterAttached&&this.eSelect.getFocusableElement().focus(),this.startedByEnter&&this.eSelect.showPicker()},e.prototype.focusIn=function(){this.eSelect.getFocusableElement().focus()},e.prototype.getValue=function(){return this.eSelect.getValue()},e.prototype.isPopup=function(){return!1},Ji([it("valueFormatterService")],e.prototype,"valueFormatterService",void 0),Ji([Wn("eSelect")],e.prototype,"eSelect",void 0),e}(Hn),er=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),or=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return er(e,t),e.prototype.isPopup=function(){return!0},e}(Kn),nr=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),ir=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return nr(e,t),e.prototype.isPopup=function(){return!0},e}(tr),rr=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),sr=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},ar=function(t){function o(){return t.call(this,o.TEMPLATE)||this}return rr(o,t),o.prototype.init=function(t){this.params=t,this.focusAfterAttached=t.cellStartedEdit,this.eTextArea.setMaxLength(t.maxLength||200).setCols(t.cols||60).setRows(t.rows||10),e(t.value)&&this.eTextArea.setValue(t.value.toString(),!0),this.addGuiEventListener("keydown",this.onKeyDown.bind(this))},o.prototype.onKeyDown=function(t){var e=t.which||t.keyCode;(e===jn.LEFT||e===jn.UP||e===jn.RIGHT||e===jn.DOWN||t.shiftKey&&e===jn.ENTER)&&t.stopPropagation()},o.prototype.afterGuiAttached=function(){var t=this.gridOptionsWrapper.getLocaleTextFunc();this.eTextArea.setInputAriaLabel(t("ariaInputEditor","Input Editor")),this.focusAfterAttached&&this.eTextArea.getFocusableElement().focus()},o.prototype.getValue=function(){return this.params.parseValue(this.eTextArea.getValue())},o.TEMPLATE='<div class="ag-large-text" tabindex="0">\n <ag-input-text-area ref="eTextArea" class="ag-large-text-input"></ag-input-text-area>\n </div>',sr([Wn("eTextArea")],o.prototype,"eTextArea",void 0),o}(Hn),lr=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),pr=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},ur=function(e){function o(){return e.call(this,"numberFilter")||this}return lr(o,e),o.prototype.mapRangeFromModel=function(t){return{from:t.filter,to:t.filterTo}},o.prototype.getDefaultDebounceMs=function(){return 500},o.prototype.resetUiToDefaults=function(t){var o=this;return e.prototype.resetUiToDefaults.call(this,t).then((function(){[o.eValueFrom1,o.eValueFrom2,o.eValueTo1,o.eValueTo2].forEach((function(e){return e.setValue(null,t)})),o.resetPlaceholder()}))},o.prototype.setConditionIntoUi=function(t,e){var o=e===Bn.One,n=o?this.eValueFrom1:this.eValueFrom2,i=o?this.eValueTo1:this.eValueTo2;n.setValue(t?""+t.filter:null),i.setValue(t?""+t.filterTo:null)},o.prototype.setValueFromFloatingFilter=function(t){this.eValueFrom1.setValue(t),this.eValueTo1.setValue(null),this.eValueFrom2.setValue(null),this.eValueTo2.setValue(null)},o.prototype.comparator=function(){return function(t,e){return t===e?0:t<e?1:-1}},o.prototype.setParams=function(t){this.numberFilterParams=t;var o=this.getAllowedCharPattern();if(o){var n={allowedCharPattern:o};this.resetTemplate({eValueFrom1:n,eValueTo1:n,eValueFrom2:n,eValueTo2:n})}e.prototype.setParams.call(this,t),this.addValueChangedListeners()},o.prototype.addValueChangedListeners=function(){var t=this,e=function(){return t.onUiChanged()};this.eValueFrom1.onValueChange(e),this.eValueTo1.onValueChange(e),this.eValueFrom2.onValueChange(e),this.eValueTo2.onValueChange(e)},o.prototype.resetPlaceholder=function(){var t=this.gridOptionsWrapper.getLocaleTextFunc(),e=this.showValueTo(this.getCondition1Type()),o=this.showValueTo(this.getCondition2Type());this.eValueFrom1.setInputPlaceholder(this.translate(e?"inRangeStart":"filterOoo")),this.eValueFrom1.setInputAriaLabel(e?t("ariaFilterFromValue","Filter from value"):t("ariaFilterValue","Filter Value")),this.eValueTo1.setInputPlaceholder(this.translate("inRangeEnd")),this.eValueTo1.setInputAriaLabel(t("ariaFilterToValue","Filter to Value")),this.eValueFrom2.setInputPlaceholder(this.translate(o?"inRangeStart":"filterOoo")),this.eValueFrom2.setInputAriaLabel(o?t("ariaFilterFromValue","Filter from value"):t("ariaFilterValue","Filter Value")),this.eValueTo2.setInputPlaceholder(this.translate("inRangeEnd")),this.eValueTo2.setInputAriaLabel(t("ariaFilterToValue","Filter to Value"))},o.prototype.afterGuiAttached=function(t){e.prototype.afterGuiAttached.call(this,t),this.resetPlaceholder(),t&&t.suppressFocus||this.eValueFrom1.getInputElement().focus()},o.prototype.getDefaultFilterOptions=function(){return o.DEFAULT_FILTER_OPTIONS},o.prototype.createValueTemplate=function(t){var e=t===Bn.One?"1":"2",o=this.getAllowedCharPattern()?"ag-input-text-field":"ag-input-number-field";return'\n <div class="ag-filter-body" ref="eCondition'+e+'Body" role="presentation">\n <'+o+' class="ag-filter-from ag-filter-filter" ref="eValueFrom'+e+'"></'+o+">\n <"+o+' class="ag-filter-to ag-filter-filter" ref="eValueTo'+e+'"></'+o+">\n </div>"},o.prototype.isConditionUiComplete=function(t){var e=t===Bn.One,o=e?this.getCondition1Type():this.getCondition2Type();if(o===ri.EMPTY)return!1;if(this.doesFilterHaveHiddenInput(o))return!0;var n=e?this.eValueFrom1:this.eValueFrom2,i=e?this.eValueTo1:this.eValueTo2;return null!=this.stringToFloat(n.getValue())&&(!this.showValueTo(o)||null!=this.stringToFloat(i.getValue()))},o.prototype.areSimpleModelsEqual=function(t,e){return t.filter===e.filter&&t.filterTo===e.filterTo&&t.type===e.type},o.prototype.getFilterType=function(){return"number"},o.prototype.stringToFloat=function(e){if("number"==typeof e)return e;var o=t(e);return null!=o&&""===o.trim()&&(o=null),this.numberFilterParams.numberParser?this.numberFilterParams.numberParser(o):null==o||"-"===o.trim()?null:parseFloat(o)},o.prototype.createCondition=function(t){var e=t===Bn.One,o=e?this.getCondition1Type():this.getCondition2Type(),n=e?this.eValueFrom1:this.eValueFrom2,i=this.stringToFloat(n.getValue()),r={filterType:this.getFilterType(),type:o};if(!this.doesFilterHaveHiddenInput(o)&&(r.filter=i,this.showValueTo(o))){var s=e?this.eValueTo1:this.eValueTo2,a=this.stringToFloat(s.getValue());r.filterTo=a}return r},o.prototype.updateUiVisibility=function(){e.prototype.updateUiVisibility.call(this),this.resetPlaceholder();var t=this.getCondition1Type(),o=this.getCondition2Type();ke(this.eValueFrom1.getGui(),this.showValueFrom(t)),ke(this.eValueTo1.getGui(),this.showValueTo(t)),ke(this.eValueFrom2.getGui(),this.showValueFrom(o)),ke(this.eValueTo2.getGui(),this.showValueTo(o))},o.prototype.getAllowedCharPattern=function(){var t=(this.numberFilterParams||{}).allowedCharPattern;return t||(be()||Pe()?null:"\\d\\-\\.")},o.DEFAULT_FILTER_OPTIONS=[ai.EQUALS,ai.NOT_EQUAL,ai.LESS_THAN,ai.LESS_THAN_OR_EQUAL,ai.GREATER_THAN,ai.GREATER_THAN_OR_EQUAL,ai.IN_RANGE],pr([Wn("eValueFrom1")],o.prototype,"eValueFrom1",void 0),pr([Wn("eValueTo1")],o.prototype,"eValueTo1",void 0),pr([Wn("eValueFrom2")],o.prototype,"eValueFrom2",void 0),pr([Wn("eValueTo2")],o.prototype,"eValueTo2",void 0),o}(ai),cr=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),dr=function(t){function e(){return t.call(this)||this}return cr(e,t),e.prototype.destroy=function(){t.prototype.destroy.call(this)},e.prototype.init=function(t){var o=this.gridOptionsWrapper.getOverlayLoadingTemplate()?this.gridOptionsWrapper.getOverlayLoadingTemplate():e.DEFAULT_LOADING_OVERLAY_TEMPLATE,n=this.gridOptionsWrapper.getLocaleTextFunc(),i=o.replace("[LOADING...]",n("loadingOoo","Loading..."));this.setTemplate(i)},e.DEFAULT_LOADING_OVERLAY_TEMPLATE='<span class="ag-overlay-loading-center">[LOADING...]</span>',e}(xn),hr=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),fr=function(t){function e(){return t.call(this)||this}return hr(e,t),e.prototype.destroy=function(){t.prototype.destroy.call(this)},e.prototype.init=function(t){var o=this.gridOptionsWrapper.getOverlayNoRowsTemplate()?this.gridOptionsWrapper.getOverlayNoRowsTemplate():e.DEFAULT_NO_ROWS_TEMPLATE,n=this.gridOptionsWrapper.getLocaleTextFunc(),i=o.replace("[NO_ROWS_TO_SHOW]",n("noRowsToShow","No Rows To Show"));this.setTemplate(i)},e.DEFAULT_NO_ROWS_TEMPLATE='<span class="ag-overlay-no-rows-center">[NO_ROWS_TO_SHOW]</span>',e}(xn),gr=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),yr=function(t){function e(){return t.call(this,'<div class="ag-tooltip"></div>')||this}return gr(e,t),e.prototype.init=function(t){var e=t.value;this.getGui().innerHTML=e},e}(Hn),vr=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),mr=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Cr=function(t){function e(){return t.call(this,'\n <div class="ag-filter-filter">\n <ag-input-text-field class="ag-date-filter" ref="eDateInput"></ag-input-text-field>\n </div>')||this}return vr(e,t),e.prototype.destroy=function(){t.prototype.destroy.call(this)},e.prototype.init=function(t){var e=this.eDateInput.getInputElement();this.shouldUseBrowserDatePicker(t)&&(Oe()?console.warn("ag-grid: browserDatePicker is specified to true, but it is not supported in IE 11; reverting to text date picker"):e.type="date"),this.addManagedListener(e,"mousedown",(function(){return e.focus()})),this.addManagedListener(this.eDateInput.getInputElement(),"input",(function(e){e.target===document.activeElement&&t.onDateChanged()}))},e.prototype.getDate=function(){return tn(this.eDateInput.getValue())},e.prototype.setDate=function(t){this.eDateInput.setValue(Jo(t,!1))},e.prototype.setInputPlaceholder=function(t){this.eDateInput.setInputPlaceholder(t)},e.prototype.afterGuiAttached=function(t){t&&t.suppressFocus||this.eDateInput.getInputElement().focus()},e.prototype.shouldUseBrowserDatePicker=function(t){return t.filterParams&&null!=t.filterParams.browserDatePicker?t.filterParams.browserDatePicker:be()||De()},mr([Wn("eDateInput")],e.prototype,"eDateInput",void 0),e}(xn),wr=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Er=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return wr(e,t),e.prototype.getDefaultDebounceMs=function(){return 0},e.prototype.destroy=function(){t.prototype.destroy.call(this)},e.prototype.getTextFromModel=function(t){if(!t)return null;if(t.operator){var e=t,o=this.conditionToString(e.condition1),n=this.conditionToString(e.condition2);return o+" "+e.operator+" "+n}var i=t,r=this.optionsFactory.getCustomOption(i.type);return r?(this.gridOptionsWrapper.getLocaleTextFunc()(r.displayKey,r.displayName),r.displayName):this.conditionToString(i)},e.prototype.isEventFromFloatingFilter=function(t){return t&&t.afterFloatingFilter},e.prototype.getLastType=function(){return this.lastType},e.prototype.setLastTypeFromModel=function(t){if(t){var e;if(t.operator)e=t.condition1;else e=t;this.lastType=e.type}else this.lastType=this.optionsFactory.getDefaultOption()},e.prototype.canWeEditAfterModelFromParentFilter=function(t){if(!t)return this.isTypeEditable(this.lastType);if(t.operator)return!1;var e=t;return this.isTypeEditable(e.type)},e.prototype.init=function(t){this.optionsFactory=new qn,this.optionsFactory.init(t.filterParams,this.getDefaultFilterOptions()),this.lastType=this.optionsFactory.getDefaultOption();var e=this.isTypeEditable(this.lastType);this.setEditable(e)},e.prototype.doesFilterHaveHiddenInput=function(t){var e=this.optionsFactory.getCustomOption(t);return e&&e.hideFilterInput},e.prototype.isTypeEditable=function(t){return!!t&&!this.doesFilterHaveHiddenInput(t)&&t!==ri.IN_RANGE&&t!==ri.EMPTY},e}(xn),Rr=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Or=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Pr=function(t){function e(){return t.call(this,'\n <div class="ag-floating-filter-input" role="presentation">\n <ag-input-text-field ref="eReadOnlyText"></ag-input-text-field>\n <div ref="eDateWrapper" style="display: flex;"></div>\n </div>')||this}return Rr(e,t),e.prototype.getDefaultFilterOptions=function(){return ui.DEFAULT_FILTER_OPTIONS},e.prototype.conditionToString=function(t){var e=t.type,o=tn(t.dateFrom);if(e===ri.IN_RANGE){var n=tn(t.dateTo);return Jo(o,!1)+"-"+Jo(n,!1)}return null==o?""+e:""+Jo(o,!1)},e.prototype.init=function(e){t.prototype.init.call(this,e),this.params=e,this.createDateComponent();var o=this.gridOptionsWrapper.getLocaleTextFunc();this.eReadOnlyText.setDisabled(!0).setInputAriaLabel(o("ariaDateFilterInput","Date Filter Input"))},e.prototype.setEditable=function(t){ke(this.eDateWrapper,t),ke(this.eReadOnlyText.getGui(),!t)},e.prototype.onParentModelChanged=function(e,o){if(!this.isEventFromFloatingFilter(o)){t.prototype.setLastTypeFromModel.call(this,e);var n=this.canWeEditAfterModelFromParentFilter(e);if(this.setEditable(n),n){if(e){var i=e;this.dateComp.setDate(tn(i.dateFrom))}else this.dateComp.setDate(null);this.eReadOnlyText.setValue("")}else this.eReadOnlyText.setValue(this.getTextFromModel(e)),this.dateComp.setDate(null)}},e.prototype.onDateChanged=function(){var t=this,e=Jo(this.dateComp.getDate());this.params.parentFilterInstance((function(o){o&&o.onFloatingFilterChanged(t.getLastType(),e)}))},e.prototype.createDateComponent=function(){var t=this,e=ei.getDebounceMs(this.params.filterParams,this.getDefaultDebounceMs()),o={onDateChanged:$(this.onDateChanged.bind(this),e),filterParams:this.params.column.getColDef().filterParams};this.dateComp=new Yn(this.getContext(),this.userComponentFactory,o,this.eDateWrapper),this.addDestroyFunc((function(){return t.dateComp.destroy()}))},Or([it("userComponentFactory")],e.prototype,"userComponentFactory",void 0),Or([Wn("eReadOnlyText")],e.prototype,"eReadOnlyText",void 0),Or([Wn("eDateWrapper")],e.prototype,"eDateWrapper",void 0),e}(Er),Sr=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),br=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Dr=function(e){function o(){return e.call(this,"textFilter")||this}return Sr(o,e),o.trimInput=function(t){var e=t&&t.trim();return""===e?t:e},o.prototype.getDefaultDebounceMs=function(){return 500},o.prototype.getCleanValue=function(e){var n=t(e.getValue());return this.textFilterParams.trimInput?o.trimInput(n):n},o.prototype.addValueChangedListeners=function(){var t=this,e=function(){return t.onUiChanged()};this.eValue1.onValueChange(e),this.eValue2.onValueChange(e)},o.prototype.setParams=function(t){e.prototype.setParams.call(this,t),this.textFilterParams=t,this.comparator=this.textFilterParams.textCustomComparator||o.DEFAULT_COMPARATOR,this.formatter=this.textFilterParams.textFormatter||(this.textFilterParams.caseSensitive?o.DEFAULT_FORMATTER:o.DEFAULT_LOWERCASE_FORMATTER),this.addValueChangedListeners()},o.prototype.setConditionIntoUi=function(t,e){(e===Bn.One?this.eValue1:this.eValue2).setValue(t?t.filter:null)},o.prototype.createCondition=function(t){var e=t===Bn.One,o=e?this.getCondition1Type():this.getCondition2Type(),n=e?this.eValue1:this.eValue2,i=this.getCleanValue(n);n.setValue(i,!0);var r={filterType:this.getFilterType(),type:o};return this.doesFilterHaveHiddenInput(o)||(r.filter=i),r},o.prototype.getFilterType=function(){return"text"},o.prototype.areSimpleModelsEqual=function(t,e){return t.filter===e.filter&&t.type===e.type},o.prototype.resetUiToDefaults=function(t){var o=this;return e.prototype.resetUiToDefaults.call(this,t).then((function(){o.forEachInput((function(e){return e.setValue(null,t)})),o.resetPlaceholder()}))},o.prototype.resetPlaceholder=function(){var t=this.gridOptionsWrapper.getLocaleTextFunc(),e=this.translate("filterOoo");this.forEachInput((function(o){o.setInputPlaceholder(e),o.setInputAriaLabel(t("ariaFilterValue","Filter Value"))}))},o.prototype.forEachInput=function(t){P([this.eValue1,this.eValue2],t)},o.prototype.setValueFromFloatingFilter=function(t){this.eValue1.setValue(t),this.eValue2.setValue(null)},o.prototype.getDefaultFilterOptions=function(){return o.DEFAULT_FILTER_OPTIONS},o.prototype.createValueTemplate=function(t){var e=t===Bn.One?"1":"2";return'\n <div class="ag-filter-body" ref="eCondition'+e+'Body" role="presentation">\n <ag-input-text-field class="ag-filter-filter" ref="eValue'+e+'"></ag-input-text-field>\n </div>'},o.prototype.updateUiVisibility=function(){e.prototype.updateUiVisibility.call(this),ke(this.eCondition1Body,this.showValueFrom(this.getCondition1Type())),ke(this.eCondition2Body,this.isCondition2Enabled()&&this.showValueFrom(this.getCondition2Type()))},o.prototype.afterGuiAttached=function(t){e.prototype.afterGuiAttached.call(this,t),this.resetPlaceholder(),t&&t.suppressFocus||this.eValue1.getInputElement().focus()},o.prototype.isConditionUiComplete=function(t){var e=t===Bn.One,o=e?this.getCondition1Type():this.getCondition2Type();return o!==ri.EMPTY&&(!!this.doesFilterHaveHiddenInput(o)||null!=this.getCleanValue(e?this.eValue1:this.eValue2))},o.prototype.individualConditionPasses=function(t,e){var o=e.filter,n=e.type,i=this.textFilterParams.valueGetter(t.node),r=this.formatter(i),s=this.optionsFactory.getCustomOption(n);if(s&&(null!=o||s.hideFilterInput))return s.test(o,r);if(null==i)return n===ri.NOT_EQUAL||n===ri.NOT_CONTAINS;var a=this.formatter(o);return this.comparator(n,r,a)},o.DEFAULT_FILTER_OPTIONS=[ri.CONTAINS,ri.NOT_CONTAINS,ri.EQUALS,ri.NOT_EQUAL,ri.STARTS_WITH,ri.ENDS_WITH],o.DEFAULT_FORMATTER=function(t){return t},o.DEFAULT_LOWERCASE_FORMATTER=function(t){return null==t?null:t.toString().toLowerCase()},o.DEFAULT_COMPARATOR=function(t,e,n){switch(t){case o.CONTAINS:return e.indexOf(n)>=0;case o.NOT_CONTAINS:return e.indexOf(n)<0;case o.EQUALS:return e===n;case o.NOT_EQUAL:return e!=n;case o.STARTS_WITH:return 0===e.indexOf(n);case o.ENDS_WITH:var i=e.lastIndexOf(n);return i>=0&&i===e.length-n.length;default:return console.warn("invalid filter type "+t),!1}},br([Wn("eValue1")],o.prototype,"eValue1",void 0),br([Wn("eValue2")],o.prototype,"eValue2",void 0),o}(ri),Ar=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Tr=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},_r=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Ar(e,t),e.prototype.postConstruct=function(){this.setTemplate('\n <div class="ag-floating-filter-input" role="presentation">\n <ag-input-text-field ref="eFloatingFilterInput"></ag-input-text-field>\n </div>')},e.prototype.getDefaultDebounceMs=function(){return 500},e.prototype.onParentModelChanged=function(t,e){this.isEventFromFloatingFilter(e)||(this.setLastTypeFromModel(t),this.eFloatingFilterInput.setValue(this.getTextFromModel(t)),this.setEditable(this.canWeEditAfterModelFromParentFilter(t)))},e.prototype.init=function(e){t.prototype.init.call(this,e),this.params=e,this.applyActive=ei.isUseApplyButton(this.params.filterParams);var o=ei.getDebounceMs(this.params.filterParams,this.getDefaultDebounceMs()),n=$(this.syncUpWithParentFilter.bind(this),o),i=this.eFloatingFilterInput.getGui();this.addManagedListener(i,"input",n),this.addManagedListener(i,"keypress",n),this.addManagedListener(i,"keydown",n);var r=e.column.getDefinition();r.filterParams&&r.filterParams.filterOptions&&1===r.filterParams.filterOptions.length&&"inRange"===r.filterParams.filterOptions[0]&&this.eFloatingFilterInput.setDisabled(!0);var s=this.columnController.getDisplayNameForColumn(e.column,"header",!0),a=this.gridOptionsWrapper.getLocaleTextFunc();this.eFloatingFilterInput.setInputAriaLabel(s+" "+a("ariaFilterInput","Filter Input"))},e.prototype.syncUpWithParentFilter=function(t){var e=this,o=hn(t,jn.ENTER);if(!this.applyActive||o){var n=this.eFloatingFilterInput.getValue();this.params.filterParams.trimInput&&(n=Dr.trimInput(n),this.eFloatingFilterInput.setValue(n,!0)),this.params.parentFilterInstance((function(t){t&&t.onFloatingFilterChanged(e.getLastType(),n)}))}},e.prototype.setEditable=function(t){this.eFloatingFilterInput.setDisabled(!t)},Tr([it("columnController")],e.prototype,"columnController",void 0),Tr([Wn("eFloatingFilterInput")],e.prototype,"eFloatingFilterInput",void 0),Tr([et],e.prototype,"postConstruct",null),e}(Er),Fr=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Nr=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Fr(e,t),e.prototype.getDefaultFilterOptions=function(){return ur.DEFAULT_FILTER_OPTIONS},e.prototype.conditionToString=function(t){return t.type==ri.IN_RANGE?t.filter+"-"+t.filterTo:null!=t.filter?""+t.filter:""+t.type},e}(_r),Lr=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Ir=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Lr(e,t),e.prototype.conditionToString=function(t){return null!=t.filter?""+t.filter:""+t.type},e.prototype.getDefaultFilterOptions=function(){return Dr.DEFAULT_FILTER_OPTIONS},e}(_r),Gr=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Mr=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s};!function(t){t[t.DEFAULT=0]="DEFAULT",t[t.REGISTERED=1]="REGISTERED"}(Hi||(Hi={}));!function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.agGridDefaults={agDateInput:Cr,agColumnHeader:fi,agColumnGroupHeader:vi,agTextColumnFloatingFilter:Ir,agNumberColumnFloatingFilter:Nr,agDateColumnFloatingFilter:Pr,agAnimateShowChangeCellRenderer:zi,agAnimateSlideCellRenderer:qi,agGroupCellRenderer:Bi,agGroupRowRenderer:Bi,agLoadingCellRenderer:$i,agCellEditor:Kn,agTextCellEditor:Kn,agSelectCellEditor:tr,agPopupTextCellEditor:or,agPopupSelectCellEditor:ir,agLargeTextCellEditor:ar,agTextColumnFilter:Dr,agNumberColumnFilter:ur,agDateColumnFilter:ui,agLoadingOverlay:dr,agNoRowsOverlay:fr,agTooltipComponent:yr},e.agDeprecatedNames={set:{newComponentName:"agSetColumnFilter",propertyHolder:"filter"},text:{newComponentName:"agTextColumnFilter",propertyHolder:"filter"},number:{newComponentName:"agNumberColumnFilter",propertyHolder:"filter"},date:{newComponentName:"agDateColumnFilter",propertyHolder:"filter"},group:{newComponentName:"agGroupCellRenderer",propertyHolder:"cellRenderer"},animateShowChange:{newComponentName:"agAnimateShowChangeCellRenderer",propertyHolder:"cellRenderer"},animateSlide:{newComponentName:"agAnimateSlideCellRenderer",propertyHolder:"cellRenderer"},select:{newComponentName:"agSelectCellEditor",propertyHolder:"cellEditor"},largeText:{newComponentName:"agLargeTextCellEditor",propertyHolder:"cellEditor"},popupSelect:{newComponentName:"agPopupSelectCellEditor",propertyHolder:"cellEditor"},popupText:{newComponentName:"agPopupTextCellEditor",propertyHolder:"cellEditor"},richSelect:{newComponentName:"agRichSelectCellEditor",propertyHolder:"cellEditor"},headerComponent:{newComponentName:"agColumnHeader",propertyHolder:"headerComponent"}},e.jsComponents={},e.frameworkComponents={},e}Gr(e,t),e.prototype.init=function(){var t=this;null!=this.gridOptions.components&&A(this.gridOptions.components,(function(e,o){return t.registerComponent(e,o)})),null!=this.gridOptions.frameworkComponents&&A(this.gridOptions.frameworkComponents,(function(e,o){return t.registerFwComponent(e,o)}))},e.prototype.registerDefaultComponent=function(t,e){var o=this.translateIfDeprecated(t);this.agGridDefaults[o]?console.error("Trying to overwrite a default component. You should call registerComponent"):this.agGridDefaults[o]=e},e.prototype.registerComponent=function(t,e){var o=this.translateIfDeprecated(t);this.frameworkComponents[o]?console.error("Trying to register a component that you have already registered for frameworks: "+o):this.jsComponents[o]=e},e.prototype.registerFwComponent=function(t,e){var o=this.translateIfDeprecated(t);this.jsComponents[o]?console.error("Trying to register a component that you have already registered for plain javascript: "+o):this.frameworkComponents[o]=e},e.prototype.retrieve=function(t){var e=this.translateIfDeprecated(t),o=this.frameworkComponents[e];if(o)return{componentFromFramework:!0,component:o,source:Hi.REGISTERED};var n=this.jsComponents[e];if(n)return{componentFromFramework:!1,component:n,source:Hi.REGISTERED};var i=this.agGridDefaults[e];return i?{componentFromFramework:!1,component:i,source:Hi.DEFAULT}:(Object.keys(this.agGridDefaults).indexOf(e)<0&&console.warn("AG Grid: Looking for component ["+e+"] but it wasn't found."),null)},e.prototype.translateIfDeprecated=function(t){var e=this.agDeprecatedNames[t];return null!=e?(z((function(){console.warn("ag-grid. Since v15.0 component names have been renamed to be namespaced. You should rename "+e.propertyHolder+":"+t+" to "+e.propertyHolder+":"+e.newComponentName)}),"DEPRECATE_COMPONENT_"+t),e.newComponentName):t},Mr([it("gridOptions")],e.prototype,"gridOptions",void 0),Mr([et],e.prototype,"init",null),e=Mr([nt("userComponentRegistry")],e)}(Mt);
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/var xr=function(){function t(){}return t.parse=function(e){if(!e)return null;if(!0===e)return{toolPanels:[t.DEFAULT_COLUMN_COMP,t.DEFAULT_FILTER_COMP],defaultToolPanel:"columns"};if("string"==typeof e)return t.parse([e]);if(Array.isArray(e)){var o=[];return e.forEach((function(e){var n=t.DEFAULT_BY_KEY[e];n?o.push(n):console.warn("ag-grid: the key "+e+" is not a valid key for specifying a tool panel, valid keys are: "+Object.keys(t.DEFAULT_BY_KEY).join(","))})),0===o.length?null:{toolPanels:o,defaultToolPanel:o[0].id}}return{toolPanels:t.parseComponents(e.toolPanels),defaultToolPanel:e.defaultToolPanel,hiddenByDefault:e.hiddenByDefault,position:e.position}},t.parseComponents=function(e){var o=[];return e?(e.forEach((function(e){var n=null;if("string"==typeof e){var i=t.DEFAULT_BY_KEY[e];if(!i)return void console.warn("ag-grid: the key "+e+" is not a valid key for specifying a tool panel, valid keys are: "+Object.keys(t.DEFAULT_BY_KEY).join(","));n=i}else n=e;o.push(n)})),o):o},t.DEFAULT_COLUMN_COMP={id:"columns",labelDefault:"Columns",labelKey:"columns",iconKey:"columns",toolPanel:"agColumnsToolPanel"},t.DEFAULT_FILTER_COMP={id:"filters",labelDefault:"Filters",labelKey:"filters",iconKey:"filter",toolPanel:"agFiltersToolPanel"},t.DEFAULT_BY_KEY={columns:t.DEFAULT_COLUMN_COMP,filters:t.DEFAULT_FILTER_COMP},t}(),Vr=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Hr=function(t,e){return function(o,n){e(o,n,t)}},Wr=function(){for(var t=0,e=0,o=arguments.length;e<o;e++)t+=arguments[e].length;var n=Array(t),i=0;for(e=0;e<o;e++)for(var r=arguments[e],s=0,a=r.length;s<a;s++,i++)n[i]=r[s];return n};function kr(t){return!0===t||"true"===t}function Br(t,e){var o=parseInt(t,10);return ee(o)&&o>0?o:e}var jr,Ur,zr=function(){function t(){this.propertyEventService=new dt,this.domDataKey="__AG_"+Math.random().toString(),this.layoutElements=[],this.destroyed=!1}var n;return n=t,t.prototype.agWire=function(t,e){this.gridOptions.api=t,this.gridOptions.columnApi=e,this.checkForDeprecated(),this.checkForViolations()},t.prototype.destroy=function(){this.gridOptions.api=null,this.gridOptions.columnApi=null,this.removeEventListener(n.PROP_DOM_LAYOUT,this.updateLayoutClassesListener),this.destroyed=!0},t.prototype.init=function(){var t=this;!0!==this.gridOptions.suppressPropertyNamesCheck&&(this.checkGridOptionsProperties(),this.checkColumnDefProperties()),null!=this.gridOptions.sideBar&&(this.gridOptions.sideBar=xr.parse(this.gridOptions.sideBar));var o=this.useAsyncEvents();if(this.eventService.addGlobalListener(this.globalEventHandler.bind(this),o),this.isGroupSelectsChildren()&&this.isSuppressParentsInRowNodes()&&console.warn("AG Grid: 'groupSelectsChildren' does not work with 'suppressParentsInRowNodes', this selection method needs the part in rowNode to work"),this.isGroupSelectsChildren()&&(this.isRowSelectionMulti()||console.warn("AG Grid: rowSelection must be 'multiple' for groupSelectsChildren to make sense"),this.isRowModelServerSide()&&console.warn("AG Grid: group selects children is NOT support for Server Side Row Model. This is because the rows are lazy loaded, so selecting a group is not possible asthe grid has no way of knowing what the children are.")),this.isGroupRemoveSingleChildren()&&this.isGroupHideOpenParents()&&console.warn("AG Grid: groupRemoveSingleChildren and groupHideOpenParents do not work with each other, you need to pick one. And don't ask us how to us these together on our support forum either you will get the same answer!"),this.isRowModelServerSide()){var i=function(t){return"AG Grid: '"+t+"' is not supported on the Server-Side Row Model"};e(this.gridOptions.groupDefaultExpanded)&&console.warn(i("groupDefaultExpanded")),e(this.gridOptions.groupDefaultExpanded)&&console.warn(i("groupIncludeFooter")),e(this.gridOptions.groupDefaultExpanded)&&console.warn(i("groupIncludeTotalFooter"))}this.isEnableRangeSelection()&&ft.assertRegistered(pt.RangeSelectionModule,"enableRangeSelection"),this.isEnableRangeSelection()||!this.isEnableRangeHandle()&&!this.isEnableFillHandle()||console.warn("AG Grid: 'enableRangeHandle' and 'enableFillHandle' will not work unless 'enableRangeSelection' is set to true");var r=function(e){t.gridOptions.icons&&t.gridOptions.icons[e]&&console.warn("gridOptions.icons."+e+" is no longer supported. For information on how to style checkboxes and radio buttons, see https://www.ag-grid.com/javascript-grid-icons/")};r("radioButtonOff"),r("radioButtonOn"),r("checkboxChecked"),r("checkboxUnchecked"),r("checkboxIndeterminate"),this.updateLayoutClassesListener=this.updateLayoutClasses.bind(this),this.addEventListener(n.PROP_DOM_LAYOUT,this.updateLayoutClassesListener),this.getScrollbarWidth()},t.prototype.checkColumnDefProperties=function(){var t=this;null!=this.gridOptions.columnDefs&&this.gridOptions.columnDefs.forEach((function(e){var o=Object.getOwnPropertyNames(e),n=Wr(fe.ALL_PROPERTIES,fe.FRAMEWORK_PROPERTIES);t.checkProperties(o,n,n,"colDef","https://www.ag-grid.com/javascript-grid-column-properties/")}))},t.prototype.checkGridOptionsProperties=function(){var t=Object.getOwnPropertyNames(this.gridOptions),e=Wr(ue.ALL_PROPERTIES,ue.FRAMEWORK_PROPERTIES,l(Wt).map((function(t){return de.getCallbackForEvent(t)}))),o=Wr(e,["api","columnApi"]);this.checkProperties(t,o,e,"gridOptions","https://www.ag-grid.com/javascript-grid-properties/")},t.prototype.checkProperties=function(t,e,o,n,i){var r=on(t,e,o);A(r,(function(t,e){console.warn("ag-grid: invalid "+n+" property '"+t+"' did you mean any of these: "+e.slice(0,8).join(", "))})),Object.keys(r).length>0&&console.warn("ag-grid: to see all the valid "+n+" properties please check: "+i)},t.prototype.getDomDataKey=function(){return this.domDataKey},t.prototype.getDomData=function(t,e){var o=t[this.getDomDataKey()];return o?o[e]:void 0},t.prototype.setDomData=function(t,e,n){var i=this.getDomDataKey(),r=t[i];o(r)&&(r={},t[i]=r),r[e]=n},t.prototype.isRowSelection=function(){return"single"===this.gridOptions.rowSelection||"multiple"===this.gridOptions.rowSelection},t.prototype.isSuppressRowDeselection=function(){return kr(this.gridOptions.suppressRowDeselection)},t.prototype.isRowSelectionMulti=function(){return"multiple"===this.gridOptions.rowSelection},t.prototype.isRowMultiSelectWithClick=function(){return kr(this.gridOptions.rowMultiSelectWithClick)},t.prototype.getContext=function(){return this.gridOptions.context},t.prototype.isPivotMode=function(){return kr(this.gridOptions.pivotMode)},t.prototype.isSuppressExpandablePivotGroups=function(){return kr(this.gridOptions.suppressExpandablePivotGroups)},t.prototype.getPivotColumnGroupTotals=function(){return this.gridOptions.pivotColumnGroupTotals},t.prototype.getPivotRowTotals=function(){return this.gridOptions.pivotRowTotals},t.prototype.isRowModelInfinite=function(){return this.gridOptions.rowModelType===ht.ROW_MODEL_TYPE_INFINITE},t.prototype.isRowModelViewport=function(){return this.gridOptions.rowModelType===ht.ROW_MODEL_TYPE_VIEWPORT},t.prototype.isRowModelServerSide=function(){return this.gridOptions.rowModelType===ht.ROW_MODEL_TYPE_SERVER_SIDE},t.prototype.isRowModelDefault=function(){return o(this.gridOptions.rowModelType)||this.gridOptions.rowModelType===ht.ROW_MODEL_TYPE_CLIENT_SIDE},t.prototype.isFullRowEdit=function(){return"fullRow"===this.gridOptions.editType},t.prototype.isSuppressFocusAfterRefresh=function(){return kr(this.gridOptions.suppressFocusAfterRefresh)},t.prototype.isSuppressBrowserResizeObserver=function(){return kr(this.gridOptions.suppressBrowserResizeObserver)},t.prototype.isSuppressMaintainUnsortedOrder=function(){return kr(this.gridOptions.suppressMaintainUnsortedOrder)},t.prototype.isSuppressClearOnFillReduction=function(){return kr(this.gridOptions.suppressClearOnFillReduction)},t.prototype.isShowToolPanel=function(){return kr(this.gridOptions.sideBar&&Array.isArray(this.getSideBar().toolPanels))},t.prototype.getSideBar=function(){return this.gridOptions.sideBar},t.prototype.isSuppressTouch=function(){return kr(this.gridOptions.suppressTouch)},t.prototype.isApplyColumnDefOrder=function(){return kr(this.gridOptions.applyColumnDefOrder)},t.prototype.isSuppressRowTransform=function(){return kr(this.gridOptions.suppressRowTransform)},t.prototype.isSuppressColumnStateEvents=function(){return kr(this.gridOptions.suppressColumnStateEvents)},t.prototype.isAllowDragFromColumnsToolPanel=function(){return kr(this.gridOptions.allowDragFromColumnsToolPanel)},t.prototype.useAsyncEvents=function(){return!kr(this.gridOptions.suppressAsyncEvents)},t.prototype.isEnableCellChangeFlash=function(){return kr(this.gridOptions.enableCellChangeFlash)},t.prototype.getCellFlashDelay=function(){return this.gridOptions.cellFlashDelay||500},t.prototype.getCellFadeDelay=function(){return this.gridOptions.cellFadeDelay||1e3},t.prototype.isGroupSelectsChildren=function(){var t=kr(this.gridOptions.groupSelectsChildren);return t&&this.isTreeData()?(console.warn("AG Grid: groupSelectsChildren does not work with tree data"),!1):t},t.prototype.isSuppressRowHoverHighlight=function(){return kr(this.gridOptions.suppressRowHoverHighlight)},t.prototype.isGroupSelectsFiltered=function(){return kr(this.gridOptions.groupSelectsFiltered)},t.prototype.isGroupHideOpenParents=function(){return kr(this.gridOptions.groupHideOpenParents)},t.prototype.isGroupMultiAutoColumn=function(){return kr(this.gridOptions.groupMultiAutoColumn)||kr(this.gridOptions.groupHideOpenParents)},t.prototype.isGroupRemoveSingleChildren=function(){return kr(this.gridOptions.groupRemoveSingleChildren)},t.prototype.isGroupRemoveLowestSingleChildren=function(){return kr(this.gridOptions.groupRemoveLowestSingleChildren)},t.prototype.isGroupIncludeFooter=function(){return kr(this.gridOptions.groupIncludeFooter)},t.prototype.isGroupIncludeTotalFooter=function(){return kr(this.gridOptions.groupIncludeTotalFooter)},t.prototype.isGroupSuppressBlankHeader=function(){return kr(this.gridOptions.groupSuppressBlankHeader)},t.prototype.isSuppressRowClickSelection=function(){return kr(this.gridOptions.suppressRowClickSelection)},t.prototype.isSuppressCellSelection=function(){return kr(this.gridOptions.suppressCellSelection)},t.prototype.isSuppressMultiSort=function(){return kr(this.gridOptions.suppressMultiSort)},t.prototype.isMultiSortKeyCtrl=function(){return"ctrl"===this.gridOptions.multiSortKey},t.prototype.isGroupSuppressAutoColumn=function(){return kr(this.gridOptions.groupSuppressAutoColumn)},t.prototype.isPivotSuppressAutoColumn=function(){return kr(this.gridOptions.pivotSuppressAutoColumn)},t.prototype.isSuppressDragLeaveHidesColumns=function(){return kr(this.gridOptions.suppressDragLeaveHidesColumns)},t.prototype.isSuppressScrollOnNewData=function(){return kr(this.gridOptions.suppressScrollOnNewData)},t.prototype.isRowDragManaged=function(){return kr(this.gridOptions.rowDragManaged)},t.prototype.isSuppressRowDrag=function(){return kr(this.gridOptions.suppressRowDrag)},t.prototype.isSuppressMoveWhenRowDragging=function(){return kr(this.gridOptions.suppressMoveWhenRowDragging)},t.prototype.isEnableMultiRowDragging=function(){return kr(this.gridOptions.enableMultiRowDragging)},t.prototype.getDomLayout=function(){var t=this.gridOptions.domLayout||ht.DOM_LAYOUT_NORMAL;return-1===[ht.DOM_LAYOUT_PRINT,ht.DOM_LAYOUT_AUTO_HEIGHT,ht.DOM_LAYOUT_NORMAL].indexOf(t)?(z((function(){return console.warn("AG Grid: "+t+" is not valid for DOM Layout, valid values are "+ht.DOM_LAYOUT_NORMAL+", "+ht.DOM_LAYOUT_AUTO_HEIGHT+" and "+ht.DOM_LAYOUT_PRINT)}),"warn about dom layout values"),ht.DOM_LAYOUT_NORMAL):t},t.prototype.isSuppressHorizontalScroll=function(){return kr(this.gridOptions.suppressHorizontalScroll)},t.prototype.isSuppressMaxRenderedRowRestriction=function(){return kr(this.gridOptions.suppressMaxRenderedRowRestriction)},t.prototype.isExcludeChildrenWhenTreeDataFiltering=function(){return kr(this.gridOptions.excludeChildrenWhenTreeDataFiltering)},t.prototype.isAlwaysShowHorizontalScroll=function(){return kr(this.gridOptions.alwaysShowHorizontalScroll)},t.prototype.isAlwaysShowVerticalScroll=function(){return kr(this.gridOptions.alwaysShowVerticalScroll)},t.prototype.isDebounceVerticalScrollbar=function(){return kr(this.gridOptions.debounceVerticalScrollbar)},t.prototype.isSuppressLoadingOverlay=function(){return kr(this.gridOptions.suppressLoadingOverlay)},t.prototype.isSuppressNoRowsOverlay=function(){return kr(this.gridOptions.suppressNoRowsOverlay)},t.prototype.isSuppressFieldDotNotation=function(){return kr(this.gridOptions.suppressFieldDotNotation)},t.prototype.getPinnedTopRowData=function(){return this.gridOptions.pinnedTopRowData},t.prototype.getPinnedBottomRowData=function(){return this.gridOptions.pinnedBottomRowData},t.prototype.isFunctionsPassive=function(){return kr(this.gridOptions.functionsPassive)},t.prototype.isSuppressChangeDetection=function(){return kr(this.gridOptions.suppressChangeDetection)},t.prototype.isSuppressAnimationFrame=function(){return kr(this.gridOptions.suppressAnimationFrame)},t.prototype.getQuickFilterText=function(){return this.gridOptions.quickFilterText},t.prototype.isCacheQuickFilter=function(){return kr(this.gridOptions.cacheQuickFilter)},t.prototype.isUnSortIcon=function(){return kr(this.gridOptions.unSortIcon)},t.prototype.isSuppressMenuHide=function(){return kr(this.gridOptions.suppressMenuHide)},t.prototype.isEnterMovesDownAfterEdit=function(){return kr(this.gridOptions.enterMovesDownAfterEdit)},t.prototype.isEnterMovesDown=function(){return kr(this.gridOptions.enterMovesDown)},t.prototype.isUndoRedoCellEditing=function(){return kr(this.gridOptions.undoRedoCellEditing)},t.prototype.getUndoRedoCellEditingLimit=function(){return this.gridOptions.undoRedoCellEditingLimit},t.prototype.getRowStyle=function(){return this.gridOptions.rowStyle},t.prototype.getRowClass=function(){return this.gridOptions.rowClass},t.prototype.getRowStyleFunc=function(){return this.gridOptions.getRowStyle},t.prototype.getRowClassFunc=function(){return this.gridOptions.getRowClass},t.prototype.rowClassRules=function(){return this.gridOptions.rowClassRules},t.prototype.getServerSideStoreType=function(){return this.gridOptions.serverSideStoreType},t.prototype.getServerSideStoreParamsFunc=function(){return this.gridOptions.getServerSideStoreParams},t.prototype.getCreateChartContainerFunc=function(){return this.gridOptions.createChartContainer},t.prototype.getPopupParent=function(){return this.gridOptions.popupParent},t.prototype.getBlockLoadDebounceMillis=function(){return this.gridOptions.blockLoadDebounceMillis},t.prototype.getPostProcessPopupFunc=function(){return this.gridOptions.postProcessPopup},t.prototype.getPaginationNumberFormatterFunc=function(){return this.gridOptions.paginationNumberFormatter},t.prototype.getChildCountFunc=function(){return this.gridOptions.getChildCount},t.prototype.getIsApplyServerSideTransactionFunc=function(){return this.gridOptions.isApplyServerSideTransaction},t.prototype.getDefaultGroupSortComparator=function(){return this.gridOptions.defaultGroupSortComparator},t.prototype.getIsFullWidthCellFunc=function(){return this.gridOptions.isFullWidthCell},t.prototype.getFullWidthCellRendererParams=function(){return this.gridOptions.fullWidthCellRendererParams},t.prototype.isEmbedFullWidthRows=function(){return kr(this.gridOptions.embedFullWidthRows)||kr(this.gridOptions.deprecatedEmbedFullWidthRows)},t.prototype.isDetailRowAutoHeight=function(){return kr(this.gridOptions.detailRowAutoHeight)},t.prototype.getSuppressKeyboardEventFunc=function(){return this.gridOptions.suppressKeyboardEvent},t.prototype.getBusinessKeyForNodeFunc=function(){return this.gridOptions.getBusinessKeyForNode},t.prototype.getApi=function(){return this.gridOptions.api},t.prototype.getColumnApi=function(){return this.gridOptions.columnApi},t.prototype.isImmutableData=function(){return kr(this.gridOptions.immutableData)},t.prototype.isEnsureDomOrder=function(){return kr(this.gridOptions.ensureDomOrder)},t.prototype.isEnableCharts=function(){return!!kr(this.gridOptions.enableCharts)&&ft.assertRegistered(pt.GridChartsModule,"enableCharts")},t.prototype.getColResizeDefault=function(){return this.gridOptions.colResizeDefault},t.prototype.isSingleClickEdit=function(){return kr(this.gridOptions.singleClickEdit)},t.prototype.isSuppressClickEdit=function(){return kr(this.gridOptions.suppressClickEdit)},t.prototype.isStopEditingWhenGridLosesFocus=function(){return kr(this.gridOptions.stopEditingWhenGridLosesFocus)},t.prototype.getGroupDefaultExpanded=function(){return this.gridOptions.groupDefaultExpanded},t.prototype.getMaxConcurrentDatasourceRequests=function(){return this.gridOptions.maxConcurrentDatasourceRequests},t.prototype.getMaxBlocksInCache=function(){return this.gridOptions.maxBlocksInCache},t.prototype.getCacheOverflowSize=function(){return this.gridOptions.cacheOverflowSize},t.prototype.getPaginationPageSize=function(){return"number"==typeof(t=this.gridOptions.paginationPageSize)?t:"string"==typeof t?parseInt(t,10):void 0;var t},t.prototype.isPaginateChildRows=function(){return!(!this.isGroupRemoveSingleChildren()&&!this.isGroupRemoveLowestSingleChildren())||kr(this.gridOptions.paginateChildRows)},t.prototype.getCacheBlockSize=function(){return Br(this.gridOptions.cacheBlockSize)},t.prototype.getInfiniteInitialRowCount=function(){return this.gridOptions.infiniteInitialRowCount},t.prototype.isPurgeClosedRowNodes=function(){return kr(this.gridOptions.purgeClosedRowNodes)},t.prototype.isSuppressPaginationPanel=function(){return kr(this.gridOptions.suppressPaginationPanel)},t.prototype.getRowData=function(){return this.gridOptions.rowData},t.prototype.isGroupUseEntireRow=function(t){return!t&&kr(this.gridOptions.groupUseEntireRow)},t.prototype.isEnableRtl=function(){return kr(this.gridOptions.enableRtl)},t.prototype.getAutoGroupColumnDef=function(){return this.gridOptions.autoGroupColumnDef},t.prototype.getRowGroupPanelShow=function(){return this.gridOptions.rowGroupPanelShow},t.prototype.getPivotPanelShow=function(){return this.gridOptions.pivotPanelShow},t.prototype.isAngularCompileRows=function(){return kr(this.gridOptions.angularCompileRows)},t.prototype.isAngularCompileFilters=function(){return kr(this.gridOptions.angularCompileFilters)},t.prototype.isDebug=function(){return kr(this.gridOptions.debug)},t.prototype.getColumnDefs=function(){return this.gridOptions.columnDefs},t.prototype.getColumnTypes=function(){return this.gridOptions.columnTypes},t.prototype.getDatasource=function(){return this.gridOptions.datasource},t.prototype.getViewportDatasource=function(){return this.gridOptions.viewportDatasource},t.prototype.getServerSideDatasource=function(){return this.gridOptions.serverSideDatasource},t.prototype.isAccentedSort=function(){return kr(this.gridOptions.accentedSort)},t.prototype.isEnableBrowserTooltips=function(){return kr(this.gridOptions.enableBrowserTooltips)},t.prototype.isEnableCellExpressions=function(){return kr(this.gridOptions.enableCellExpressions)},t.prototype.isEnableGroupEdit=function(){return kr(this.gridOptions.enableGroupEdit)},t.prototype.isSuppressMiddleClickScrolls=function(){return kr(this.gridOptions.suppressMiddleClickScrolls)},t.prototype.isPreventDefaultOnContextMenu=function(){return kr(this.gridOptions.preventDefaultOnContextMenu)},t.prototype.isSuppressPreventDefaultOnMouseWheel=function(){return kr(this.gridOptions.suppressPreventDefaultOnMouseWheel)},t.prototype.isSuppressColumnVirtualisation=function(){return kr(this.gridOptions.suppressColumnVirtualisation)},t.prototype.isSuppressContextMenu=function(){return kr(this.gridOptions.suppressContextMenu)},t.prototype.isAllowContextMenuWithControlKey=function(){return kr(this.gridOptions.allowContextMenuWithControlKey)},t.prototype.isSuppressCopyRowsToClipboard=function(){return kr(this.gridOptions.suppressCopyRowsToClipboard)},t.prototype.isCopyHeadersToClipboard=function(){return kr(this.gridOptions.copyHeadersToClipboard)},t.prototype.isSuppressClipboardPaste=function(){return kr(this.gridOptions.suppressClipboardPaste)},t.prototype.isSuppressLastEmptyLineOnPaste=function(){return kr(this.gridOptions.suppressLastEmptyLineOnPaste)},t.prototype.isPagination=function(){return kr(this.gridOptions.pagination)},t.prototype.isSuppressEnterpriseResetOnNewColumns=function(){return kr(this.gridOptions.suppressEnterpriseResetOnNewColumns)},t.prototype.getProcessDataFromClipboardFunc=function(){return this.gridOptions.processDataFromClipboard},t.prototype.getAsyncTransactionWaitMillis=function(){return e(this.gridOptions.asyncTransactionWaitMillis)?this.gridOptions.asyncTransactionWaitMillis:ht.BATCH_WAIT_MILLIS},t.prototype.isSuppressMovableColumns=function(){return kr(this.gridOptions.suppressMovableColumns)},t.prototype.isAnimateRows=function(){return!this.isEnsureDomOrder()&&kr(this.gridOptions.animateRows)},t.prototype.isSuppressColumnMoveAnimation=function(){return kr(this.gridOptions.suppressColumnMoveAnimation)},t.prototype.isSuppressAggFuncInHeader=function(){return kr(this.gridOptions.suppressAggFuncInHeader)},t.prototype.isSuppressAggAtRootLevel=function(){return kr(this.gridOptions.suppressAggAtRootLevel)},t.prototype.isSuppressAggFilteredOnly=function(){return kr(this.gridOptions.suppressAggFilteredOnly)},t.prototype.isShowOpenedGroup=function(){return kr(this.gridOptions.showOpenedGroup)},t.prototype.isEnableRangeSelection=function(){return ft.isRegistered(pt.RangeSelectionModule)&&kr(this.gridOptions.enableRangeSelection)},t.prototype.isEnableRangeHandle=function(){return kr(this.gridOptions.enableRangeHandle)},t.prototype.isEnableFillHandle=function(){return kr(this.gridOptions.enableFillHandle)},t.prototype.getFillHandleDirection=function(){var t=this.gridOptions.fillHandleDirection;return t?"x"!==t&&"y"!==t&&"xy"!==t?(z((function(){return console.warn("AG Grid: valid values for fillHandleDirection are 'x', 'y' and 'xy'. Default to 'xy'.")}),"warn invalid fill direction"),"xy"):t:"xy"},t.prototype.getFillOperation=function(){return this.gridOptions.fillOperation},t.prototype.isSuppressMultiRangeSelection=function(){return kr(this.gridOptions.suppressMultiRangeSelection)},t.prototype.isPaginationAutoPageSize=function(){return kr(this.gridOptions.paginationAutoPageSize)},t.prototype.isRememberGroupStateWhenNewData=function(){return kr(this.gridOptions.rememberGroupStateWhenNewData)},t.prototype.getIcons=function(){return this.gridOptions.icons},t.prototype.getAggFuncs=function(){return this.gridOptions.aggFuncs},t.prototype.getSortingOrder=function(){return this.gridOptions.sortingOrder},t.prototype.getAlignedGrids=function(){return this.gridOptions.alignedGrids},t.prototype.isMasterDetail=function(){return!!kr(this.gridOptions.masterDetail)&&ft.assertRegistered(pt.MasterDetailModule,"masterDetail")},t.prototype.isKeepDetailRows=function(){return kr(this.gridOptions.keepDetailRows)},t.prototype.getKeepDetailRowsCount=function(){var t=this.gridOptions.keepDetailRowsCount;return e(t)&&t>0?this.gridOptions.keepDetailRowsCount:10},t.prototype.getIsRowMasterFunc=function(){return this.gridOptions.isRowMaster},t.prototype.getIsRowSelectableFunc=function(){return this.gridOptions.isRowSelectable},t.prototype.getGroupRowRendererParams=function(){return this.gridOptions.groupRowRendererParams},t.prototype.getOverlayLoadingTemplate=function(){return this.gridOptions.overlayLoadingTemplate},t.prototype.getOverlayNoRowsTemplate=function(){return this.gridOptions.overlayNoRowsTemplate},t.prototype.isSuppressAutoSize=function(){return kr(this.gridOptions.suppressAutoSize)},t.prototype.isEnableCellTextSelection=function(){return kr(this.gridOptions.enableCellTextSelection)},t.prototype.isSuppressParentsInRowNodes=function(){return kr(this.gridOptions.suppressParentsInRowNodes)},t.prototype.isSuppressClipboardApi=function(){return kr(this.gridOptions.suppressClipboardApi)},t.prototype.isFunctionsReadOnly=function(){return kr(this.gridOptions.functionsReadOnly)},t.prototype.isFloatingFilter=function(){return this.gridOptions.floatingFilter},t.prototype.isEnableCellTextSelect=function(){return kr(this.gridOptions.enableCellTextSelection)},t.prototype.isEnableOldSetFilterModel=function(){return kr(this.gridOptions.enableOldSetFilterModel)},t.prototype.getDefaultColDef=function(){return this.gridOptions.defaultColDef},t.prototype.getDefaultColGroupDef=function(){return this.gridOptions.defaultColGroupDef},t.prototype.getDefaultExportParams=function(){return this.gridOptions.defaultExportParams},t.prototype.isSuppressCsvExport=function(){return kr(this.gridOptions.suppressCsvExport)},t.prototype.isAllowShowChangeAfterFilter=function(){return kr(this.gridOptions.allowShowChangeAfterFilter)},t.prototype.isSuppressExcelExport=function(){return kr(this.gridOptions.suppressExcelExport)},t.prototype.isSuppressMakeColumnVisibleAfterUnGroup=function(){return kr(this.gridOptions.suppressMakeColumnVisibleAfterUnGroup)},t.prototype.getDataPathFunc=function(){return this.gridOptions.getDataPath},t.prototype.getIsServerSideGroupFunc=function(){return this.gridOptions.isServerSideGroup},t.prototype.getIsServerSideGroupOpenByDefaultFunc=function(){return this.gridOptions.isServerSideGroupOpenByDefault},t.prototype.getServerSideGroupKeyFunc=function(){return this.gridOptions.getServerSideGroupKey},t.prototype.getGroupRowAggNodesFunc=function(){return this.gridOptions.groupRowAggNodes},t.prototype.getContextMenuItemsFunc=function(){return this.gridOptions.getContextMenuItems},t.prototype.getMainMenuItemsFunc=function(){return this.gridOptions.getMainMenuItems},t.prototype.getRowNodeIdFunc=function(){return this.gridOptions.getRowNodeId},t.prototype.getNavigateToNextHeaderFunc=function(){return this.gridOptions.navigateToNextHeader},t.prototype.getTabToNextHeaderFunc=function(){return this.gridOptions.tabToNextHeader},t.prototype.getNavigateToNextCellFunc=function(){return this.gridOptions.navigateToNextCell},t.prototype.getTabToNextCellFunc=function(){return this.gridOptions.tabToNextCell},t.prototype.isTreeData=function(){return!!kr(this.gridOptions.treeData)&&ft.assertRegistered(pt.RowGroupingModule,"Tree Data")},t.prototype.isValueCache=function(){return kr(this.gridOptions.valueCache)},t.prototype.isValueCacheNeverExpires=function(){return kr(this.gridOptions.valueCacheNeverExpires)},t.prototype.isDeltaSort=function(){return kr(this.gridOptions.deltaSort)},t.prototype.isAggregateOnlyChangedColumns=function(){return kr(this.gridOptions.aggregateOnlyChangedColumns)},t.prototype.getProcessSecondaryColDefFunc=function(){return this.gridOptions.processSecondaryColDef},t.prototype.getProcessSecondaryColGroupDefFunc=function(){return this.gridOptions.processSecondaryColGroupDef},t.prototype.getSendToClipboardFunc=function(){return this.gridOptions.sendToClipboard},t.prototype.getProcessRowPostCreateFunc=function(){return this.gridOptions.processRowPostCreate},t.prototype.getProcessCellForClipboardFunc=function(){return this.gridOptions.processCellForClipboard},t.prototype.getProcessHeaderForClipboardFunc=function(){return this.gridOptions.processHeaderForClipboard},t.prototype.getProcessCellFromClipboardFunc=function(){return this.gridOptions.processCellFromClipboard},t.prototype.getViewportRowModelPageSize=function(){return Br(this.gridOptions.viewportRowModelPageSize,5)},t.prototype.getViewportRowModelBufferSize=function(){return t=this.gridOptions.viewportRowModelBufferSize,e=5,t>=0?t:e;var t,e},t.prototype.isServerSideSortingAlwaysResets=function(){return kr(this.gridOptions.serverSideSortingAlwaysResets)},t.prototype.isServerSideFilteringAlwaysResets=function(){return kr(this.gridOptions.serverSideFilteringAlwaysResets)},t.prototype.getPostSortFunc=function(){return this.gridOptions.postSort},t.prototype.getChartToolbarItemsFunc=function(){return this.gridOptions.getChartToolbarItems},t.prototype.getChartThemeOverrides=function(){return this.gridOptions.chartThemeOverrides},t.prototype.getCustomChartThemes=function(){return this.gridOptions.customChartThemes},t.prototype.getChartThemes=function(){return this.gridOptions.chartThemes||["ag-default","ag-material","ag-pastel","ag-vivid","ag-solar"]},t.prototype.getProcessChartOptionsFunc=function(){return this.gridOptions.processChartOptions},t.prototype.getClipboardDeliminator=function(){return e(this.gridOptions.clipboardDeliminator)?this.gridOptions.clipboardDeliminator:"\t"},t.prototype.setProperty=function(t,e,o){void 0===o&&(o=!1);var n=this.gridOptions,i=n[t];if(o||i!==e){n[t]=e;var r={type:t,currentValue:e,previousValue:i};this.propertyEventService.dispatchEvent(r)}},t.prototype.addLayoutElement=function(t){this.layoutElements.push(t),this.updateLayoutClasses()},t.prototype.updateLayoutClasses=function(){var t=this.getDomLayout(),e=t===ht.DOM_LAYOUT_AUTO_HEIGHT,o=t===ht.DOM_LAYOUT_PRINT,n=t===ht.DOM_LAYOUT_NORMAL;this.layoutElements.forEach((function(t){Ve(t,"ag-layout-auto-height",e),Ve(t,"ag-layout-normal",n),Ve(t,"ag-layout-print",o)}))},t.prototype.addEventListener=function(t,e){this.propertyEventService.addEventListener(t,e)},t.prototype.removeEventListener=function(t,e){this.propertyEventService.removeEventListener(t,e)},t.prototype.isSkipHeaderOnAutoSize=function(){return!!this.gridOptions.skipHeaderOnAutoSize},t.prototype.getAutoSizePadding=function(){var t=this.gridOptions.autoSizePadding;return null!=t&&t>=0?t:20},t.prototype.getHeaderHeight=function(){return"number"==typeof this.gridOptions.headerHeight?this.gridOptions.headerHeight:this.getFromTheme(25,"headerHeight")},t.prototype.getFloatingFiltersHeight=function(){return"number"==typeof this.gridOptions.floatingFiltersHeight?this.gridOptions.floatingFiltersHeight:this.getFromTheme(25,"headerHeight")},t.prototype.getGroupHeaderHeight=function(){return"number"==typeof this.gridOptions.groupHeaderHeight?this.gridOptions.groupHeaderHeight:this.getHeaderHeight()},t.prototype.getPivotHeaderHeight=function(){return"number"==typeof this.gridOptions.pivotHeaderHeight?this.gridOptions.pivotHeaderHeight:this.getHeaderHeight()},t.prototype.getPivotGroupHeaderHeight=function(){return"number"==typeof this.gridOptions.pivotGroupHeaderHeight?this.gridOptions.pivotGroupHeaderHeight:this.getGroupHeaderHeight()},t.prototype.isExternalFilterPresent=function(){return"function"==typeof this.gridOptions.isExternalFilterPresent&&this.gridOptions.isExternalFilterPresent()},t.prototype.doesExternalFilterPass=function(t){return"function"==typeof this.gridOptions.doesExternalFilterPass&&this.gridOptions.doesExternalFilterPass(t)},t.prototype.getTooltipShowDelay=function(){var t=this.gridOptions.tooltipShowDelay;return e(t)?(t<0&&console.warn("ag-grid: tooltipShowDelay should not be lower than 0"),Math.max(200,t)):null},t.prototype.isTooltipMouseTrack=function(){return kr(this.gridOptions.tooltipMouseTrack)},t.prototype.isSuppressModelUpdateAfterUpdateTransaction=function(){return kr(this.gridOptions.suppressModelUpdateAfterUpdateTransaction)},t.prototype.getDocument=function(){var t=null;return this.gridOptions.getDocument&&e(this.gridOptions.getDocument)&&(t=this.gridOptions.getDocument()),t&&e(t)?t:document},t.prototype.getMinColWidth=function(){var t=this.gridOptions.minColWidth;if(e(t)&&t>n.MIN_COL_WIDTH)return this.gridOptions.minColWidth;var o=this.getFromTheme(null,"headerCellMinWidth");return e(o)?Math.max(o,n.MIN_COL_WIDTH):n.MIN_COL_WIDTH},t.prototype.getMaxColWidth=function(){return this.gridOptions.maxColWidth&&this.gridOptions.maxColWidth>n.MIN_COL_WIDTH?this.gridOptions.maxColWidth:null},t.prototype.getColWidth=function(){return"number"!=typeof this.gridOptions.colWidth||this.gridOptions.colWidth<n.MIN_COL_WIDTH?200:this.gridOptions.colWidth},t.prototype.getRowBuffer=function(){var t=this.gridOptions.rowBuffer;return"number"==typeof t?t<0&&(z((function(){return console.warn("AG Grid: rowBuffer should not be negative")}),"warn rowBuffer negative"),this.gridOptions.rowBuffer=t=0):t=ht.ROW_BUFFER_SIZE,t},t.prototype.getRowBufferInPixels=function(){return this.getRowBuffer()*this.getRowHeightAsNumber()},t.prototype.getScrollbarWidth=function(){if(null==this.scrollbarWidth){var t="number"==typeof this.gridOptions.scrollbarWidth&&this.gridOptions.scrollbarWidth>=0?this.gridOptions.scrollbarWidth:Fe();null!=t&&(this.scrollbarWidth=t,this.eventService.dispatchEvent({type:Wt.EVENT_SCROLLBAR_WIDTH_CHANGED}))}return this.scrollbarWidth},t.prototype.checkForDeprecated=function(){var t=this.gridOptions;t.deprecatedEmbedFullWidthRows&&console.warn("AG Grid: since v21.2, deprecatedEmbedFullWidthRows has been replaced with embedFullWidthRows."),t.enableOldSetFilterModel&&console.warn("AG Grid: since v22.x, enableOldSetFilterModel is deprecated. Please move to the new Set Filter Model as the old one may not be supported in v23 onwards."),t.floatingFilter&&(console.warn("AG Grid: since v23.1, floatingFilter on the gridOptions is deprecated. Please use floatingFilter on the colDef instead."),t.defaultColDef||(t.defaultColDef={}),null==t.defaultColDef.floatingFilter&&(t.defaultColDef.floatingFilter=!0)),t.rowDeselection&&console.warn("AG Grid: since v24.x, rowDeselection is deprecated and the behaviour is true by default. Please use `suppressRowDeselection` to prevent rows from being deselected.");var e=function(e,o,n){null!=t[e]&&(console.warn("ag-grid: since version "+n+", '"+e+"' is deprecated / renamed, please use the new property name '"+o+"' instead."),null==t[o]&&(t[o]=t[e]))};if(e("batchUpdateWaitMillis","asyncTransactionWaitMillis","23.1.x"),e("deltaRowDataMode","immutableData","23.1.x"),(t.immutableColumns||t.deltaColumnMode)&&console.warn("AG Grid: since v24.0, immutableColumns and deltaColumnMode properties are gone. The grid now works like this as default. To keep column order maintained, set grid property applyColumnDefOrder=true"),e("suppressSetColumnStateEvents","suppressColumnStateEvents","24.0.x"),t.groupRowInnerRenderer||t.groupRowInnerRendererParams||t.groupRowInnerRendererFramework){console.warn("AG Grid: since v24.0, grid properties groupRowInnerRenderer, groupRowInnerRendererFramework and groupRowInnerRendererParams are no longer used."),console.warn(" Instead use the grid properties groupRowRendererParams.innerRenderer, groupRowRendererParams.innerRendererFramework and groupRowRendererParams.innerRendererParams."),console.warn(" For example instead of this:"),console.warn(' groupRowInnerRenderer: "myRenderer"'),console.warn(" groupRowInnerRendererParams: {x: a}"),console.warn(" Replace with this:"),console.warn(" groupRowRendererParams: {"),console.warn(' innerRenderer: "myRenderer",'),console.warn(" innerRendererParams: {x: a}"),console.warn(" }"),console.warn(" We have copied the properties over for you. However to stop this error message, please change your application code."),t.groupRowRendererParams||(t.groupRowRendererParams={});var o=t.groupRowRendererParams;t.groupRowInnerRenderer&&(o.innerRenderer=t.groupRowInnerRenderer),t.groupRowInnerRendererParams&&(o.innerRendererParams=t.groupRowInnerRendererParams),t.groupRowInnerRendererFramework&&(o.innerRendererFramework=t.groupRowInnerRendererFramework)}t.rememberGroupStateWhenNewData&&console.warn("AG Grid: since v24.0, grid property rememberGroupStateWhenNewData is deprecated. This feature was provided before Transaction Updates worked (which keep group state). Now that transaction updates are possible and they keep group state, this feature is no longer needed."),t.detailCellRendererParams&&t.detailCellRendererParams.autoHeight&&(console.warn("AG Grid: since v24.1, grid property detailCellRendererParams.autoHeight is replaced with grid property detailRowAutoHeight. This allows this feature to work when you provide a custom DetailCellRenderer"),t.detailRowAutoHeight=!0),t.suppressKeyboardEvent&&console.warn("AG Grid: since v24.1 suppressKeyboardEvent in the gridOptions has been deprecated and will be removed in\n future versions of AG Grid. If you need this to be set for every column use the defaultColDef property."),t.suppressEnterpriseResetOnNewColumns&&(console.warn("AG Grid: since v25, grid property suppressEnterpriseResetOnNewColumns is deprecated. This was a temporary property to allow changing columns in Server Side Row Model without triggering a reload. Now that it is possible to dynamically change columns in the grid, this is no longer needed."),t.detailRowAutoHeight=!0)},t.prototype.checkForViolations=function(){this.isTreeData()&&this.treeDataViolations()},t.prototype.treeDataViolations=function(){this.isRowModelDefault()&&o(this.getDataPathFunc())&&console.warn("AG Grid: property usingTreeData=true with rowModel=clientSide, but you did not provide getDataPath function, please provide getDataPath function if using tree data."),this.isRowModelServerSide()&&(o(this.getIsServerSideGroupFunc())&&console.warn("AG Grid: property usingTreeData=true with rowModel=serverSide, but you did not provide isServerSideGroup function, please provide isServerSideGroup function if using tree data."),o(this.getServerSideGroupKeyFunc())&&console.warn("AG Grid: property usingTreeData=true with rowModel=serverSide, but you did not provide getServerSideGroupKey function, please provide getServerSideGroupKey function if using tree data."))},t.prototype.getLocaleTextFunc=function(){if(this.gridOptions.localeTextFunc)return this.gridOptions.localeTextFunc;var t=this.gridOptions.localeText;return function(e,o){return t&&t[e]?t[e]:o}},t.prototype.globalEventHandler=function(t,e){if(!this.destroyed){var o=de.getCallbackForEvent(t);"function"==typeof this.gridOptions[o]&&this.gridOptions[o](e)}},t.prototype.getRowHeightAsNumber=function(){return!this.gridOptions.rowHeight||o(this.gridOptions.rowHeight)?this.getDefaultRowHeight():this.gridOptions.rowHeight&&this.isNumeric(this.gridOptions.rowHeight)?this.gridOptions.rowHeight:(console.warn("AG Grid row height must be a number if not using standard row model"),this.getDefaultRowHeight())},t.prototype.getRowHeightForNode=function(t,o){if(void 0===o&&(o=!1),"function"==typeof this.gridOptions.getRowHeight){if(o)return{height:this.getDefaultRowHeight(),estimated:!0};var n={node:t,data:t.data,api:this.gridOptions.api,context:this.gridOptions.context},i=this.gridOptions.getRowHeight(n);if(this.isNumeric(i))return 0===i&&z((function(){return console.warn("AG Grid: The return of `getRowHeight` cannot be zero. If the intention is to hide rows, use a filter instead.")}),"invalidRowHeight"),{height:Math.max(1,i),estimated:!1}}if(t.detail&&this.isMasterDetail())return this.isNumeric(this.gridOptions.detailRowHeight)?{height:this.gridOptions.detailRowHeight,estimated:!1}:{height:300,estimated:!1};var r=this.getDefaultRowHeight(),s=this.gridOptions.rowHeight&&this.isNumeric(this.gridOptions.rowHeight)?this.gridOptions.rowHeight:r,a=e(s)?Math.min(r,s):r;if(this.columnController.isAutoRowHeightActive()){if(o)return{height:s,estimated:!0};var l=this.autoHeightCalculator.getPreferredHeightForRow(t);return{height:Math.max(l,a),estimated:!1}}return{height:s,estimated:!1}},t.prototype.isDynamicRowHeight=function(){return"function"==typeof this.gridOptions.getRowHeight},t.prototype.getListItemHeight=function(){return this.getFromTheme(20,"listItemHeight")},t.prototype.chartMenuPanelWidth=function(){return this.environment.chartMenuPanelWidth()},t.prototype.isNumeric=function(t){return!isNaN(t)&&"number"==typeof t&&isFinite(t)},t.prototype.getFromTheme=function(t,e){var o=this.environment.getTheme().theme;return o&&0===o.indexOf("ag-theme")?this.environment.getSassVariable(o,e):t},t.prototype.getDefaultRowHeight=function(){return this.getFromTheme(25,"rowHeight")},t.MIN_COL_WIDTH=10,t.PROP_HEADER_HEIGHT="headerHeight",t.PROP_GROUP_REMOVE_SINGLE_CHILDREN="groupRemoveSingleChildren",t.PROP_GROUP_REMOVE_LOWEST_SINGLE_CHILDREN="groupRemoveLowestSingleChildren",t.PROP_PIVOT_HEADER_HEIGHT="pivotHeaderHeight",t.PROP_SUPPRESS_CLIPBOARD_PASTE="suppressClipboardPaste",t.PROP_GROUP_HEADER_HEIGHT="groupHeaderHeight",t.PROP_PIVOT_GROUP_HEADER_HEIGHT="pivotGroupHeaderHeight",t.PROP_FLOATING_FILTERS_HEIGHT="floatingFiltersHeight",t.PROP_SUPPRESS_ROW_CLICK_SELECTION="suppressRowClickSelection",t.PROP_SUPPRESS_ROW_DRAG="suppressRowDrag",t.PROP_SUPPRESS_MOVE_WHEN_ROW_DRAG="suppressMoveWhenRowDragging",t.PROP_POPUP_PARENT="popupParent",t.PROP_DOM_LAYOUT="domLayout",t.PROP_FILL_HANDLE_DIRECTION="fillHandleDirection",Vr([it("gridOptions")],t.prototype,"gridOptions",void 0),Vr([it("columnController")],t.prototype,"columnController",void 0),Vr([it("eventService")],t.prototype,"eventService",void 0),Vr([it("environment")],t.prototype,"environment",void 0),Vr([it("autoHeightCalculator")],t.prototype,"autoHeightCalculator",void 0),Vr([Hr(0,at("gridApi")),Hr(1,at("columnApi"))],t.prototype,"agWire",null),Vr([ot],t.prototype,"destroy",null),Vr([et],t.prototype,"init",null),t=n=Vr([nt("gridOptionsWrapper")],t)}(),Kr=function(){function t(t,e){this.active=!0,this.nodeIdsToColumns={},this.mapToItems={},this.keepingColumns=t,this.pathRoot={rowNode:e,children:null},this.mapToItems[e.id]=this.pathRoot}return t.prototype.setInactive=function(){this.active=!1},t.prototype.isActive=function(){return this.active},t.prototype.depthFirstSearchChangedPath=function(t,e){if(t.children)for(var o=0;o<t.children.length;o++)this.depthFirstSearchChangedPath(t.children[o],e);e(t.rowNode)},t.prototype.depthFirstSearchEverything=function(t,e,o){if(t.childrenAfterGroup)for(var n=0;n<t.childrenAfterGroup.length;n++){var i=t.childrenAfterGroup[n];i.childrenAfterGroup?this.depthFirstSearchEverything(t.childrenAfterGroup[n],e,o):o&&e(i)}e(t)},t.prototype.forEachChangedNodeDepthFirst=function(t,e){void 0===e&&(e=!1),this.active?this.depthFirstSearchChangedPath(this.pathRoot,t):this.depthFirstSearchEverything(this.pathRoot.rowNode,t,e)},t.prototype.executeFromRootNode=function(t){t(this.pathRoot.rowNode)},t.prototype.createPathItems=function(t){for(var e=t,o=0;!this.mapToItems[e.id];){var n={rowNode:e,children:null};this.mapToItems[e.id]=n,o++,e=e.parent}return o},t.prototype.populateColumnsMap=function(t,e){var o=this;if(this.keepingColumns&&e)for(var n=t;n;)this.nodeIdsToColumns[n.id]||(this.nodeIdsToColumns[n.id]={}),e.forEach((function(t){return o.nodeIdsToColumns[n.id][t.getId()]=!0})),n=n.parent},t.prototype.linkPathItems=function(t,e){for(var o=t,n=0;n<e;n++){var i=this.mapToItems[o.id],r=this.mapToItems[o.parent.id];r.children||(r.children=[]),r.children.push(i),o=o.parent}},t.prototype.addParentNode=function(t,e){if(t&&!t.isRowPinned()){var o=this.createPathItems(t);this.linkPathItems(t,o),this.populateColumnsMap(t,e)}},t.prototype.canSkip=function(t){return this.active&&!this.mapToItems[t.id]},t.prototype.getValueColumnsForNode=function(t,e){if(!this.keepingColumns)return e;var o=this.nodeIdsToColumns[t.id];return e.filter((function(t){return o[t.getId()]}))},t.prototype.getNotValueColumnsForNode=function(t,e){if(!this.keepingColumns)return null;var o=this.nodeIdsToColumns[t.id];return e.filter((function(t){return!o[t.getId()]}))},t}(),Yr=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),qr=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Xr=function(t,e){return function(o,n){e(o,n,t)}},Qr=(function(t){function o(){return null!==t&&t.apply(this,arguments)||this}Yr(o,t),o.prototype.setBeans=function(t){this.logger=t.create("SelectionController"),this.reset(),this.gridOptionsWrapper.isRowModelDefault()&&this.addManagedListener(this.eventService,Wt.EVENT_ROW_DATA_CHANGED,this.reset.bind(this))},o.prototype.init=function(){this.groupSelectsChildren=this.gridOptionsWrapper.isGroupSelectsChildren(),this.addManagedListener(this.eventService,Wt.EVENT_ROW_SELECTED,this.onRowSelected.bind(this))},o.prototype.setLastSelectedNode=function(t){this.lastSelectedNode=t},o.prototype.getLastSelectedNode=function(){return this.lastSelectedNode},o.prototype.getSelectedNodes=function(){var t=[];return A(this.selectedNodes,(function(e,o){o&&t.push(o)})),t},o.prototype.getSelectedRows=function(){var t=[];return A(this.selectedNodes,(function(e,o){o&&o.data&&t.push(o.data)})),t},o.prototype.removeGroupsFromSelection=function(){var t=this;A(this.selectedNodes,(function(e,o){o&&o.group&&(t.selectedNodes[o.id]=void 0)}))},o.prototype.updateGroupsFromChildrenSelections=function(t){if(this.gridOptionsWrapper.isGroupSelectsChildren()&&this.rowModel.getType()===ht.ROW_MODEL_TYPE_CLIENT_SIDE){var e=this.rowModel.getRootNode();t||(t=new Kr(!0,e)).setInactive(),t.forEachChangedNodeDepthFirst((function(t){t!==e&&t.calculateSelectedFromChildren()}))}},o.prototype.getNodeForIdIfSelected=function(t){return this.selectedNodes[t]},o.prototype.clearOtherNodes=function(t){var e=this,o={},n=0;return A(this.selectedNodes,(function(i,r){if(r&&r.id!==t.id){var s=e.selectedNodes[r.id];n+=s.setSelectedParams({newValue:!1,clearSelection:!1,suppressFinishActions:!0}),e.groupSelectsChildren&&r.parent&&(o[r.parent.id]=r.parent)}})),A(o,(function(t,e){e.calculateSelectedFromChildren()})),n},o.prototype.onRowSelected=function(t){var e=t.node;this.groupSelectsChildren&&e.group||(e.isSelected()?this.selectedNodes[e.id]=e:this.selectedNodes[e.id]=void 0)},o.prototype.syncInRowNode=function(t,e){this.syncInOldRowNode(t,e),this.syncInNewRowNode(t)},o.prototype.syncInOldRowNode=function(t,o){e(o)&&t.id!==o.id&&o&&(e(this.selectedNodes[o.id])&&(this.selectedNodes[o.id]=o))},o.prototype.syncInNewRowNode=function(t){e(this.selectedNodes[t.id])?(t.setSelectedInitialValue(!0),this.selectedNodes[t.id]=t):t.setSelectedInitialValue(!1)},o.prototype.reset=function(){this.logger.log("reset"),this.selectedNodes={},this.lastSelectedNode=null},o.prototype.getBestCostNodeSelection=function(){if(this.rowModel.getType()===ht.ROW_MODEL_TYPE_CLIENT_SIDE){var t=this.rowModel.getTopLevelNodes();if(null!==t){var e=[];return function t(o){for(var n=0,i=o.length;n<i;n++){var r=o[n];r.isSelected()?e.push(r):r.group&&r.children&&t(r.children)}}(t),e}console.warn("selectAll not available doing rowModel=virtual")}else console.warn("getBestCostNodeSelection is only available when using normal row model")},o.prototype.setRowModel=function(t){this.rowModel=t},o.prototype.isEmpty=function(){var t=0;return A(this.selectedNodes,(function(e,o){o&&t++})),0===t},o.prototype.deselectAllRowNodes=function(t){void 0===t&&(t=!1);var e=function(t){return t.selectThisNode(!1)},o=this.rowModel.getType()===ht.ROW_MODEL_TYPE_CLIENT_SIDE;if(t){if(!o)return void console.error("AG Grid: selecting just filtered only works with In Memory Row Model");this.rowModel.forEachNodeAfterFilter(e)}else A(this.selectedNodes,(function(t,o){o&&e(o)})),this.reset();o&&this.groupSelectsChildren&&this.updateGroupsFromChildrenSelections();var n={type:Wt.EVENT_SELECTION_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(n)},o.prototype.selectAllRowNodes=function(t){if(void 0===t&&(t=!1),this.rowModel.getType()!==ht.ROW_MODEL_TYPE_CLIENT_SIDE)throw new Error("selectAll only available with normal row model, ie not "+this.rowModel.getType());var e=this.rowModel,o=function(t){return t.selectThisNode(!0)};t?e.forEachNodeAfterFilter(o):e.forEachNode(o),this.rowModel.getType()===ht.ROW_MODEL_TYPE_CLIENT_SIDE&&this.groupSelectsChildren&&this.updateGroupsFromChildrenSelections();var n={type:Wt.EVENT_SELECTION_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(n)},o.prototype.selectNode=function(t,e){t&&t.setSelectedParams({newValue:!0,clearSelection:!e})},o.prototype.deselectIndex=function(t){var e=this.rowModel.getRow(t);this.deselectNode(e)},o.prototype.deselectNode=function(t){t&&t.setSelectedParams({newValue:!1,clearSelection:!1})},o.prototype.selectIndex=function(t,e){var o=this.rowModel.getRow(t);this.selectNode(o,e)},qr([it("rowModel")],o.prototype,"rowModel",void 0),qr([it("columnApi")],o.prototype,"columnApi",void 0),qr([it("gridApi")],o.prototype,"gridApi",void 0),qr([Xr(0,at("loggerFactory"))],o.prototype,"setBeans",null),qr([et],o.prototype,"init",null),o=qr([nt("selectionController")],o)}(Mt),function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s});
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/!function(){function t(){}t.prototype.sizeColumnsToFit=function(t){void 0===t&&console.error("AG Grid: missing parameter to columnApi.sizeColumnsToFit(gridWidth)"),this.columnController.sizeColumnsToFit(t,"api")},t.prototype.setColumnGroupOpened=function(t,e){this.columnController.setColumnGroupOpened(t,e,"api")},t.prototype.getColumnGroup=function(t,e){return this.columnController.getColumnGroup(t,e)},t.prototype.getOriginalColumnGroup=function(t){return this.columnController.getOriginalColumnGroup(t)},t.prototype.getDisplayNameForColumn=function(t,e){return this.columnController.getDisplayNameForColumn(t,e)||""},t.prototype.getDisplayNameForColumnGroup=function(t,e){return this.columnController.getDisplayNameForColumnGroup(t,e)||""},t.prototype.getColumn=function(t){return this.columnController.getPrimaryColumn(t)},t.prototype.applyColumnState=function(t){return this.columnController.applyColumnState(t,"api")},t.prototype.getColumnState=function(){return this.columnController.getColumnState()},t.prototype.resetColumnState=function(){this.columnController.resetColumnState("api")},t.prototype.getColumnGroupState=function(){return this.columnController.getColumnGroupState()},t.prototype.setColumnGroupState=function(t){this.columnController.setColumnGroupState(t,"api")},t.prototype.resetColumnGroupState=function(){this.columnController.resetColumnGroupState("api")},t.prototype.isPinning=function(){return this.columnController.isPinningLeft()||this.columnController.isPinningRight()},t.prototype.isPinningLeft=function(){return this.columnController.isPinningLeft()},t.prototype.isPinningRight=function(){return this.columnController.isPinningRight()},t.prototype.getDisplayedColAfter=function(t){return this.columnController.getDisplayedColAfter(t)},t.prototype.getDisplayedColBefore=function(t){return this.columnController.getDisplayedColBefore(t)},t.prototype.setColumnVisible=function(t,e){this.columnController.setColumnVisible(t,e,"api")},t.prototype.setColumnsVisible=function(t,e){this.columnController.setColumnsVisible(t,e,"api")},t.prototype.setColumnPinned=function(t,e){this.columnController.setColumnPinned(t,e,"api")},t.prototype.setColumnsPinned=function(t,e){this.columnController.setColumnsPinned(t,e,"api")},t.prototype.getAllColumns=function(){return this.columnController.getAllPrimaryColumns()},t.prototype.getAllGridColumns=function(){return this.columnController.getAllGridColumns()},t.prototype.getDisplayedLeftColumns=function(){return this.columnController.getDisplayedLeftColumns()},t.prototype.getDisplayedCenterColumns=function(){return this.columnController.getDisplayedCenterColumns()},t.prototype.getDisplayedRightColumns=function(){return this.columnController.getDisplayedRightColumns()},t.prototype.getAllDisplayedColumns=function(){return this.columnController.getAllDisplayedColumns()},t.prototype.getAllDisplayedVirtualColumns=function(){return this.columnController.getViewportColumns()},t.prototype.moveColumn=function(t,e){"number"==typeof t?(console.warn("AG Grid: you are using moveColumn(fromIndex, toIndex) - moveColumn takes a column key and a destination index, not two indexes, to move with indexes use moveColumnByIndex(from,to) instead"),this.columnController.moveColumnByIndex(t,e,"api")):this.columnController.moveColumn(t,e,"api")},t.prototype.moveColumnByIndex=function(t,e){this.columnController.moveColumnByIndex(t,e,"api")},t.prototype.moveColumns=function(t,e){this.columnController.moveColumns(t,e,"api")},t.prototype.moveRowGroupColumn=function(t,e){this.columnController.moveRowGroupColumn(t,e)},t.prototype.setColumnAggFunc=function(t,e){this.columnController.setColumnAggFunc(t,e)},t.prototype.setColumnWidth=function(t,e,o){void 0===o&&(o=!0),this.columnController.setColumnWidths([{key:t,newWidth:e}],!1,o)},t.prototype.setColumnWidths=function(t,e){void 0===e&&(e=!0),this.columnController.setColumnWidths(t,!1,e)},t.prototype.setPivotMode=function(t){this.columnController.setPivotMode(t)},t.prototype.isPivotMode=function(){return this.columnController.isPivotMode()},t.prototype.getSecondaryPivotColumn=function(t,e){return this.columnController.getSecondaryPivotColumn(t,e)},t.prototype.setValueColumns=function(t){this.columnController.setValueColumns(t,"api")},t.prototype.getValueColumns=function(){return this.columnController.getValueColumns()},t.prototype.removeValueColumn=function(t){this.columnController.removeValueColumn(t,"api")},t.prototype.removeValueColumns=function(t){this.columnController.removeValueColumns(t,"api")},t.prototype.addValueColumn=function(t){this.columnController.addValueColumn(t,"api")},t.prototype.addValueColumns=function(t){this.columnController.addValueColumns(t,"api")},t.prototype.setRowGroupColumns=function(t){this.columnController.setRowGroupColumns(t,"api")},t.prototype.removeRowGroupColumn=function(t){this.columnController.removeRowGroupColumn(t,"api")},t.prototype.removeRowGroupColumns=function(t){this.columnController.removeRowGroupColumns(t,"api")},t.prototype.addRowGroupColumn=function(t){this.columnController.addRowGroupColumn(t,"api")},t.prototype.addRowGroupColumns=function(t){this.columnController.addRowGroupColumns(t,"api")},t.prototype.getRowGroupColumns=function(){return this.columnController.getRowGroupColumns()},t.prototype.setPivotColumns=function(t){this.columnController.setPivotColumns(t,"api")},t.prototype.removePivotColumn=function(t){this.columnController.removePivotColumn(t,"api")},t.prototype.removePivotColumns=function(t){this.columnController.removePivotColumns(t,"api")},t.prototype.addPivotColumn=function(t){this.columnController.addPivotColumn(t,"api")},t.prototype.addPivotColumns=function(t){this.columnController.addPivotColumns(t,"api")},t.prototype.getPivotColumns=function(){return this.columnController.getPivotColumns()},t.prototype.getLeftDisplayedColumnGroups=function(){return this.columnController.getDisplayedTreeLeft()},t.prototype.getCenterDisplayedColumnGroups=function(){return this.columnController.getDisplayedTreeCentre()},t.prototype.getRightDisplayedColumnGroups=function(){return this.columnController.getDisplayedTreeRight()},t.prototype.getAllDisplayedColumnGroups=function(){return this.columnController.getAllDisplayedTrees()},t.prototype.autoSizeColumn=function(t,e){return this.columnController.autoSizeColumn(t,e,"api")},t.prototype.autoSizeColumns=function(t,e){return this.columnController.autoSizeColumns(t,e,"api")},t.prototype.autoSizeAllColumns=function(t){this.columnController.autoSizeAllColumns(t,"api")},t.prototype.setSecondaryColumns=function(t){this.columnController.setSecondaryColumns(t,"api")},t.prototype.getSecondaryColumns=function(){return this.columnController.getSecondaryColumns()},t.prototype.getPrimaryColumns=function(){return this.columnController.getAllPrimaryColumns()},t.prototype.cleanDownReferencesToAvoidMemoryLeakInCaseApplicationIsKeepingReferenceToDestroyedGrid=function(){setTimeout(bn.removeAllReferences.bind(window,this,"Column API"),100)},t.prototype.columnGroupOpened=function(t,e){console.error("AG Grid: columnGroupOpened no longer exists, use setColumnGroupOpened"),this.setColumnGroupOpened(t,e)},t.prototype.hideColumns=function(t,e){console.error("AG Grid: hideColumns is deprecated, use setColumnsVisible"),this.columnController.setColumnsVisible(t,!e,"api")},t.prototype.hideColumn=function(t,e){console.error("AG Grid: hideColumn is deprecated, use setColumnVisible"),this.columnController.setColumnVisible(t,!e,"api")},t.prototype.setState=function(t){return console.error("AG Grid: setState is deprecated, use setColumnState"),this.setColumnState(t)},t.prototype.getState=function(){return console.error("AG Grid: getState is deprecated, use getColumnState"),this.getColumnState()},t.prototype.resetState=function(){console.error("AG Grid: resetState is deprecated, use resetColumnState"),this.resetColumnState()},t.prototype.getAggregationColumns=function(){return console.error("AG Grid: getAggregationColumns is deprecated, use getValueColumns"),this.columnController.getValueColumns()},t.prototype.removeAggregationColumn=function(t){console.error("AG Grid: removeAggregationColumn is deprecated, use removeValueColumn"),this.columnController.removeValueColumn(t,"api")},t.prototype.removeAggregationColumns=function(t){console.error("AG Grid: removeAggregationColumns is deprecated, use removeValueColumns"),this.columnController.removeValueColumns(t,"api")},t.prototype.addAggregationColumn=function(t){console.error("AG Grid: addAggregationColumn is deprecated, use addValueColumn"),this.columnController.addValueColumn(t,"api")},t.prototype.addAggregationColumns=function(t){console.error("AG Grid: addAggregationColumns is deprecated, use addValueColumns"),this.columnController.addValueColumns(t,"api")},t.prototype.setColumnAggFunction=function(t,e){console.error("AG Grid: setColumnAggFunction is deprecated, use setColumnAggFunc"),this.columnController.setColumnAggFunc(t,e,"api")},t.prototype.getDisplayNameForCol=function(t){return console.error("AG Grid: getDisplayNameForCol is deprecated, use getDisplayNameForColumn"),this.getDisplayNameForColumn(t,null)},t.prototype.setColumnState=function(t){return this.columnController.applyColumnState({state:t,applyOrder:!0},"api")},Qr([it("columnController")],t.prototype,"columnController",void 0),Qr([ot],t.prototype,"cleanDownReferencesToAvoidMemoryLeakInCaseApplicationIsKeepingReferenceToDestroyedGrid",null),t=Qr([nt("columnApi")],t)}();!function(t){t[t.FILL=0]="FILL",t[t.RANGE=1]="RANGE"}(jr||(jr={})),function(t){t[t.VALUE=0]="VALUE",t[t.DIMENSION=1]="DIMENSION"}(Ur||(Ur={}));
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
var $r,Zr,Jr,ts=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),es=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s};!function(t){t[t.ToolPanel=0]="ToolPanel",t[t.HeaderCell=1]="HeaderCell",t[t.RowDrag=2]="RowDrag",t[t.ChartPanel=3]="ChartPanel"}($r||($r={})),function(t){t[t.Up=0]="Up",t[t.Down=1]="Down"}(Zr||(Zr={})),function(t){t[t.Left=0]="Left",t[t.Right=1]="Right"}(Jr||(Jr={}));var os,ns=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.dragSourceAndParamsList=[],e.dropTargets=[],e}var o;return ts(e,t),o=e,e.prototype.init=function(){this.ePinnedIcon=un("columnMovePin",this.gridOptionsWrapper,null),this.eHideIcon=un("columnMoveHide",this.gridOptionsWrapper,null),this.eMoveIcon=un("columnMoveMove",this.gridOptionsWrapper,null),this.eLeftIcon=un("columnMoveLeft",this.gridOptionsWrapper,null),this.eRightIcon=un("columnMoveRight",this.gridOptionsWrapper,null),this.eGroupIcon=un("columnMoveGroup",this.gridOptionsWrapper,null),this.eAggregateIcon=un("columnMoveValue",this.gridOptionsWrapper,null),this.ePivotIcon=un("columnMovePivot",this.gridOptionsWrapper,null),this.eDropNotAllowedIcon=un("dropNotAllowed",this.gridOptionsWrapper,null)},e.prototype.addDragSource=function(t,e){void 0===e&&(e=!1);var o={eElement:t.eElement,dragStartPixels:t.dragStartPixels,onDragStart:this.onDragStart.bind(this,t),onDragStop:this.onDragStop.bind(this),onDragging:this.onDragging.bind(this)};this.dragSourceAndParamsList.push({params:o,dragSource:t}),this.dragService.addDragSource(o,e)},e.prototype.removeDragSource=function(t){var e=a(this.dragSourceAndParamsList,(function(e){return e.dragSource===t}));e&&(this.dragService.removeDragSource(e.params),g(this.dragSourceAndParamsList,e))},e.prototype.clearDragSourceParamsList=function(){var t=this;this.dragSourceAndParamsList.forEach((function(e){return t.dragService.removeDragSource(e.params)})),this.dragSourceAndParamsList.length=0},e.prototype.nudge=function(){this.dragging&&this.onDragging(this.eventLastTime,!0)},e.prototype.onDragStart=function(t,e){this.dragging=!0,this.dragSource=t,this.eventLastTime=e,this.dragItem=this.dragSource.getDragItem(),this.lastDropTarget=this.dragSource.dragSourceDropTarget,this.dragSource.onDragStarted&&this.dragSource.onDragStarted(),this.createGhost()},e.prototype.onDragStop=function(t){if(this.eventLastTime=null,this.dragging=!1,this.dragSource.onDragStopped&&this.dragSource.onDragStopped(),this.lastDropTarget&&this.lastDropTarget.onDragStop){var e=this.createDropTargetEvent(this.lastDropTarget,t,null,null,!1);this.lastDropTarget.onDragStop(e)}this.lastDropTarget=null,this.dragItem=null,this.removeGhost()},e.prototype.onDragging=function(t,e){var o=this,n=this.getHorizontalDirection(t),i=this.getVerticalDirection(t);this.eventLastTime=t,this.positionGhost(t);var r=this.dropTargets.filter((function(e){return o.isMouseOnDropTarget(t,e)})),s=r.length,a=null;if(s>0&&(a=1===s?r[0]:r.reduce((function(t,e){if(!t)return e;var o=t.getContainer(),n=e.getContainer();return o.contains(n)?e:t}))),a!==this.lastDropTarget)this.leaveLastTargetIfExists(t,n,i,e),this.enterDragTargetIfExists(a,t,n,i,e),this.lastDropTarget=a;else if(a&&a.onDragging){var l=this.createDropTargetEvent(a,t,n,i,e);a.onDragging(l)}},e.prototype.enterDragTargetIfExists=function(t,e,o,n,i){if(t){if(t.onDragEnter){var r=this.createDropTargetEvent(t,e,o,n,i);t.onDragEnter(r)}this.setGhostIcon(t.getIconName?t.getIconName():null)}},e.prototype.leaveLastTargetIfExists=function(t,e,o,n){if(this.lastDropTarget){if(this.lastDropTarget.onDragLeave){var i=this.createDropTargetEvent(this.lastDropTarget,t,e,o,n);this.lastDropTarget.onDragLeave(i)}this.setGhostIcon(null)}},e.prototype.getAllContainersFromDropTarget=function(t){var e=[t.getContainer()],o=t.getSecondaryContainers?t.getSecondaryContainers():null;return o&&(e=e.concat(o)),e},e.prototype.isMouseOnDropTarget=function(t,e){var o=!1;return this.getAllContainersFromDropTarget(e).filter((function(t){return t})).forEach((function(e){var n=e.getBoundingClientRect();if(0!==n.width&&0!==n.height){var i=t.clientX>=n.left&&t.clientX<n.right,r=t.clientY>=n.top&&t.clientY<n.bottom;i&&r&&(o=!0)}})),o&&e.isInterestedIn(this.dragSource.type)},e.prototype.addDropTarget=function(t){this.dropTargets.push(t)},e.prototype.removeDropTarget=function(t){this.dropTargets=this.dropTargets.filter((function(e){return e.getContainer()!==t.getContainer()}))},e.prototype.hasExternalDropZones=function(){return this.dropTargets.some((function(t){return t.external}))},e.prototype.findExternalZone=function(t){return a(this.dropTargets.filter((function(t){return t.external})),(function(e){return e.getContainer()===t.getContainer()}))},e.prototype.getHorizontalDirection=function(t){var e=this.eventLastTime&&this.eventLastTime.clientX,o=t.clientX;return e===o?null:e>o?Jr.Left:Jr.Right},e.prototype.getVerticalDirection=function(t){var e=this.eventLastTime&&this.eventLastTime.clientY,o=t.clientY;return e===o?null:e>o?Zr.Up:Zr.Down},e.prototype.createDropTargetEvent=function(t,e,o,n,i){var r=t.getContainer(),s=r.getBoundingClientRect(),a=this.gridApi,l=this.columnApi,p=this.dragItem,u=this.dragSource;return{event:e,x:e.clientX-s.left,y:e.clientY-s.top,vDirection:n,hDirection:o,dragSource:u,fromNudge:i,dragItem:p,api:a,columnApi:l,dropZoneTarget:r}},e.prototype.positionGhost=function(t){var e=this.eGhost;if(e){var o=e.getBoundingClientRect().height,n=Ne()-2,i=Le()-2,r=t.pageY-o/2,s=t.pageX-10,a=this.gridOptionsWrapper.getDocument(),l=window.pageYOffset||a.documentElement.scrollTop,p=window.pageXOffset||a.documentElement.scrollLeft;n>0&&s+e.clientWidth>n+p&&(s=n+p-e.clientWidth),s<0&&(s=0),i>0&&r+e.clientHeight>i+l&&(r=i+l-e.clientHeight),r<0&&(r=0),e.style.left=s+"px",e.style.top=r+"px"}},e.prototype.removeGhost=function(){this.eGhost&&this.eGhostParent&&this.eGhostParent.removeChild(this.eGhost),this.eGhost=null},e.prototype.createGhost=function(){this.eGhost=oo(o.GHOST_TEMPLATE);var t=this.environment.getTheme().theme;t&&Me(this.eGhost,t),this.eGhostIcon=this.eGhost.querySelector(".ag-dnd-ghost-icon"),this.setGhostIcon(null);var e=this.eGhost.querySelector(".ag-dnd-ghost-label"),n=this.dragSource.dragItemName;Y(n)&&(n=n()),e.innerHTML=Kt(n)||"",this.eGhost.style.height="25px",this.eGhost.style.top="20px",this.eGhost.style.left="20px";var i=this.gridOptionsWrapper.getDocument(),r=i.fullscreenElement||i.querySelector("body");this.eGhostParent=r,this.eGhostParent?this.eGhostParent.appendChild(this.eGhost):console.warn("AG Grid: could not find document body, it is needed for dragging columns")},e.prototype.setGhostIcon=function(t,e){void 0===e&&(e=!1),Je(this.eGhostIcon);var n=null;switch(t||(t=this.dragSource.defaultIconName||o.ICON_NOT_ALLOWED),t){case o.ICON_PINNED:n=this.ePinnedIcon;break;case o.ICON_MOVE:n=this.eMoveIcon;break;case o.ICON_LEFT:n=this.eLeftIcon;break;case o.ICON_RIGHT:n=this.eRightIcon;break;case o.ICON_GROUP:n=this.eGroupIcon;break;case o.ICON_AGGREGATE:n=this.eAggregateIcon;break;case o.ICON_PIVOT:n=this.ePivotIcon;break;case o.ICON_NOT_ALLOWED:n=this.eDropNotAllowedIcon;break;case o.ICON_HIDE:n=this.eHideIcon}Ve(this.eGhostIcon,"ag-shake-left-to-right",e),n===this.eHideIcon&&this.gridOptionsWrapper.isSuppressDragLeaveHidesColumns()||n&&this.eGhostIcon.appendChild(n)},e.ICON_PINNED="pinned",e.ICON_MOVE="move",e.ICON_LEFT="left",e.ICON_RIGHT="right",e.ICON_GROUP="group",e.ICON_AGGREGATE="aggregate",e.ICON_PIVOT="pivot",e.ICON_NOT_ALLOWED="notAllowed",e.ICON_HIDE="hide",e.GHOST_TEMPLATE='<div class="ag-dnd-ghost ag-unselectable">\n <span class="ag-dnd-ghost-icon ag-shake-left-to-right"></span>\n <div class="ag-dnd-ghost-label"></div>\n </div>',es([it("dragService")],e.prototype,"dragService",void 0),es([it("environment")],e.prototype,"environment",void 0),es([it("columnApi")],e.prototype,"columnApi",void 0),es([it("gridApi")],e.prototype,"gridApi",void 0),es([et],e.prototype,"init",null),es([ot],e.prototype,"clearDragSourceParamsList",null),e=o=es([nt("dragAndDropService")],e)}(Mt),is=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),rs=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},ss=function(t){function e(e,o,n,i,r){var s=t.call(this)||this;return s.rowNode=e,s.column=o,s.cellValueFn=n,s.beans=i,s.customGui=r,s.isCustomGui=!1,s.dragSource=null,s}return is(e,t),e.prototype.postConstruct=function(){this.customGui?(this.isCustomGui=!0,this.setDragElement(this.customGui)):(this.setTemplate('<div class="ag-drag-handle ag-row-drag" aria-hidden="true"></div>'),this.getGui().appendChild(cn("rowDrag",this.beans.gridOptionsWrapper,null)),this.addDragSource());this.checkCompatibility();var t=this.beans.gridOptionsWrapper.isRowDragManaged()?new ps(this,this.beans,this.rowNode,this.column):new ls(this,this.beans,this.rowNode,this.column);this.createManagedBean(t,this.beans.context)},e.prototype.setDragElement=function(t){this.setTemplateFromElement(t),this.addDragSource()},e.prototype.getSelectedCount=function(){if(!this.beans.gridOptionsWrapper.isEnableMultiRowDragging())return 1;var t=this.beans.selectionController.getSelectedNodes();return-1!==t.indexOf(this.rowNode)?t.length:1},e.prototype.checkCompatibility=function(){var t=this.beans.gridOptionsWrapper.isRowDragManaged();this.beans.gridOptionsWrapper.isTreeData()&&t&&z((function(){return console.warn("AG Grid: If using row drag with tree data, you cannot have rowDragManaged=true")}),"RowDragComp.managedAndTreeData")},e.prototype.addDragSource=function(){var t=this;this.dragSource&&this.removeDragSource();var e={rowNode:this.rowNode,columns:[this.column],defaultTextValue:this.cellValueFn()},o=this.column.getColDef().rowDragText;this.dragSource={type:$r.RowDrag,eElement:this.getGui(),dragItemName:function(){var n=t.getSelectedCount();return o?o(e,n):1===n?t.cellValueFn():n+" rows"},getDragItem:function(){return e},dragStartPixels:0,dragSourceDomDataKey:this.beans.gridOptionsWrapper.getDomDataKey()},this.beans.dragAndDropService.addDragSource(this.dragSource,!0)},e.prototype.removeDragSource=function(){this.dragSource&&this.beans.dragAndDropService.removeDragSource(this.dragSource),this.dragSource=null},rs([et],e.prototype,"postConstruct",null),rs([ot],e.prototype,"removeDragSource",null),e}(xn),as=function(t){function e(e,o,n){var i=t.call(this)||this;return i.parent=e,i.column=n,i.rowNode=o,i}return is(e,t),e.prototype.setDisplayedOrVisible=function(t){if(t)this.parent.setDisplayed(!1);else{var e=this.column.isRowDrag(this.rowNode)||this.parent.isCustomGui;Y(this.column.getColDef().rowDrag)?(this.parent.setDisplayed(!0),this.parent.setVisible(e)):this.parent.setDisplayed(e)}},e}(Mt),ls=function(t){function e(e,o,n,i){var r=t.call(this,e,n,i)||this;return r.beans=o,r}return is(e,t),e.prototype.postConstruct=function(){this.addManagedListener(this.beans.gridOptionsWrapper,"suppressRowDrag",this.onSuppressRowDrag.bind(this)),this.addManagedListener(this.rowNode,Ci.EVENT_DATA_CHANGED,this.workOutVisibility.bind(this)),this.addManagedListener(this.rowNode,Ci.EVENT_CELL_CHANGED,this.workOutVisibility.bind(this)),this.workOutVisibility()},e.prototype.onSuppressRowDrag=function(){this.workOutVisibility()},e.prototype.workOutVisibility=function(){var t=this.beans.gridOptionsWrapper.isSuppressRowDrag();this.setDisplayedOrVisible(t)},rs([et],e.prototype,"postConstruct",null),e}(as),ps=function(t){function e(e,o,n,i){var r=t.call(this,e,n,i)||this;return r.beans=o,r}return is(e,t),e.prototype.postConstruct=function(){this.addManagedListener(this.beans.eventService,Wt.EVENT_SORT_CHANGED,this.workOutVisibility.bind(this)),this.addManagedListener(this.beans.eventService,Wt.EVENT_FILTER_CHANGED,this.workOutVisibility.bind(this)),this.addManagedListener(this.beans.eventService,Wt.EVENT_COLUMN_ROW_GROUP_CHANGED,this.workOutVisibility.bind(this)),this.addManagedListener(this.rowNode,Ci.EVENT_DATA_CHANGED,this.workOutVisibility.bind(this)),this.addManagedListener(this.rowNode,Ci.EVENT_CELL_CHANGED,this.workOutVisibility.bind(this)),this.addManagedListener(this.beans.gridOptionsWrapper,"suppressRowDrag",this.onSuppressRowDrag.bind(this)),this.workOutVisibility()},e.prototype.onSuppressRowDrag=function(){this.workOutVisibility()},e.prototype.workOutVisibility=function(){var t=this.beans.gridPanel.getRowDragFeature(),e=t&&t.shouldPreventRowMove(),o=this.beans.gridOptionsWrapper.isSuppressRowDrag(),n=this.beans.dragAndDropService.hasExternalDropZones(),i=e&&!n||o;this.setDisplayedOrVisible(i)},rs([et],e.prototype,"postConstruct",null),e}(as),us=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),cs=function(t){function e(e){var o=t.call(this,'<div class="ag-popup-editor" tabindex="-1"/>')||this;return o.getGuiCalledOnChild=!1,o.cellEditor=e,o}return us(e,t),e.prototype.onKeyDown=function(t){gn(this.gridOptionsWrapper,t,this.params.node,this.params.column,!0)||this.params.onKeyDown(t)},e.prototype.getGui=function(){return this.getGuiCalledOnChild||(this.appendChild(this.cellEditor.getGui()),this.getGuiCalledOnChild=!0),t.prototype.getGui.call(this)},e.prototype.init=function(o){var n=this;this.params=o,this.gridOptionsWrapper.setDomData(this.getGui(),e.DOM_KEY_POPUP_EDITOR_WRAPPER,!0),this.addDestroyFunc((function(){return n.destroyBean(n.cellEditor)})),this.addManagedListener(t.prototype.getGui.call(this),"keydown",this.onKeyDown.bind(this))},e.prototype.afterGuiAttached=function(){this.cellEditor.afterGuiAttached&&this.cellEditor.afterGuiAttached()},e.prototype.getValue=function(){return this.cellEditor.getValue()},e.prototype.isCancelBeforeStart=function(){return!!this.cellEditor.isCancelBeforeStart&&this.cellEditor.isCancelBeforeStart()},e.prototype.isCancelAfterEnd=function(){return!!this.cellEditor.isCancelAfterEnd&&this.cellEditor.isCancelAfterEnd()},e.prototype.getPopupPosition=function(){if(this.cellEditor.getPopupPosition)return this.cellEditor.getPopupPosition()},e.prototype.focusIn=function(){this.cellEditor.focusIn&&this.cellEditor.focusIn()},e.prototype.focusOut=function(){this.cellEditor.focusOut&&this.cellEditor.focusOut()},e.DOM_KEY_POPUP_EDITOR_WRAPPER="popupEditorWrapper",e}(Hn),ds=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),hs=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},fs=function(t){function e(e,o,n,i,r){var s=t.call(this,'<div class="ag-drag-handle ag-row-drag" draggable="true"></div>')||this;return s.rowNode=e,s.column=o,s.cellValue=n,s.beans=i,s.eCell=r,s}return ds(e,t),e.prototype.postConstruct=function(){this.getGui().appendChild(cn("rowDrag",this.beans.gridOptionsWrapper,null)),this.addGuiEventListener("mousedown",(function(t){t.stopPropagation()})),this.addDragSource(),this.checkVisibility()},e.prototype.addDragSource=function(){this.addGuiEventListener("dragstart",this.onDragStart.bind(this))},e.prototype.onDragStart=function(t){var e=this,o=this.column.getColDef().dndSourceOnRowDrag,n=Oe();n||t.dataTransfer.setDragImage(this.eCell,0,0);o?o({rowNode:this.rowNode,dragEvent:t}):function(){try{var o=JSON.stringify(e.rowNode.data);n?t.dataTransfer.setData("text",o):(t.dataTransfer.setData("application/json",o),t.dataTransfer.setData("text/plain",o))}catch(t){}}()},e.prototype.checkVisibility=function(){var t=this.column.isDndSource(this.rowNode);this.setDisplayed(t)},hs([et],e.prototype,"postConstruct",null),e}(xn),gs=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),ys=function(){return(ys=Object.assign||function(t){for(var e,o=1,n=arguments.length;o<n;o++)for(var i in e=arguments[o])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)},vs=function(t){function n(e,o,n,i,r,s,a){var l=t.call(this)||this;if(l.hasChartRange=!1,l.editingCell=!1,l.suppressRefreshCell=!1,l.tooltipFeatureEnabled=!1,l.scope=null,l.cellEditorVersion=0,l.cellRendererVersion=0,l.scope=e,l.beans=o,l.column=n,l.rowNode=i,l.rowComp=r,l.autoHeightCell=s,l.printLayout=a,l.createGridCellVo(),l.rangeSelectionEnabled=l.beans.rangeController&&o.gridOptionsWrapper.isEnableRangeSelection(),l.cellFocused=l.beans.focusController.isCellFocused(l.cellPosition),l.firstRightPinned=l.column.isFirstRightPinned(),l.lastLeftPinned=l.column.isLastLeftPinned(),l.rangeSelectionEnabled&&l.beans.rangeController){var p=l.beans.rangeController;l.rangeCount=p.getCellRangeCount(l.cellPosition),l.hasChartRange=l.getHasChartRange()}return l.getValueAndFormat(),l.setUsingWrapper(),l.chooseCellRenderer(),l.setupColSpan(),l.rowSpan=l.column.getRowSpan(l.rowNode),l}return gs(n,t),n.prototype.getCreateTemplate=function(){var t=this.beans.gridOptionsWrapper.isEnableCellTextSelection()?"":' unselectable="on"',o=[],n=this.column,i=this.getCellWidth(),r=this.modifyLeftForPrintLayout(this.getCellLeft()),s=this.getInitialValueToRender(),a=x(this.column,"colDef.template",null)?s:Kt(s);this.tooltip=this.getToolTip();var l=Kt(this.tooltip),p=Kt(n.getId()),u=this.preProcessStylesFromColDef(),c=this.getInitialCssClasses(),d=this.getStylesForRowSpanning(),h=Kt(this.beans.columnController.getAriaColumnIndex(this.column).toString());return o.push("<div"),o.push(' tabindex="-1"'),o.push(""+t),o.push(' role="gridcell"'),o.push(' aria-colindex="'+h+'"'),o.push(' comp-id="'+this.getCompId()+'" '),o.push(' col-id="'+p+'"'),o.push(' class="'+Kt(c.join(" "))+'"'),this.beans.gridOptionsWrapper.isEnableBrowserTooltips()&&e(l)&&o.push(' title="'+l+'"'),this.rangeSelectionEnabled&&o.push(' aria-selected="'+(this.rangeCount?"true":"false")+'"'),o.push(' style="width: '+Number(i)+"px; left: "+Number(r)+"px; "+Kt(u)+" "+Kt(d)+'">'),this.usingWrapper?o.push(this.getCellWrapperString(a)):null!=a&&o.push(a),o.push("</div>"),o.join("")},n.prototype.getCellWrapperString=function(t){return void 0===t&&(t=""),'<div ref="eCellWrapper" class="ag-cell-wrapper" role="presentation">\n <span ref="eCellValue" role="presentation" class="ag-cell-value"'+(this.beans.gridOptionsWrapper.isEnableCellTextSelection()?"":' unselectable="on"')+">\n "+(null!=t?t:"")+"\n </span>\n </div>"},n.prototype.getStylesForRowSpanning=function(){return 1===this.rowSpan?"":"height: "+this.beans.gridOptionsWrapper.getRowHeightAsNumber()*this.rowSpan+"px; z-index: 1;"},n.prototype.afterAttached=function(){var t='[comp-id="'+this.getCompId()+'"]',o=this.eParentRow.querySelector(t);this.setGui(o),this.addDomData(),this.populateTemplate(),this.createCellRendererInstance(!0),this.angular1Compile(),this.refreshHandle(),e(this.tooltip)&&this.createTooltipFeatureIfNeeded()},n.prototype.createTooltipFeatureIfNeeded=function(){this.beans.gridOptionsWrapper.isEnableBrowserTooltips()||this.tooltipFeatureEnabled||(this.createManagedBean(new Ln(this),this.beans.context),this.tooltipFeatureEnabled=!0)},n.prototype.onColumnHover=function(){var t=this.beans.columnHoverService.isHovered(this.column);this.addOrRemoveCssClass("ag-column-hover",t)},n.prototype.onCellChanged=function(t){t.column===this.column&&this.refreshCell({})},n.prototype.getCellLeft=function(){return(this.beans.gridOptionsWrapper.isEnableRtl()&&this.colsSpanning?d(this.colsSpanning):this.column).getLeft()},n.prototype.getCellWidth=function(){return this.colsSpanning?this.colsSpanning.reduce((function(t,e){return t+e.getActualWidth()}),0):this.column.getActualWidth()},n.prototype.onFlashCells=function(t){var e=this.beans.cellPositionUtils.createId(this.cellPosition);t.cells[e]&&this.animateCell("highlight")},n.prototype.setupColSpan=function(){o(this.getComponentHolder().colSpan)||(this.addManagedListener(this.beans.eventService,Wt.EVENT_DISPLAYED_COLUMNS_CHANGED,this.onDisplayColumnsChanged.bind(this)),this.addManagedListener(this.beans.eventService,Wt.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED,this.onWidthChanged.bind(this)),this.colsSpanning=this.getColSpanningList())},n.prototype.getColSpanningList=function(){var t=this.column.getColSpan(this.rowNode),e=[];if(1===t)e.push(this.column);else for(var n=this.column,i=this.column.getPinned(),r=0;n&&r<t&&(e.push(n),(n=this.beans.columnController.getDisplayedColAfter(n))&&!o(n))&&i===n.getPinned();r++);return e},n.prototype.onDisplayColumnsChanged=function(){var t=this.getColSpanningList();h(this.colsSpanning,t)||(this.colsSpanning=t,this.onWidthChanged(),this.onLeftChanged())},n.prototype.refreshAriaIndex=function(){var t=this.beans.columnController.getAriaColumnIndex(this.column);Ko(this.getGui(),t)},n.prototype.getInitialCssClasses=function(){var t=["ag-cell","ag-cell-not-inline-editing"];return this.autoHeightCell||t.push("ag-cell-auto-height"),!this.beans.gridOptionsWrapper.isSuppressCellSelection()&&this.cellFocused&&t.push("ag-cell-focus"),this.firstRightPinned&&t.push("ag-cell-first-right-pinned"),this.lastLeftPinned&&t.push("ag-cell-last-left-pinned"),this.beans.columnHoverService.isHovered(this.column)&&t.push("ag-column-hover"),w(t,this.preProcessClassesFromColDef()),w(t,this.preProcessCellClassRules()),w(t,this.getInitialRangeClasses()),this.usingWrapper||t.push("ag-cell-value"),this.wrapText=1==this.column.getColDef().wrapText,this.wrapText&&t.push("ag-cell-wrap-text"),t},n.prototype.getInitialValueToRender=function(){if(this.usingCellRenderer)return"string"==typeof this.cellRendererGui?this.cellRendererGui:"";var t=this.getComponentHolder();return t.template?t.template:t.templateUrl?this.beans.templateService.getTemplate(t.templateUrl,this.refreshCell.bind(this,!0))||"":this.getValueToUse()},n.prototype.getRenderedRow=function(){return this.rowComp},n.prototype.isSuppressNavigable=function(){return this.column.isSuppressNavigable(this.rowNode)},n.prototype.getCellRenderer=function(){return this.cellRenderer},n.prototype.getCellEditor=function(){return this.cellEditor},n.prototype.onNewColumnsLoaded=function(){this.postProcessWrapText(),this.postProcessCellClassRules()},n.prototype.postProcessWrapText=function(){var t=1==this.column.getColDef().wrapText;t!==this.wrapText&&(this.wrapText=t,this.addOrRemoveCssClass("ag-cell-wrap-text",this.wrapText))},n.prototype.refreshCell=function(t){if(!this.suppressRefreshCell&&!this.editingCell){var e=this.getComponentHolder(),o=t&&t.newData,n=t&&t.suppressFlash||e.suppressCellFlash,i=t&&t.forceRefresh,r=this.value;this.value=this.getValue();var s=!this.valuesAreEqual(r,this.value);if(i||s){this.valueFormatted=this.beans.valueFormatterService.formatValue(this.column,this.rowNode,this.scope,this.value),!o&&this.attemptCellRendererRefresh()||this.replaceContentsAfterRefresh();var a=this.beans.filterManager.isSuppressFlashingCellsBecauseFiltering();!n&&!a&&(this.beans.gridOptionsWrapper.isEnableCellChangeFlash()||e.enableCellChangeFlash)&&this.flashCell(),this.postProcessStylesFromColDef(),this.postProcessClassesFromColDef()}this.updateAngular1ScopeAndCompile(),this.refreshToolTip(),this.postProcessCellClassRules()}},n.prototype.flashCell=function(t){var e=t&&t.flashDelay,o=t&&t.fadeDelay;this.animateCell("data-changed",e,o)},n.prototype.animateCell=function(t,o,n){var i=this,r="ag-cell-"+t,s="ag-cell-"+t+"-animation",a=this.getGui(),l=this.beans.gridOptionsWrapper;o||(o=l.getCellFlashDelay()),e(n)||(n=l.getCellFadeDelay()),this.addCssClass(r),this.removeCssClass(s),window.setTimeout((function(){i.removeCssClass(r),i.addCssClass(s),a.style.transition="background-color "+n+"ms",window.setTimeout((function(){i.removeCssClass(s),a.style.removeProperty("transition")}),n)}),o)},n.prototype.replaceContentsAfterRefresh=function(){this.setUsingWrapper(),Je(this.eCellValue),this.cellRenderer=this.beans.context.destroyBean(this.cellRenderer),this.cellRendererGui=null,this.putDataIntoCellAfterRefresh(),this.updateAngular1ScopeAndCompile()},n.prototype.updateAngular1ScopeAndCompile=function(){this.beans.gridOptionsWrapper.isAngularCompileRows()&&this.scope&&(this.scope.data=ys({},this.rowNode.data),this.angular1Compile())},n.prototype.angular1Compile=function(){if(this.beans.gridOptionsWrapper.isAngularCompileRows()){var t=this.getGui();if(!t.classList.contains("ng-scope")||0===t.childElementCount){var e=this.beans.$compile(t)(this.scope);this.addDestroyFunc((function(){return e.remove()}))}}},n.prototype.postProcessStylesFromColDef=function(){var t=this.processStylesFromColDef();t&&po(this.getGui(),t)},n.prototype.preProcessStylesFromColDef=function(){return So(this.processStylesFromColDef())},n.prototype.processStylesFromColDef=function(){var t=this.getComponentHolder();if(t.cellStyle){var e=void 0;if("function"==typeof t.cellStyle){var o={column:this.column,value:this.value,colDef:t,data:this.rowNode.data,node:this.rowNode,rowIndex:this.rowNode.rowIndex,$scope:this.scope,api:this.beans.gridOptionsWrapper.getApi(),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),context:this.beans.gridOptionsWrapper.getContext()};e=(0,t.cellStyle)(o)}else e=t.cellStyle;return e}},n.prototype.postProcessClassesFromColDef=function(){var t=this;this.processClassesFromColDef((function(e){return t.addCssClass(e)}))},n.prototype.preProcessClassesFromColDef=function(){var t=[];return this.processClassesFromColDef((function(e){return t.push(e)})),t},n.prototype.processClassesFromColDef=function(t){var e=this.getComponentHolder(),o={value:this.value,data:this.rowNode.data,node:this.rowNode,colDef:e,rowIndex:this.rowNode.rowIndex,$scope:this.scope,api:this.beans.gridOptionsWrapper.getApi(),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),context:this.beans.gridOptionsWrapper.getContext()};this.beans.stylingService.processStaticCellClasses(e,o,t)},n.prototype.putDataIntoCellAfterRefresh=function(){var t=this.getComponentHolder();if(t.template)this.eCellValue.innerHTML=t.template;else if(t.templateUrl){var e=this.beans.templateService.getTemplate(t.templateUrl,this.refreshCell.bind(this,!0));e&&(this.eCellValue.innerHTML=e)}else if(this.chooseCellRenderer(),this.usingCellRenderer)this.createCellRendererInstance();else{var o=this.getValueToUse();null!=o&&(this.eCellValue.innerHTML=Kt(o)||"")}},n.prototype.attemptCellRendererRefresh=function(){if(o(this.cellRenderer)||!this.cellRenderer||o(this.cellRenderer.refresh))return!1;var t=this.createCellRendererParams(),e=this.beans.userComponentFactory.createFinalParams(this.getComponentHolder(),this.cellRendererType,t),n=this.cellRenderer.refresh(e);return!0===n||void 0===n},n.prototype.refreshToolTip=function(){var t=this.getToolTip();if(this.tooltip!==t){this.createTooltipFeatureIfNeeded();var o=e(t);o&&this.tooltip===t.toString()||(this.tooltip=t,this.beans.gridOptionsWrapper.isEnableBrowserTooltips()&&(o?this.eCellValue.setAttribute("title",this.tooltip):this.eCellValue.removeAttribute("title")))}},n.prototype.valuesAreEqual=function(t,e){var o=this.getComponentHolder(),n=o?o.equals:null;return n?n(t,e):t===e},n.prototype.getToolTip=function(){var t=this.getComponentHolder(),o=this.rowNode.data;if(t.tooltipField&&e(o))return V(o,t.tooltipField,this.column.isTooltipFieldContainsDots());var n=t.tooltipValueGetter;return n?n(ys(ys({api:this.beans.gridOptionsWrapper.getApi(),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),context:this.beans.gridOptionsWrapper.getContext()},this.getTooltipParams()),{value:this.value})):null},n.prototype.getTooltipParams=function(){return{location:"cell",colDef:this.getComponentHolder(),column:this.getColumn(),rowIndex:this.cellPosition.rowIndex,node:this.rowNode,data:this.rowNode.data,value:this.getTooltipText(),valueFormatted:this.valueFormatted}},n.prototype.getTooltipText=function(t){return void 0===t&&(t=!0),t?Kt(this.tooltip):this.tooltip},n.prototype.processCellClassRules=function(t,e){var o=this.getComponentHolder(),n={value:this.value,data:this.rowNode.data,node:this.rowNode,colDef:o,rowIndex:this.cellPosition.rowIndex,api:this.beans.gridOptionsWrapper.getApi(),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),$scope:this.scope,context:this.beans.gridOptionsWrapper.getContext()};this.beans.stylingService.processClassRules(o.cellClassRules,n,t,e)},n.prototype.postProcessCellClassRules=function(){var t=this;this.processCellClassRules((function(e){return t.addCssClass(e)}),(function(e){return t.removeCssClass(e)}))},n.prototype.preProcessCellClassRules=function(){var t=[];return this.processCellClassRules((function(e){return t.push(e)}),(function(t){})),t},n.prototype.setUsingWrapper=function(){var t=this.getComponentHolder();if(this.rowNode.rowPinned)return this.usingWrapper=!1,this.includeSelectionComponent=!1,this.includeRowDraggingComponent=!1,void(this.includeDndSourceComponent=!1);var e="function"==typeof t.checkboxSelection,o="function"==typeof t.rowDrag,n="function"==typeof t.dndSource;this.includeSelectionComponent=e||!0===t.checkboxSelection,this.includeRowDraggingComponent=o||!0===t.rowDrag,this.includeDndSourceComponent=n||!0===t.dndSource;var i=this.beans.gridOptionsWrapper.isEnableCellTextSelection();this.usingWrapper=i||this.includeRowDraggingComponent||this.includeSelectionComponent||this.includeDndSourceComponent},n.prototype.chooseCellRenderer=function(){var t=this.getComponentHolder();if(t.template||t.templateUrl)this.usingCellRenderer=!1;else{var e=this.createCellRendererParams();this.rowNode.rowPinned&&this.beans.userComponentFactory.lookupComponentClassDef(t,"pinnedRowCellRenderer",e)?(this.cellRendererType=n.CELL_RENDERER_TYPE_PINNED,this.usingCellRenderer=!0):this.beans.userComponentFactory.lookupComponentClassDef(t,"cellRenderer",e)?(this.cellRendererType=n.CELL_RENDERER_TYPE_NORMAL,this.usingCellRenderer=!0):this.usingCellRenderer=!1}},n.prototype.createCellRendererInstance=function(t){var e=this;if(void 0===t&&(t=!1),this.usingCellRenderer){var o=this.beans.gridOptionsWrapper.isAngularCompileRows(),i=this.beans.gridOptionsWrapper.isSuppressAnimationFrame();(o||i||this.autoHeightCell)&&(t=!1);var r=this.createCellRendererParams();this.cellRendererVersion++;var s=this.afterCellRendererCreated.bind(this,this.cellRendererVersion),a=this.cellRendererType===n.CELL_RENDERER_TYPE_NORMAL;this.createCellRendererFunc=function(){e.createCellRendererFunc=null;var t=e.beans.userComponentFactory.newCellRenderer(e.getComponentHolder(),r,!a);t&&t.then(s)},t?this.beans.taskQueue.createTask(this.createCellRendererFunc,this.rowNode.rowIndex,"createTasksP2"):this.createCellRendererFunc()}},n.prototype.afterCellRendererCreated=function(t,e){this.isAlive()&&t===this.cellRendererVersion?(this.cellRenderer=e,this.cellRendererGui=this.cellRenderer.getGui(),o(this.cellRendererGui)||this.editingCell||this.eCellValue.appendChild(this.cellRendererGui)):this.beans.context.destroyBean(e)},n.prototype.createCellRendererParams=function(){var t=this;return{value:this.value,valueFormatted:this.valueFormatted,getValue:this.getValue.bind(this),setValue:function(e){return t.beans.valueService.setValue(t.rowNode,t.column,e)},formatValue:this.formatValue.bind(this),data:this.rowNode.data,node:this.rowNode,colDef:this.getComponentHolder(),column:this.column,$scope:this.scope,rowIndex:this.cellPosition.rowIndex,api:this.beans.gridOptionsWrapper.getApi(),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),context:this.beans.gridOptionsWrapper.getContext(),refreshCell:this.refreshCell.bind(this),eGridCell:this.getGui(),eParentOfValue:this.eCellValue,registerRowDragger:function(e){return t.addRowDragging(e)},addRowCompListener:this.rowComp?this.rowComp.addEventListener.bind(this.rowComp):null,addRenderedRowListener:function(e,o){console.warn("AG Grid: since AG Grid .v11, params.addRenderedRowListener() is now params.addRowCompListener()"),t.rowComp&&t.rowComp.addEventListener(e,o)}}},n.prototype.formatValue=function(t){var e=this.beans.valueFormatterService.formatValue(this.column,this.rowNode,this.scope,t);return null!=e?e:t},n.prototype.getValueToUse=function(){return null!=this.valueFormatted?this.valueFormatted:this.value},n.prototype.getValueAndFormat=function(){this.value=this.getValue(),this.valueFormatted=this.beans.valueFormatterService.formatValue(this.column,this.rowNode,this.scope,this.value)},n.prototype.getValue=function(){var t=this.rowNode.leafGroup&&this.beans.columnController.isPivotMode(),e=this.rowNode.group&&this.rowNode.expanded&&!this.rowNode.footer&&!t,o=this.beans.gridOptionsWrapper.isGroupIncludeFooter(),n=this.beans.gridOptionsWrapper.isGroupSuppressBlankHeader(),i=e&&o&&!n;return this.beans.valueService.getValue(this.column,this.rowNode,!1,i)},n.prototype.onMouseEvent=function(t,e){if(!Pt(e))switch(t){case"click":this.onCellClicked(e);break;case"mousedown":this.onMouseDown(e);break;case"dblclick":this.onCellDoubleClicked(e);break;case"mouseout":this.onMouseOut(e);break;case"mouseover":this.onMouseOver(e)}},n.prototype.dispatchCellContextMenuEvent=function(t){var e=this.getComponentHolder(),o=this.createEvent(t,Wt.EVENT_CELL_CONTEXT_MENU);this.beans.eventService.dispatchEvent(o),e.onCellContextMenu&&window.setTimeout((function(){return e.onCellContextMenu(o)}),0)},n.prototype.createEvent=function(t,e){var o={node:this.rowNode,data:this.rowNode.data,value:this.value,column:this.column,colDef:this.getComponentHolder(),context:this.beans.gridOptionsWrapper.getContext(),api:this.beans.gridApi,columnApi:this.beans.columnApi,rowPinned:this.rowNode.rowPinned,event:t,type:e,rowIndex:this.rowNode.rowIndex};return this.scope&&(o.$scope=this.scope),o},n.prototype.onMouseOut=function(t){var e=this.createEvent(t,Wt.EVENT_CELL_MOUSE_OUT);this.beans.eventService.dispatchEvent(e),this.beans.columnHoverService.clearMouseOver()},n.prototype.onMouseOver=function(t){var e=this.createEvent(t,Wt.EVENT_CELL_MOUSE_OVER);this.beans.eventService.dispatchEvent(e),this.beans.columnHoverService.setMouseOver([this.column])},n.prototype.onCellDoubleClicked=function(t){var e=this.getComponentHolder(),o=this.createEvent(t,Wt.EVENT_CELL_DOUBLE_CLICKED);this.beans.eventService.dispatchEvent(o),"function"==typeof e.onCellDoubleClicked&&window.setTimeout((function(){return e.onCellDoubleClicked(o)}),0),!this.beans.gridOptionsWrapper.isSingleClickEdit()&&!this.beans.gridOptionsWrapper.isSuppressClickEdit()&&this.startRowOrCellEdit()},n.prototype.startRowOrCellEdit=function(t,e){this.beans.gridOptionsWrapper.isFullRowEdit()?this.rowComp.startRowEditing(t,e,this):this.startEditingIfEnabled(t,e,!0)},n.prototype.isCellEditable=function(){return this.column.isCellEditable(this.rowNode)},n.prototype.startEditingIfEnabled=function(t,e,n){if(void 0===t&&(t=null),void 0===e&&(e=null),void 0===n&&(n=!1),this.isCellEditable()&&!this.editingCell){this.editingCell=!0,this.cellEditorVersion++;var i=this.afterCellEditorCreated.bind(this,this.cellEditorVersion),r=this.createCellEditorParams(t,e,n);this.createCellEditor(r).then(i),o(this.cellEditor)&&n&&this.focusCell(!0)}},n.prototype.createCellEditor=function(t){var e=this;return this.beans.userComponentFactory.newCellEditor(this.column.getColDef(),t).then((function(o){var n=o;if(!(n.isPopup&&n.isPopup()))return n;e.beans.gridOptionsWrapper.isFullRowEdit()&&console.warn("AG Grid: popup cellEditor does not work with fullRowEdit - you cannot use them both - either turn off fullRowEdit, or stop using popup editors.");var i=new cs(n);return e.beans.context.createBean(i),i.init(t),i}))},n.prototype.afterCellEditorCreated=function(t,e){if(t!==this.cellEditorVersion||!this.editingCell)this.beans.context.destroyBean(e);else{if(e.isCancelBeforeStart&&e.isCancelBeforeStart())return this.beans.context.destroyBean(e),void(this.editingCell=!1);if(!e.getGui)return console.warn("AG Grid: cellEditor for column "+this.column.getId()+" is missing getGui() method"),e.render&&console.warn("AG Grid: we found 'render' on the component, are you trying to set a React renderer but added it as colDef.cellEditor instead of colDef.cellEditorFmk?"),this.beans.context.destroyBean(e),void(this.editingCell=!1);this.cellEditor=e,this.cellEditorInPopup=void 0!==e.isPopup&&e.isPopup(),this.setInlineEditingClass(),this.cellEditorInPopup?this.addPopupCellEditor():this.addInCellEditor(),e.afterGuiAttached&&e.afterGuiAttached();var o=this.createEvent(null,Wt.EVENT_CELL_EDITING_STARTED);this.beans.eventService.dispatchEvent(o)}},n.prototype.addInCellEditor=function(){var t=this.getGui();t.contains(document.activeElement)&&t.focus(),this.clearCellElement(),this.cellEditor&&t.appendChild(this.cellEditor.getGui()),this.angular1Compile()},n.prototype.addPopupCellEditor=function(){var t=this,e=this.cellEditor&&this.cellEditor.getGui();if(e){var o=this.beans.popupService,n=this.beans.gridOptionsWrapper.isStopEditingWhenGridLosesFocus(),i=this.cellEditor&&this.cellEditor.getPopupPosition?this.cellEditor.getPopupPosition():"over",r={column:this.column,rowNode:this.rowNode,type:"popupCellEditor",eventSource:this.getGui(),ePopup:e,keepWithinBounds:!0},s="under"===i?o.positionPopupUnderComponent.bind(o,r):o.positionPopupOverComponent.bind(o,r),a=o.addPopup({modal:n,eChild:e,closeOnEsc:!0,closedCallback:function(){t.onPopupEditorClosed()},anchorToElement:this.getGui(),positionCallback:s});a&&(this.hideEditorPopup=a.hideFunc),this.angular1Compile()}},n.prototype.onPopupEditorClosed=function(){this.editingCell&&this.stopRowOrCellEdit()},n.prototype.setInlineEditingClass=function(){if(this.isAlive()){var t=this.editingCell&&!this.cellEditorInPopup,e=this.editingCell&&this.cellEditorInPopup;this.addOrRemoveCssClass("ag-cell-inline-editing",t),this.addOrRemoveCssClass("ag-cell-not-inline-editing",!t),this.addOrRemoveCssClass("ag-cell-popup-editing",e),Ve(this.getGui().parentNode,"ag-row-inline-editing",t),Ve(this.getGui().parentNode,"ag-row-not-inline-editing",!t)}},n.prototype.createCellEditorParams=function(t,e,o){return{value:this.getValue(),keyPress:t,charPress:e,column:this.column,colDef:this.column.getColDef(),rowIndex:this.cellPosition.rowIndex,node:this.rowNode,data:this.rowNode.data,api:this.beans.gridOptionsWrapper.getApi(),cellStartedEdit:o,columnApi:this.beans.gridOptionsWrapper.getColumnApi(),context:this.beans.gridOptionsWrapper.getContext(),$scope:this.scope,onKeyDown:this.onKeyDown.bind(this),stopEditing:this.stopEditingAndFocus.bind(this),eGridCell:this.getGui(),parseValue:this.parseValue.bind(this),formatValue:this.formatValue.bind(this)}},n.prototype.stopEditingAndFocus=function(t){void 0===t&&(t=!1),this.stopRowOrCellEdit(),this.focusCell(!0),t||this.navigateAfterEdit()},n.prototype.parseValue=function(t){var o=this.getComponentHolder(),n={node:this.rowNode,data:this.rowNode.data,oldValue:this.value,newValue:t,colDef:o,column:this.column,api:this.beans.gridOptionsWrapper.getApi(),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),context:this.beans.gridOptionsWrapper.getContext()},i=o.valueParser;return e(i)?this.beans.expressionService.evaluate(i,n):t},n.prototype.focusCell=function(t){void 0===t&&(t=!1),this.beans.focusController.setFocusedCell(this.cellPosition.rowIndex,this.column,this.rowNode.rowPinned,t)},n.prototype.setFocusInOnEditor=function(){this.editingCell&&(this.cellEditor&&this.cellEditor.focusIn?this.cellEditor.focusIn():this.focusCell(!0))},n.prototype.isEditing=function(){return this.editingCell},n.prototype.onKeyDown=function(t){var e=t.which||t.keyCode;switch(e){case jn.ENTER:this.onEnterKeyDown(t);break;case jn.F2:this.onF2KeyDown();break;case jn.ESCAPE:this.onEscapeKeyDown();break;case jn.TAB:this.onTabKeyDown(t);break;case jn.BACKSPACE:case jn.DELETE:this.onBackspaceOrDeleteKeyPressed(e);break;case jn.DOWN:case jn.UP:case jn.RIGHT:case jn.LEFT:this.onNavigationKeyPressed(t,e)}},n.prototype.setFocusOutOnEditor=function(){this.editingCell&&this.cellEditor&&this.cellEditor.focusOut&&this.cellEditor.focusOut()},n.prototype.onNavigationKeyPressed=function(t,e){this.editingCell||(t.shiftKey&&this.rangeSelectionEnabled?this.onShiftRangeSelect(e):this.beans.rowRenderer.navigateToNextCell(t,e,this.cellPosition,!0),t.preventDefault())},n.prototype.onShiftRangeSelect=function(t){if(this.beans.rangeController){var e=this.beans.rangeController.extendLatestRangeInDirection(t);e&&this.beans.rowRenderer.ensureCellVisible(e)}},n.prototype.onTabKeyDown=function(t){this.beans.rowRenderer.onTabKeyDown(this,t)},n.prototype.onBackspaceOrDeleteKeyPressed=function(t){this.editingCell||this.startRowOrCellEdit(t)},n.prototype.onEnterKeyDown=function(t){this.editingCell||this.rowComp.isEditing()?this.stopEditingAndFocus():this.beans.gridOptionsWrapper.isEnterMovesDown()?this.beans.rowRenderer.navigateToNextCell(null,jn.DOWN,this.cellPosition,!1):(this.startRowOrCellEdit(jn.ENTER),this.editingCell&&t.preventDefault())},n.prototype.navigateAfterEdit=function(){this.beans.gridOptionsWrapper.isFullRowEdit()||this.beans.gridOptionsWrapper.isEnterMovesDownAfterEdit()&&this.beans.rowRenderer.navigateToNextCell(null,jn.DOWN,this.cellPosition,!1)},n.prototype.onF2KeyDown=function(){this.editingCell||this.startRowOrCellEdit(jn.F2)},n.prototype.onEscapeKeyDown=function(){this.editingCell&&(this.stopRowOrCellEdit(!0),this.focusCell(!0))},n.prototype.onKeyPress=function(t){if(!(At(t)!==this.getGui())&&!this.editingCell){var e=String.fromCharCode(t.charCode);" "===e?this.onSpaceKeyPressed(t):fn(t)&&(this.startRowOrCellEdit(null,e),t.preventDefault())}},n.prototype.onSpaceKeyPressed=function(t){var e=this.beans.gridOptionsWrapper;if(!this.editingCell&&e.isRowSelection()){var o=this.rowNode.isSelected(),n=!o;if(n||!e.isSuppressRowDeselection()){var i=this.beans.gridOptionsWrapper.isGroupSelectsFiltered(),r=this.rowNode.setSelectedParams({newValue:n,rangeSelect:t.shiftKey,groupSelectsFiltered:i});void 0===o&&0===r&&this.rowNode.setSelectedParams({newValue:!1,rangeSelect:t.shiftKey,groupSelectsFiltered:i})}}t.preventDefault()},n.prototype.onMouseDown=function(t){var e=t.ctrlKey,o=t.metaKey,n=t.shiftKey,i=t.target,r=this.beans,s=r.eventService,a=r.rangeController;if(!this.isRightClickInExistingRange(t)){if(!n||a&&!a.getCellRanges().length){var l=(Oe()||Pe())&&!this.editingCell&&!We(i);this.focusCell(l)}else a&&t.preventDefault();if(!this.containsWidget(i)){if(a){var p=this.cellPosition;if(n)a.extendLatestRangeToCell(p);else{var u=e||o;a.setRangeToCell(p,u)}}s.dispatchEvent(this.createEvent(t,Wt.EVENT_CELL_MOUSE_DOWN))}}},n.prototype.isRightClickInExistingRange=function(t){var e=this.beans.rangeController;if(e&&(e.isCellInAnyRange(this.getCellPosition())&&2===t.button))return!0;return!1},n.prototype.containsWidget=function(t){return Ue(t,"ag-selection-checkbox",3)},n.prototype.isDoubleClickOnIPad=function(){if(!Ae()||bt("dblclick"))return!1;var t=(new Date).getTime(),e=t-this.lastIPadMouseClickEvent<200;return this.lastIPadMouseClickEvent=t,e},n.prototype.onCellClicked=function(t){if(this.isDoubleClickOnIPad())return this.onCellDoubleClicked(t),void t.preventDefault();var e=this.beans,o=e.eventService,n=e.gridOptionsWrapper,i=this.createEvent(t,Wt.EVENT_CELL_CLICKED);o.dispatchEvent(i);var r=this.getComponentHolder();r.onCellClicked&&window.setTimeout((function(){return r.onCellClicked(i)}),0),(n.isSingleClickEdit()||r.singleClickEdit)&&!n.isSuppressClickEdit()&&this.startRowOrCellEdit()},n.prototype.createGridCellVo=function(){this.cellPosition={rowIndex:this.rowNode.rowIndex,rowPinned:this.rowNode.rowPinned,column:this.column}},n.prototype.getRowPosition=function(){return{rowIndex:this.cellPosition.rowIndex,rowPinned:this.cellPosition.rowPinned}},n.prototype.getCellPosition=function(){return this.cellPosition},n.prototype.getParentRow=function(){return this.eParentRow},n.prototype.setParentRow=function(t){this.eParentRow=t},n.prototype.getColumn=function(){return this.column},n.prototype.getComponentHolder=function(){return this.column.getColDef()},n.prototype.detach=function(){this.eParentRow.removeChild(this.getGui())},n.prototype.destroy=function(){this.createCellRendererFunc&&this.beans.taskQueue.cancelTask(this.createCellRendererFunc),this.stopEditing(),this.cellRenderer=this.beans.context.destroyBean(this.cellRenderer),this.beans.context.destroyBean(this.selectionHandle),t.prototype.destroy.call(this)},n.prototype.onLeftChanged=function(){var t=this.modifyLeftForPrintLayout(this.getCellLeft());this.getGui().style.left=t+"px",this.refreshAriaIndex()},n.prototype.modifyLeftForPrintLayout=function(t){if(!this.printLayout||this.column.getPinned()===ht.PINNED_LEFT)return t;var e=this.beans.columnController.getDisplayedColumnsLeftWidth();return this.column.getPinned()===ht.PINNED_RIGHT?e+this.beans.columnController.getBodyContainerWidth()+(t||0):e+(t||0)},n.prototype.onWidthChanged=function(){var t=this.getCellWidth();this.getGui().style.width=t+"px"},n.prototype.getRangeBorders=function(){var t,e,o=this,n=this.beans.gridOptionsWrapper.isEnableRtl(),i=!1,r=!1,s=!1,a=!1,l=this.cellPosition.column,p=this.beans,u=p.rangeController,c=p.columnController;n?(t=c.getDisplayedColAfter(l),e=c.getDisplayedColBefore(l)):(t=c.getDisplayedColBefore(l),e=c.getDisplayedColAfter(l));var d=u.getCellRanges().filter((function(t){return u.isCellInSpecificRange(o.cellPosition,t)}));t||(a=!0),e||(r=!0);for(var h=0;h<d.length&&!(i&&r&&s&&a);h++){var f=d[h],g=u.getRangeStartRow(f),y=u.getRangeEndRow(f);!i&&this.beans.rowPositionUtils.sameRow(g,this.cellPosition)&&(i=!0),!s&&this.beans.rowPositionUtils.sameRow(y,this.cellPosition)&&(s=!0),!a&&t&&f.columns.indexOf(t)<0&&(a=!0),!r&&e&&f.columns.indexOf(e)<0&&(r=!0)}return{top:i,right:r,bottom:s,left:a}},n.prototype.getInitialRangeClasses=function(){var t=[];if(!this.rangeSelectionEnabled||!this.rangeCount)return t;t.push("ag-cell-range-selected"),this.hasChartRange&&t.push("ag-cell-range-chart");var e=Math.min(this.rangeCount,4);if(t.push("ag-cell-range-selected-"+e),this.isSingleCell()&&t.push("ag-cell-range-single-cell"),this.rangeCount>0){var o=this.getRangeBorders();o.top&&t.push("ag-cell-range-top"),o.right&&t.push("ag-cell-range-right"),o.bottom&&t.push("ag-cell-range-bottom"),o.left&&t.push("ag-cell-range-left")}return this.selectionHandle&&t.push("ag-cell-range-handle"),t},n.prototype.onRowIndexChanged=function(){this.createGridCellVo(),this.onCellFocused(),this.onRangeSelectionChanged()},n.prototype.onRangeSelectionChanged=function(){var t=this.beans.rangeController;if(t){var e=this.cellPosition,o=this.rangeCount,n=t.getCellRangeCount(e),i=this.getGui();o!==n&&(this.addOrRemoveCssClass("ag-cell-range-selected",0!==n),this.addOrRemoveCssClass("ag-cell-range-selected-1",1===n),this.addOrRemoveCssClass("ag-cell-range-selected-2",2===n),this.addOrRemoveCssClass("ag-cell-range-selected-3",3===n),this.addOrRemoveCssClass("ag-cell-range-selected-4",n>=4),this.rangeCount=n),Qo(i,this.rangeCount>0);var r=this.getHasChartRange();r!==this.hasChartRange&&(this.hasChartRange=r,this.addOrRemoveCssClass("ag-cell-range-chart",this.hasChartRange)),this.updateRangeBorders(),this.addOrRemoveCssClass("ag-cell-range-single-cell",this.isSingleCell()),this.refreshHandle()}},n.prototype.getHasChartRange=function(){var t=this.beans.rangeController;if(!this.rangeCount||!t)return!1;var e=t.getCellRanges();return e.length>0&&e.every((function(t){return C([Ur.DIMENSION,Ur.VALUE],t.type)}))},n.prototype.shouldHaveSelectionHandle=function(){var t=this.beans,e=t.gridOptionsWrapper,o=t.rangeController,n=o.getCellRanges(),i=n.length;if(this.rangeCount<1||i<1)return!1;var r=d(n),s=this.getCellPosition(),a=1===i&&(e.isEnableFillHandle()||e.isEnableRangeHandle())&&!this.editingCell;if(this.hasChartRange){var l=n[0].type===Ur.DIMENSION&&o.isCellInSpecificRange(s,n[0]);this.addOrRemoveCssClass("ag-cell-range-chart-category",l),a=r.type===Ur.VALUE}return a&&null!=r.endRow&&o.isContiguousRange(r)&&o.isBottomRightCell(r,s)},n.prototype.addSelectionHandle=function(){var t=this.beans,e=t.gridOptionsWrapper,n=d(t.rangeController.getCellRanges()).type,i=e.isEnableFillHandle()&&o(n)?jr.FILL:jr.RANGE;this.selectionHandle&&this.selectionHandle.getType()!==i&&(this.selectionHandle=this.beans.context.destroyBean(this.selectionHandle)),this.selectionHandle||(this.selectionHandle=this.beans.selectionHandleFactory.createSelectionHandle(i)),this.selectionHandle.refresh(this)},n.prototype.updateRangeBordersIfRangeCount=function(){this.rangeCount>0&&(this.updateRangeBorders(),this.refreshHandle())},n.prototype.refreshHandle=function(){if(this.beans.rangeController){var t=this.shouldHaveSelectionHandle();this.selectionHandle&&!t&&(this.selectionHandle=this.beans.context.destroyBean(this.selectionHandle)),t&&this.addSelectionHandle(),this.addOrRemoveCssClass("ag-cell-range-handle",!!this.selectionHandle)}},n.prototype.updateRangeBorders=function(){var t=this.getRangeBorders(),e=this.isSingleCell(),o=!e&&t.top,n=!e&&t.right,i=!e&&t.bottom,r=!e&&t.left;this.addOrRemoveCssClass("ag-cell-range-top",o),this.addOrRemoveCssClass("ag-cell-range-right",n),this.addOrRemoveCssClass("ag-cell-range-bottom",i),this.addOrRemoveCssClass("ag-cell-range-left",r)},n.prototype.onFirstRightPinnedChanged=function(){var t=this.column.isFirstRightPinned();this.firstRightPinned!==t&&(this.firstRightPinned=t,this.addOrRemoveCssClass("ag-cell-first-right-pinned",t))},n.prototype.onLastLeftPinnedChanged=function(){var t=this.column.isLastLeftPinned();this.lastLeftPinned!==t&&(this.lastLeftPinned=t,this.addOrRemoveCssClass("ag-cell-last-left-pinned",t))},n.prototype.refreshShouldDestroy=function(){var t=this.usingWrapper,e=this.includeRowDraggingComponent,o=this.includeDndSourceComponent,n=this.includeSelectionComponent;return this.setUsingWrapper(),t!==this.usingWrapper||e!==this.includeRowDraggingComponent||o!==this.includeDndSourceComponent||n!==this.includeSelectionComponent},n.prototype.populateTemplate=function(){if(this.usingWrapper){this.eCellValue=this.getRefElement("eCellValue"),this.eCellWrapper=this.getRefElement("eCellWrapper"),this.eCellValue.id="cell-"+this.getCompId();var t="";this.includeRowDraggingComponent&&this.addRowDragging(),this.includeDndSourceComponent&&this.addDndSource(),this.includeSelectionComponent&&(t+=this.addSelectionCheckbox().getCheckboxId()),Mo(this.getGui(),t+" "+this.eCellValue.id)}else this.eCellValue=this.getGui(),this.eCellWrapper=this.eCellValue},n.prototype.getFrameworkOverrides=function(){return this.beans.frameworkOverrides},n.prototype.addRowDragging=function(t){var e=this,o=this.beans.gridOptionsWrapper.isPagination(),n=this.beans.gridOptionsWrapper.isRowDragManaged(),i=this.beans.gridOptionsWrapper.isRowModelDefault();if(n){if(!i)return void z((function(){return console.warn("AG Grid: managed row dragging is only allowed in the Client Side Row Model")}),"CellComp.addRowDragging");if(o)return void z((function(){return console.warn("AG Grid: managed row dragging is not possible when doing pagination")}),"CellComp.addRowDragging")}this.rowDraggingComp?t&&this.rowDraggingComp.setDragElement(t):(this.rowDraggingComp=new ss(this.rowNode,this.column,(function(){return e.value}),this.beans,t),this.createManagedBean(this.rowDraggingComp,this.beans.context)),t||this.eCellWrapper.insertBefore(this.rowDraggingComp.getGui(),this.eCellValue)},n.prototype.addDndSource=function(){var t=new fs(this.rowNode,this.column,this.getValueToUse(),this.beans,this.getGui());this.createManagedBean(t,this.beans.context),this.eCellWrapper.insertBefore(t.getGui(),this.eCellValue)},n.prototype.addSelectionCheckbox=function(){var t=this,e=new Ri;this.beans.context.createBean(e);var o=this.getComponentHolder().checkboxSelection;return"function"!=typeof o&&(o=void 0),e.init({rowNode:this.rowNode,column:this.column,visibleFunc:o}),this.addDestroyFunc((function(){return t.beans.context.destroyBean(e)})),this.eCellWrapper.insertBefore(e.getGui(),this.eCellValue),e},n.prototype.addDomData=function(){var t=this,e=this.getGui();this.beans.gridOptionsWrapper.setDomData(e,n.DOM_DATA_KEY_CELL_COMP,this),this.addDestroyFunc((function(){return t.beans.gridOptionsWrapper.setDomData(e,n.DOM_DATA_KEY_CELL_COMP,null)}))},n.prototype.isSingleCell=function(){var t=this.beans.rangeController;return 1===this.rangeCount&&t&&!t.isMoreThanOneCell()},n.prototype.onCellFocused=function(t){var e=this.beans.focusController.isCellFocused(this.cellPosition);e!==this.cellFocused&&(!this.beans.gridOptionsWrapper.isSuppressCellSelection()&&this.addOrRemoveCssClass("ag-cell-focus",e),this.cellFocused=e);if(e&&t&&t.forceBrowserFocus){var o=this.getFocusableElement();o.focus(),document.activeElement&&document.activeElement!==document.body||o.focus()}var n=this.beans.gridOptionsWrapper.isFullRowEdit();e||n||!this.editingCell||this.stopRowOrCellEdit()},n.prototype.stopRowOrCellEdit=function(t){void 0===t&&(t=!1),this.beans.gridOptionsWrapper.isFullRowEdit()?this.rowComp.stopRowEditing(t):this.stopEditing(t)},n.prototype.stopEditing=function(t){if(void 0===t&&(t=!1),this.editingCell)if(this.cellEditor){var e,o=this.getValue(),n=!1;if(!t)this.cellEditor.isCancelAfterEnd&&this.cellEditor.isCancelAfterEnd()||(e=this.cellEditor.getValue(),n=!0);if(this.editingCell=!1,this.beans.context.destroyBean(this.cellEditor),this.cellEditor=null,this.cellEditorInPopup&&this.hideEditorPopup)this.hideEditorPopup(),this.hideEditorPopup=null;else{this.clearCellElement();var i=this.getGui();if(this.usingWrapper)i.appendChild(this.eCellWrapper);else if(this.cellRenderer){var r=this.cellRendererGui;r&&i.appendChild(r)}}this.setInlineEditingClass(),this.refreshHandle(),n&&e!==o&&(this.suppressRefreshCell=!0,this.rowNode.setDataValue(this.column,e),this.suppressRefreshCell=!1),this.refreshCell({forceRefresh:!0,suppressFlash:!0});var s=ys(ys({},this.createEvent(null,Wt.EVENT_CELL_EDITING_STOPPED)),{oldValue:o,newValue:e});this.beans.eventService.dispatchEvent(s)}else this.editingCell=!1},n.prototype.clearCellElement=function(){var t=this.getGui();t.contains(document.activeElement)&&!Oe()&&t.focus({preventScroll:!0}),Je(t)},n.DOM_DATA_KEY_CELL_COMP="cellComp",n.CELL_RENDERER_TYPE_NORMAL="cellRenderer",n.CELL_RENDERER_TYPE_PINNED="pinnedRowCellRenderer",n}(xn),ms=function(){return(ms=Object.assign||function(t){for(var e,o=1,n=arguments.length;o<n;o++)for(var i in e=arguments[o])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)},Cs=function(){function t(){}return t.createChildScopeOrNull=function(t,e,o){if(!o.isAngularCompileRows())return null;var n=e.$new();n.data=ms({},t.data),n.rowNode=t,n.context=o.getContext();return{scope:n,scopeDestroyFunc:function(){n.$destroy(),n.data=null,n.rowNode=null,n.context=null}}},t}(),ws=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Es=function(t){function n(e,o,n,i,r,s,a,l,p,u,c){var d=t.call(this)||this;return d.eAllRowContainers=[],d.fullWidthRowDestroyFuncs=[],d.active=!0,d.rowContainerReadyCount=0,d.refreshNeeded=!1,d.columnRefreshPending=!1,d.cellComps={},d.createSecondPassFuncs=[],d.removeFirstPassFuncs=[],d.removeSecondPassFuncs=[],d.initialised=!1,d.elementOrderChanged=!1,d.lastMouseDownOnDragger=!1,d.parentScope=e,d.beans=a,d.bodyContainerComp=o,d.pinnedLeftContainerComp=n,d.pinnedRightContainerComp=i,d.fullWidthContainerComp=r,d.rowNode=s,d.rowIsEven=d.rowNode.rowIndex%2==0,d.paginationPage=d.beans.paginationProxy.getCurrentPage(),d.useAnimationFrameForCreate=p,d.printLayout=u,d.embedFullWidth=c,d.setAnimateFlags(l),d}return ws(n,t),n.prototype.init=function(){var t=this;this.rowFocused=this.beans.focusController.isRowFocused(this.rowNode.rowIndex,this.rowNode.rowPinned),this.setupAngular1Scope(),this.rowLevel=this.beans.rowCssClassCalculator.calculateRowLevel(this.rowNode),this.setupRowContainers(),this.addListeners(),this.slideRowIn&&this.createSecondPassFuncs.push((function(){t.onTopChanged()})),this.fadeRowIn&&this.createSecondPassFuncs.push((function(){t.eAllRowContainers.forEach((function(t){return xe(t,"ag-opacity-zero")}))}))},n.prototype.setupAngular1Scope=function(){var t=Cs.createChildScopeOrNull(this.rowNode,this.parentScope,this.beans.gridOptionsWrapper);t&&(this.scope=t.scope,this.addDestroyFunc(t.scopeDestroyFunc))},n.prototype.createTemplate=function(t,e){void 0===e&&(e=null);var o=[],n=this.rowNode.rowHeight,i=this.getInitialRowClasses(e).join(" "),r=Kt(this.rowNode.id),s=this.preProcessStylesFromGridOptions(),a=this.getRowBusinessKey(),l=Kt(a),p=this.getInitialRowTopStyle(),u=this.rowNode.getRowIndexString(),c=this.beans.headerNavigationService.getHeaderRowCount();return o.push("<div"),o.push(' role="row"'),o.push(' row-index="'+u+'" aria-rowindex="'+(c+this.rowNode.rowIndex+1)+'"'),o.push(r?' row-id="'+r+'"':""),o.push(a?' row-business-key="'+l+'"':""),o.push(' comp-id="'+this.getCompId()+'"'),o.push(' class="'+i+'"'),this.fullWidthRow&&o.push(' tabindex="-1"'),this.beans.gridOptionsWrapper.isRowSelection()&&o.push(' aria-selected="'+(this.rowNode.isSelected()?"true":"false")+'"'),this.rowNode.group&&o.push(" aria-expanded="+(this.rowNode.expanded?"true":"false")),o.push(' style="height: '+n+"px; "+p+" "+s+'">'),o.push(t),o.push("</div>"),o.join("")},n.prototype.getCellForCol=function(t){var e=this.cellComps[t.getColId()];return e?e.getGui():null},n.prototype.afterFlush=function(){this.initialised||(this.initialised=!0,this.executeProcessRowPostCreateFunc())},n.prototype.executeProcessRowPostCreateFunc=function(){var t=this.beans.gridOptionsWrapper.getProcessRowPostCreateFunc();t&&t({eRow:this.eBodyRow,ePinnedLeftRow:this.ePinnedLeftRow,ePinnedRightRow:this.ePinnedRightRow,node:this.rowNode,api:this.beans.gridOptionsWrapper.getApi(),rowIndex:this.rowNode.rowIndex,addRenderedRowListener:this.addEventListener.bind(this),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),context:this.beans.gridOptionsWrapper.getContext()})},n.prototype.getInitialRowTopStyle=function(){if(this.printLayout)return"";var t=this.slideRowIn?this.roundRowTopToBounds(this.rowNode.oldRowTop):this.rowNode.rowTop,e=this.applyPaginationOffset(t),o=this.rowNode.isRowPinned()?e:this.beans.maxDivHeightScaler.getRealPixelPosition(e);return this.beans.gridOptionsWrapper.isSuppressRowTransform()?"top: "+o+"px; ":"transform: translateY("+o+"px);"},n.prototype.getRowBusinessKey=function(){var t=this.beans.gridOptionsWrapper.getBusinessKeyForNodeFunc();if("function"==typeof t)return t(this.rowNode)},n.prototype.areAllContainersReady=function(){return 3===this.rowContainerReadyCount},n.prototype.lazyCreateCells=function(t,e){if(this.active){var o=this.createCells(t);e.innerHTML=o.template,this.callAfterRowAttachedOnCells(o.cellComps,e),this.rowContainerReadyCount++,this.areAllContainersReady()&&this.refreshNeeded&&this.refreshCells()}},n.prototype.createRowContainer=function(t,e,o){var n=this,i=this.useAnimationFrameForCreate,r=i?{cellComps:[],template:""}:this.createCells(e),s=this.createTemplate(r.template);t.appendRowTemplate(s,(function(){var s=t.getRowElement(n.getCompId());n.refreshAriaLabel(s,!!n.rowNode.isSelected()),n.afterRowAttached(t,s),o(s),i?n.beans.taskQueue.createTask(n.lazyCreateCells.bind(n,e,s),n.rowNode.rowIndex,"createTasksP1"):(n.callAfterRowAttachedOnCells(r.cellComps,s),n.rowContainerReadyCount=3)}))},n.prototype.setupRowContainers=function(){var t=this.rowNode.isFullWidthCell(),e=this.beans.doingMasterDetail&&this.rowNode.detail,o=this.beans.columnController.isPivotMode(),i=this.rowNode.group&&!this.rowNode.footer&&this.beans.gridOptionsWrapper.isGroupUseEntireRow(o);this.rowNode.stub?this.createFullWidthRows(n.LOADING_CELL_RENDERER,n.LOADING_CELL_RENDERER_COMP_NAME,!1):e?this.createFullWidthRows(n.DETAIL_CELL_RENDERER,n.DETAIL_CELL_RENDERER_COMP_NAME,!0):t?this.createFullWidthRows(n.FULL_WIDTH_CELL_RENDERER,null,!1):i?this.createFullWidthRows(n.GROUP_ROW_RENDERER,n.GROUP_ROW_RENDERER_COMP_NAME,!1):this.setupNormalRowContainers()},n.prototype.setupNormalRowContainers=function(){var t,e=this,o=[],n=[];this.printLayout?t=this.beans.columnController.getAllDisplayedColumns():(t=this.beans.columnController.getViewportCenterColumnsForRow(this.rowNode),o=this.beans.columnController.getDisplayedLeftColumnsForRow(this.rowNode),n=this.beans.columnController.getDisplayedRightColumnsForRow(this.rowNode)),this.createRowContainer(this.bodyContainerComp,t,(function(t){return e.eBodyRow=t})),this.createRowContainer(this.pinnedRightContainerComp,n,(function(t){return e.ePinnedRightRow=t})),this.createRowContainer(this.pinnedLeftContainerComp,o,(function(t){return e.ePinnedLeftRow=t}))},n.prototype.createFullWidthRows=function(t,e,o){var n=this;if(this.fullWidthRow=!0,this.embedFullWidth){if(this.createFullWidthRowContainer(this.bodyContainerComp,null,null,t,e,(function(t){n.eFullWidthRowBody=t}),(function(t){n.fullWidthRowComponentBody=t}),o),this.printLayout)return;this.createFullWidthRowContainer(this.pinnedLeftContainerComp,ht.PINNED_LEFT,"ag-cell-last-left-pinned",t,e,(function(t){n.eFullWidthRowLeft=t}),(function(t){n.fullWidthRowComponentLeft=t}),o),this.createFullWidthRowContainer(this.pinnedRightContainerComp,ht.PINNED_RIGHT,"ag-cell-first-right-pinned",t,e,(function(t){n.eFullWidthRowRight=t}),(function(t){n.fullWidthRowComponentRight=t}),o)}else this.createFullWidthRowContainer(this.fullWidthContainerComp,null,null,t,e,(function(t){n.eFullWidthRow=t}),(function(t){n.fullWidthRowComponent=t}),o)},n.prototype.setAnimateFlags=function(t){if(t){var o=e(this.rowNode.oldRowTop);this.slideRowIn=o,this.fadeRowIn=!o}else this.slideRowIn=!1,this.fadeRowIn=!1},n.prototype.isEditing=function(){return this.editingRow},n.prototype.stopRowEditing=function(t){this.stopEditing(t)},n.prototype.isFullWidth=function(){return this.fullWidthRow},n.prototype.refreshFullWidth=function(){var t=this,e=function(e,o,n){if(!e||!o)return!0;if(!o.refresh)return!1;var i=t.createFullWidthParams(e,n);return o.refresh(i)},o=e(this.eFullWidthRow,this.fullWidthRowComponent,null),n=e(this.eFullWidthRowBody,this.fullWidthRowComponentBody,null),i=e(this.eFullWidthRowLeft,this.fullWidthRowComponentLeft,ht.PINNED_LEFT),r=e(this.eFullWidthRowRight,this.fullWidthRowComponentRight,ht.PINNED_RIGHT);return o&&n&&i&&r},n.prototype.addListeners=function(){this.addManagedListener(this.rowNode,Ci.EVENT_HEIGHT_CHANGED,this.onRowHeightChanged.bind(this)),this.addManagedListener(this.rowNode,Ci.EVENT_ROW_SELECTED,this.onRowSelected.bind(this)),this.addManagedListener(this.rowNode,Ci.EVENT_ROW_INDEX_CHANGED,this.onRowIndexChanged.bind(this)),this.addManagedListener(this.rowNode,Ci.EVENT_TOP_CHANGED,this.onTopChanged.bind(this)),this.addManagedListener(this.rowNode,Ci.EVENT_EXPANDED_CHANGED,this.updateExpandedCss.bind(this)),this.addManagedListener(this.rowNode,Ci.EVENT_HAS_CHILDREN_CHANGED,this.updateExpandedCss.bind(this)),this.addManagedListener(this.rowNode,Ci.EVENT_DATA_CHANGED,this.onRowNodeDataChanged.bind(this)),this.addManagedListener(this.rowNode,Ci.EVENT_CELL_CHANGED,this.onRowNodeCellChanged.bind(this)),this.addManagedListener(this.rowNode,Ci.EVENT_HIGHLIGHT_CHANGED,this.onRowNodeHighlightChanged.bind(this)),this.addManagedListener(this.rowNode,Ci.EVENT_DRAGGING_CHANGED,this.onRowNodeDraggingChanged.bind(this)),this.addManagedListener(this.rowNode,Ci.EVENT_UI_LEVEL_CHANGED,this.onUiLevelChanged.bind(this));var t=this.beans.eventService;this.addManagedListener(t,Wt.EVENT_PAGINATION_PIXEL_OFFSET_CHANGED,this.onPaginationPixelOffsetChanged.bind(this)),this.addManagedListener(t,Wt.EVENT_HEIGHT_SCALE_CHANGED,this.onTopChanged.bind(this)),this.addManagedListener(t,Wt.EVENT_DISPLAYED_COLUMNS_CHANGED,this.onDisplayedColumnsChanged.bind(this)),this.addManagedListener(t,Wt.EVENT_VIRTUAL_COLUMNS_CHANGED,this.onVirtualColumnsChanged.bind(this)),this.addManagedListener(t,Wt.EVENT_COLUMN_RESIZED,this.onColumnResized.bind(this)),this.addManagedListener(t,Wt.EVENT_CELL_FOCUSED,this.onCellFocusChanged.bind(this)),this.addManagedListener(t,Wt.EVENT_PAGINATION_CHANGED,this.onPaginationChanged.bind(this)),this.addManagedListener(t,Wt.EVENT_MODEL_UPDATED,this.onModelUpdated.bind(this)),this.addManagedListener(t,Wt.EVENT_COLUMN_MOVED,this.onColumnMoved.bind(this)),this.addListenersForCellComps()},n.prototype.addListenersForCellComps=function(){var t=this;this.addManagedListener(this.rowNode,Ci.EVENT_ROW_INDEX_CHANGED,(function(){t.forEachCellComp((function(t){return t.onRowIndexChanged()}))})),this.addManagedListener(this.rowNode,Ci.EVENT_CELL_CHANGED,(function(e){t.forEachCellComp((function(t){return t.onCellChanged(e)}))}))},n.prototype.onRowNodeDataChanged=function(t){this.forEachCellComp((function(e){return e.refreshCell({suppressFlash:!t.update,newData:!t.update})})),this.onRowSelected(),this.postProcessCss()},n.prototype.onRowNodeCellChanged=function(){this.postProcessCss()},n.prototype.postProcessCss=function(){this.postProcessStylesFromGridOptions(),this.postProcessClassesFromGridOptions(),this.postProcessRowClassRules(),this.postProcessRowDragging()},n.prototype.onRowNodeHighlightChanged=function(){var t=this.rowNode.highlighted;this.eAllRowContainers.forEach((function(e){xe(e,"ag-row-highlight-above"),xe(e,"ag-row-highlight-below"),t&&Me(e,"ag-row-highlight-"+t)}))},n.prototype.onRowNodeDraggingChanged=function(){this.postProcessRowDragging()},n.prototype.postProcessRowDragging=function(){var t=this.rowNode.dragging;this.eAllRowContainers.forEach((function(e){return Ve(e,"ag-row-dragging",t)}))},n.prototype.updateExpandedCss=function(){var t=this.rowNode.isExpandable(),e=1==this.rowNode.expanded;this.eAllRowContainers.forEach((function(o){Ve(o,"ag-row-group",t),Ve(o,"ag-row-group-expanded",t&&e),Ve(o,"ag-row-group-contracted",t&&!e),Vo(o,t&&e)}))},n.prototype.onDisplayedColumnsChanged=function(){this.fullWidthRow||this.refreshCells()},n.prototype.destroyFullWidthComponents=function(){this.fullWidthRowDestroyFuncs.forEach((function(t){return t()})),this.fullWidthRowDestroyFuncs=[],this.fullWidthRowComponent&&(this.beans.detailRowCompCache.addOrDestroy(this.rowNode,null,this.fullWidthRowComponent),this.fullWidthRowComponent=null),this.fullWidthRowComponentBody&&(this.beans.detailRowCompCache.addOrDestroy(this.rowNode,null,this.fullWidthRowComponentBody),this.fullWidthRowComponentBody=null),this.fullWidthRowComponentLeft&&(this.beans.detailRowCompCache.addOrDestroy(this.rowNode,ht.PINNED_LEFT,this.fullWidthRowComponentLeft),this.fullWidthRowComponentLeft=null),this.fullWidthRowComponentRight&&(this.beans.detailRowCompCache.addOrDestroy(this.rowNode,ht.PINNED_RIGHT,this.fullWidthRowComponentRight),this.fullWidthRowComponentRight=null)},n.prototype.getContainerForCell=function(t){switch(t){case ht.PINNED_LEFT:return this.ePinnedLeftRow;case ht.PINNED_RIGHT:return this.ePinnedRightRow;default:return this.eBodyRow}},n.prototype.onVirtualColumnsChanged=function(){this.fullWidthRow||this.refreshCells()},n.prototype.onColumnResized=function(){this.fullWidthRow||this.refreshCells()},n.prototype.getRowPosition=function(){return{rowPinned:this.rowNode.rowPinned,rowIndex:this.rowNode.rowIndex}},n.prototype.onKeyboardNavigate=function(t){var e=this.rowNode,o=this.beans.focusController.getFocusedCell(),n={rowIndex:e.rowIndex,rowPinned:e.rowPinned,column:o&&o.column};this.beans.rowRenderer.navigateToNextCell(t,t.keyCode,n,!0),t.preventDefault()},n.prototype.onTabKeyDown=function(t){this.isFullWidth()&&this.beans.rowRenderer.onTabKeyDown(this,t)},n.prototype.onFullWidthRowFocused=function(t){var e=this.rowNode,o=this.fullWidthRow&&t.rowIndex===e.rowIndex&&t.rowPinned==e.rowPinned;(Ve(this.eFullWidthRow,"ag-full-width-focus",o),o)&&(this.embedFullWidth?this.eFullWidthRowBody:this.eFullWidthRow).focus()},n.prototype.refreshCell=function(t){this.areAllContainersReady()&&(this.destroyCells([t.getColumn().getId()]),this.refreshCells())},n.prototype.refreshCells=function(){if(this.areAllContainersReady())if(this.beans.gridOptionsWrapper.isSuppressAnimationFrame()||this.printLayout)this.refreshCellsInAnimationFrame();else{if(this.columnRefreshPending)return;this.beans.taskQueue.createTask(this.refreshCellsInAnimationFrame.bind(this),this.rowNode.rowIndex,"createTasksP1")}else this.refreshNeeded=!0},n.prototype.refreshCellsInAnimationFrame=function(){if(this.active){var t,e,o;this.columnRefreshPending=!1,this.printLayout?(t=this.beans.columnController.getAllDisplayedColumns(),e=[],o=[]):(t=this.beans.columnController.getViewportCenterColumnsForRow(this.rowNode),e=this.beans.columnController.getDisplayedLeftColumnsForRow(this.rowNode),o=this.beans.columnController.getDisplayedRightColumnsForRow(this.rowNode)),this.insertCellsIntoContainer(this.eBodyRow,t),this.insertCellsIntoContainer(this.ePinnedLeftRow,e),this.insertCellsIntoContainer(this.ePinnedRightRow,o),this.elementOrderChanged=!1;var n=Object.keys(this.cellComps);t.forEach((function(t){return g(n,t.getId())})),e.forEach((function(t){return g(n,t.getId())})),o.forEach((function(t){return g(n,t.getId())}));var i=n.filter(this.isCellEligibleToBeRemoved.bind(this));this.destroyCells(i)}},n.prototype.onColumnMoved=function(){this.elementOrderChanged=!0},n.prototype.destroyCells=function(t){var e=this;t.forEach((function(t){var n=e.cellComps[t];o(n)||(n.detach(),n.destroy(),e.cellComps[t]=null)}))},n.prototype.isCellEligibleToBeRemoved=function(t){var e=this.beans.columnController.getAllDisplayedColumns(),o=this.cellComps[t];if(!o||this.isCellInWrongRow(o))return!0;var n=o.isEditing(),i=this.beans.focusController.isCellFocused(o.getCellPosition());if(n||i){var r=o.getColumn();return!(e.indexOf(r)>=0)}return!0},n.prototype.ensureCellInCorrectContainer=function(t){if(!this.printLayout){var e=t.getGui(),o=t.getColumn().getPinned(),n=this.getContainerForCell(o),i=t.getParentRow();i!==n&&(i&&i.removeChild(e),n.appendChild(e),t.setParentRow(n),this.elementOrderChanged=!0)}},n.prototype.isCellInWrongRow=function(t){var e=t.getColumn(),o=this.getContainerForCell(e.getPinned());return t.getParentRow()!==o},n.prototype.insertCellsIntoContainer=function(t,e){var o=this;if(t){var n=[],i=[];if(e.forEach((function(e){var r=e.getId(),s=o.cellComps[r];s&&s.getColumn()==e?o.ensureCellInCorrectContainer(s):(s&&o.destroyCells([r]),o.createNewCell(e,t,n,i))})),n.length>0&&(no(t,n.join("")),this.callAfterRowAttachedOnCells(i,t)),this.elementOrderChanged&&this.beans.gridOptionsWrapper.isEnsureDomOrder()){var r=e.map((function(t){return o.getCellForCol(t)}));ao(t,r)}}},n.prototype.addDomData=function(t){var e=this.beans.gridOptionsWrapper;e.setDomData(t,n.DOM_DATA_KEY_RENDERED_ROW,this),this.addDestroyFunc((function(){e.setDomData(t,n.DOM_DATA_KEY_RENDERED_ROW,null)}))},n.prototype.createNewCell=function(t,e,o,n){var i=new vs(this.scope,this.beans,t,this.rowNode,this,!1,this.printLayout),r=i.getCreateTemplate();o.push(r),n.push(i),this.cellComps[t.getId()]=i,i.setParentRow(e),this.elementOrderChanged=!0},n.prototype.onMouseEvent=function(t,e){switch(t){case"dblclick":this.onRowDblClick(e);break;case"click":this.onRowClick(e);break;case"mousedown":this.onRowMouseDown(e)}},n.prototype.createRowEvent=function(t,e){return{type:t,node:this.rowNode,data:this.rowNode.data,rowIndex:this.rowNode.rowIndex,rowPinned:this.rowNode.rowPinned,context:this.beans.gridOptionsWrapper.getContext(),api:this.beans.gridOptionsWrapper.getApi(),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),event:e}},n.prototype.createRowEventWithSource=function(t,e){var o=this.createRowEvent(t,e);return o.source=this,o},n.prototype.onRowDblClick=function(t){if(!Pt(t)){var e=this.createRowEventWithSource(Wt.EVENT_ROW_DOUBLE_CLICKED,t);this.beans.eventService.dispatchEvent(e)}},n.prototype.onRowMouseDown=function(t){if(this.lastMouseDownOnDragger=Ue(t.target,"ag-row-drag",3),this.isFullWidth()){var e=this.rowNode,o=this.beans.columnController;this.beans.focusController.setFocusedCell(e.rowIndex,o.getAllDisplayedColumns()[0],e.rowPinned,!0)}},n.prototype.onRowClick=function(t){if(!(Pt(t)||this.lastMouseDownOnDragger)){var e=this.createRowEventWithSource(Wt.EVENT_ROW_CLICKED,t);this.beans.eventService.dispatchEvent(e);var o=t.ctrlKey||t.metaKey,n=t.shiftKey;if(!(this.beans.gridOptionsWrapper.isGroupSelectsChildren()&&this.rowNode.group||!this.rowNode.selectable||this.rowNode.rowPinned||!this.beans.gridOptionsWrapper.isRowSelection()||this.beans.gridOptionsWrapper.isSuppressRowClickSelection())){var i=this.beans.gridOptionsWrapper.isRowMultiSelectWithClick(),r=!this.beans.gridOptionsWrapper.isSuppressRowDeselection();if(this.rowNode.isSelected())i?this.rowNode.setSelectedParams({newValue:!1}):o?r&&this.rowNode.setSelectedParams({newValue:!1}):this.rowNode.setSelectedParams({newValue:!n,clearSelection:!n,rangeSelect:n});else{var s=!i&&!o;this.rowNode.setSelectedParams({newValue:!0,clearSelection:s,rangeSelect:n})}}}},n.prototype.createFullWidthRowContainer=function(t,e,o,n,i,r,s,a){var l=this,p=this.createTemplate("",o);t.appendRowTemplate(p,(function(){var o=t.getRowElement(l.getCompId()),p=l.createFullWidthParams(o,e),u=function(t){if(l.isAlive()){var e=t.getGui();o.appendChild(e),a&&l.setupDetailRowAutoHeight(e),s(t)}else l.beans.context.destroyBean(t)},c=l.beans.detailRowCompCache.get(l.rowNode,e);if(c)u(c);else{var d=l.beans.userComponentFactory.newFullWidthCellRenderer(p,n,i);if(!d){var h=ft.isRegistered(pt.MasterDetailModule);return void("agDetailCellRenderer"!==i||h?console.error("AG Grid: fullWidthCellRenderer "+i+" not found"):console.warn("AG Grid: cell renderer agDetailCellRenderer (for master detail) not found. Did you forget to include the master detail module?"))}d.then(u)}l.afterRowAttached(t,o),r(o),l.angular1Compile(o)}))},n.prototype.setupDetailRowAutoHeight=function(t){var e=this;if(this.beans.gridOptionsWrapper.isDetailRowAutoHeight()){var o=function(){var o=t.clientHeight;if(null!=o&&o>0){e.beans.frameworkOverrides.setTimeout((function(){e.rowNode.setRowHeight(o),e.beans.clientSideRowModel?e.beans.clientSideRowModel.onRowHeightChanged():e.beans.serverSideRowModel&&e.beans.serverSideRowModel.onRowHeightChanged()}),0)}},n=this.beans.resizeObserverService.observeResize(t,o);this.fullWidthRowDestroyFuncs.push(n),o()}},n.prototype.angular1Compile=function(t){this.scope&&this.beans.$compile(t)(this.scope)},n.prototype.createFullWidthParams=function(t,e){return{fullWidth:!0,data:this.rowNode.data,node:this.rowNode,value:this.rowNode.key,$scope:this.scope?this.scope:this.parentScope,$compile:this.beans.$compile,rowIndex:this.rowNode.rowIndex,api:this.beans.gridOptionsWrapper.getApi(),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),context:this.beans.gridOptionsWrapper.getContext(),eGridCell:t,eParentOfValue:t,pinned:e,addRenderedRowListener:this.addEventListener.bind(this)}},n.prototype.getInitialRowClasses=function(t){var e={rowNode:this.rowNode,extraCssClass:t,rowFocused:this.rowFocused,fadeRowIn:this.fadeRowIn,rowIsEven:this.rowIsEven,rowLevel:this.rowLevel,fullWidthRow:this.fullWidthRow,firstRowOnPage:this.isFirstRowOnPage(),lastRowOnPage:this.isLastRowOnPage(),printLayout:this.printLayout,expandable:this.rowNode.isExpandable(),scope:this.scope};return this.beans.rowCssClassCalculator.getInitialRowClasses(e)},n.prototype.onUiLevelChanged=function(){var t=this.beans.rowCssClassCalculator.calculateRowLevel(this.rowNode);if(this.rowLevel!=t){var e="ag-row-level-"+t,o="ag-row-level-"+this.rowLevel;this.eAllRowContainers.forEach((function(t){Me(t,e),xe(t,o)}))}this.rowLevel=t},n.prototype.isFirstRowOnPage=function(){return this.rowNode.rowIndex===this.beans.paginationProxy.getPageFirstRow()},n.prototype.isLastRowOnPage=function(){return this.rowNode.rowIndex===this.beans.paginationProxy.getPageLastRow()},n.prototype.onModelUpdated=function(){var t=this.isFirstRowOnPage(),e=this.isLastRowOnPage();this.firstRowOnPage!==t&&(this.firstRowOnPage=t,this.eAllRowContainers.forEach((function(e){return Ve(e,"ag-row-first",t)}))),this.lastRowOnPage!==e&&(this.lastRowOnPage=e,this.eAllRowContainers.forEach((function(t){return Ve(t,"ag-row-last",e)})))},n.prototype.stopEditing=function(t){if(void 0===t&&(t=!1),this.forEachCellComp((function(e){e.stopEditing(t)})),this.editingRow){if(!t){var e=this.createRowEvent(Wt.EVENT_ROW_VALUE_CHANGED);this.beans.eventService.dispatchEvent(e)}this.setEditingRow(!1)}},n.prototype.setEditingRow=function(t){this.editingRow=t,this.eAllRowContainers.forEach((function(e){return Ve(e,"ag-row-editing",t)}));var e=t?this.createRowEvent(Wt.EVENT_ROW_EDITING_STARTED):this.createRowEvent(Wt.EVENT_ROW_EDITING_STOPPED);this.beans.eventService.dispatchEvent(e)},n.prototype.startRowEditing=function(t,e,o){void 0===t&&(t=null),void 0===e&&(e=null),void 0===o&&(o=null),this.editingRow||(this.forEachCellComp((function(n){var i=n===o;i?n.startEditingIfEnabled(t,e,i):n.startEditingIfEnabled(null,null,i)})),this.setEditingRow(!0))},n.prototype.forEachCellComp=function(t){A(this.cellComps,(function(e,o){o&&t(o)}))},n.prototype.postProcessClassesFromGridOptions=function(){var t=this,e=this.beans.rowCssClassCalculator.processClassesFromGridOptions(this.rowNode,this.scope);e&&e.length&&e.forEach((function(e){t.eAllRowContainers.forEach((function(t){return Me(t,e)}))}))},n.prototype.postProcessRowClassRules=function(){var t=this;this.beans.rowCssClassCalculator.processRowClassRules(this.rowNode,this.scope,(function(e){t.eAllRowContainers.forEach((function(t){return Me(t,e)}))}),(function(e){t.eAllRowContainers.forEach((function(t){return xe(t,e)}))}))},n.prototype.preProcessStylesFromGridOptions=function(){return So(this.processStylesFromGridOptions())},n.prototype.postProcessStylesFromGridOptions=function(){var t=this.processStylesFromGridOptions();this.eAllRowContainers.forEach((function(e){return po(e,t)}))},n.prototype.processStylesFromGridOptions=function(){var t=this.beans.gridOptionsWrapper.getRowStyle();if(!t||"function"!=typeof t){var e,o=this.beans.gridOptionsWrapper.getRowStyleFunc();if(o)e=o({data:this.rowNode.data,node:this.rowNode,rowIndex:this.rowNode.rowIndex,$scope:this.scope,api:this.beans.gridOptionsWrapper.getApi(),columnApi:this.beans.gridOptionsWrapper.getColumnApi(),context:this.beans.gridOptionsWrapper.getContext()});return M({},t,e)}console.warn("AG Grid: rowStyle should be an object of key/value styles, not be a function, use getRowStyle() instead")},n.prototype.createCells=function(t){var e=this,o=[],n=[];return t.forEach((function(t){var i=new vs(e.scope,e.beans,t,e.rowNode,e,!1,e.printLayout),r=i.getCreateTemplate();o.push(r),n.push(i),e.cellComps[t.getId()]=i})),{template:o.join(""),cellComps:n}},n.prototype.onRowSelected=function(){var t=this,e=this.rowNode.isSelected();this.eAllRowContainers.forEach((function(o){Qo(o,e),Ve(o,"ag-row-selected",e),t.refreshAriaLabel(o,e)}))},n.prototype.refreshAriaLabel=function(t,e){e&&this.beans.gridOptionsWrapper.isSuppressRowDeselection()?t.removeAttribute("aria-label"):Io(t,this.beans.gridOptionsWrapper.getLocaleTextFunc()(e?"ariaRowDeselect":"ariaRowSelect","Press SPACE to "+(e?"deselect":"select")+" this row."))},n.prototype.callAfterRowAttachedOnCells=function(t,e){var o=this;t.forEach((function(t){t.setParentRow(e),t.afterAttached(),o.editingRow&&t.startEditingIfEnabled()}))},n.prototype.afterRowAttached=function(t,o){var n=this;this.addDomData(o),this.removeSecondPassFuncs.push((function(){t.removeRowElement(o)})),this.removeFirstPassFuncs.push((function(){if(e(n.rowNode.rowTop)){var t=n.roundRowTopToBounds(n.rowNode.rowTop);n.setRowTop(t)}else Me(o,"ag-opacity-zero")})),this.eAllRowContainers.push(o),this.useAnimationFrameForCreate?this.beans.taskQueue.createTask(this.addHoverFunctionality.bind(this,o),this.rowNode.rowIndex,"createTasksP2"):this.addHoverFunctionality(o)},n.prototype.addHoverFunctionality=function(t){var e=this;this.active&&(this.addManagedListener(t,"mouseenter",(function(){return e.rowNode.onMouseEnter()})),this.addManagedListener(t,"mouseleave",(function(){return e.rowNode.onMouseLeave()})),this.addManagedListener(this.rowNode,Ci.EVENT_MOUSE_ENTER,(function(){e.beans.gridOptionsWrapper.isSuppressRowHoverHighlight()||Me(t,"ag-row-hover")})),this.addManagedListener(this.rowNode,Ci.EVENT_MOUSE_LEAVE,(function(){xe(t,"ag-row-hover")})))},n.prototype.roundRowTopToBounds=function(t){var e=this.beans.gridPanel.getVScrollPosition(),o=this.applyPaginationOffset(e.top,!0)-100,n=this.applyPaginationOffset(e.bottom,!0)+100;return Math.min(Math.max(o,t),n)},n.prototype.getFrameworkOverrides=function(){return this.beans.frameworkOverrides},n.prototype.onRowHeightChanged=function(){if(e(this.rowNode.rowHeight)){var t=this.rowNode.rowHeight+"px";this.eAllRowContainers.forEach((function(e){return e.style.height=t}))}},n.prototype.addEventListener=function(e,o){"renderedRowRemoved"!==e&&"rowRemoved"!==e||(e=Wt.EVENT_VIRTUAL_ROW_REMOVED,console.warn("AG Grid: Since version 11, event renderedRowRemoved is now called "+Wt.EVENT_VIRTUAL_ROW_REMOVED)),t.prototype.addEventListener.call(this,e,o)},n.prototype.removeEventListener=function(e,o){"renderedRowRemoved"!==e&&"rowRemoved"!==e||(e=Wt.EVENT_VIRTUAL_ROW_REMOVED,console.warn("AG Grid: Since version 11, event renderedRowRemoved and rowRemoved is now called "+Wt.EVENT_VIRTUAL_ROW_REMOVED)),t.prototype.removeEventListener.call(this,e,o)},n.prototype.destroy=function(e){(void 0===e&&(e=!1),this.active=!1,this.destroyFullWidthComponents(),e)?(this.removeFirstPassFuncs.forEach((function(t){return t()})),this.removeSecondPassFuncs.push(this.destroyContainingCells.bind(this))):(this.destroyContainingCells(),this.getAndClearDelayedDestroyFunctions().forEach((function(t){return t()})));var o=this.createRowEvent(Wt.EVENT_VIRTUAL_ROW_REMOVED);this.dispatchEvent(o),this.beans.eventService.dispatchEvent(o),t.prototype.destroy.call(this)},n.prototype.destroyContainingCells=function(){var t=Object.keys(this.cellComps);this.destroyCells(t)},n.prototype.getAndClearDelayedDestroyFunctions=function(){var t=this.removeSecondPassFuncs;return this.removeSecondPassFuncs=[],t},n.prototype.onCellFocusChanged=function(){var t=this.beans.focusController.isRowFocused(this.rowNode.rowIndex,this.rowNode.rowPinned);t!==this.rowFocused&&(this.eAllRowContainers.forEach((function(e){return Ve(e,"ag-row-focus",t)})),this.eAllRowContainers.forEach((function(e){return Ve(e,"ag-row-no-focus",!t)})),this.rowFocused=t),!t&&this.editingRow&&this.stopEditing(!1)},n.prototype.onPaginationChanged=function(){var t=this.beans.paginationProxy.getCurrentPage();this.paginationPage!==t&&(this.paginationPage=t,this.onTopChanged())},n.prototype.onTopChanged=function(){this.setRowTop(this.rowNode.rowTop)},n.prototype.onPaginationPixelOffsetChanged=function(){this.onTopChanged()},n.prototype.applyPaginationOffset=function(t,e){return void 0===e&&(e=!1),this.rowNode.isRowPinned()?t:t+this.beans.paginationProxy.getPixelOffset()*(e?1:-1)},n.prototype.setRowTop=function(t){if(!this.printLayout&&e(t)){var o=this.applyPaginationOffset(t),n=(this.rowNode.isRowPinned()?o:this.beans.maxDivHeightScaler.getRealPixelPosition(o))+"px";this.beans.gridOptionsWrapper.isSuppressRowTransform()?this.eAllRowContainers.forEach((function(t){return t.style.top=n})):this.eAllRowContainers.forEach((function(t){return t.style.transform="translateY("+n+")"}))}},n.prototype.getAndClearNextVMTurnFunctions=function(){var t=this.createSecondPassFuncs;return this.createSecondPassFuncs=[],t},n.prototype.getRowNode=function(){return this.rowNode},n.prototype.getRenderedCellForColumn=function(t){var e=this,o=this.cellComps[t.getColId()];if(o)return o;var n=Object.keys(this.cellComps).map((function(t){return e.cellComps[t]})).filter((function(e){return e&&-1!==e.getColSpanningList().indexOf(t)}));return n.length?n[0]:null},n.prototype.onRowIndexChanged=function(){null!=this.rowNode.rowIndex&&(this.onCellFocusChanged(),this.updateRowIndexes())},n.prototype.updateRowIndexes=function(){var t=this,e=this.rowNode.getRowIndexString(),o=this.rowNode.rowIndex%2==0,n=this.rowIsEven!==o,i=this.beans.headerNavigationService.getHeaderRowCount();n&&(this.rowIsEven=o),this.eAllRowContainers.forEach((function(r){r.setAttribute("row-index",e),Uo(r,i+t.rowNode.rowIndex+1),n&&(Ve(r,"ag-row-even",o),Ve(r,"ag-row-odd",!o))}))},n.prototype.ensureDomOrder=function(){[{el:this.getBodyRowElement(),ct:this.bodyContainerComp},{el:this.getPinnedLeftRowElement(),ct:this.pinnedLeftContainerComp},{el:this.getPinnedRightRowElement(),ct:this.pinnedRightContainerComp},{el:this.getFullWidthRowElement(),ct:this.fullWidthContainerComp}].forEach((function(t){t.el&&t.ct.ensureDomOrder(t.el)}))},n.prototype.getPinnedLeftRowElement=function(){return this.ePinnedLeftRow?this.ePinnedLeftRow:this.eFullWidthRowLeft},n.prototype.getPinnedRightRowElement=function(){return this.ePinnedRightRow?this.ePinnedRightRow:this.eFullWidthRowRight},n.prototype.getBodyRowElement=function(){return this.eBodyRow?this.eBodyRow:this.eFullWidthRowBody},n.prototype.getFullWidthRowElement=function(){return this.eFullWidthRow},n.DOM_DATA_KEY_RENDERED_ROW="renderedRow",n.FULL_WIDTH_CELL_RENDERER="fullWidthCellRenderer",n.GROUP_ROW_RENDERER="groupRowRenderer",n.GROUP_ROW_RENDERER_COMP_NAME="agGroupRowRenderer",n.LOADING_CELL_RENDERER="loadingCellRenderer",n.LOADING_CELL_RENDERER_COMP_NAME="agLoadingCellRenderer",n.DETAIL_CELL_RENDERER="detailCellRenderer",n.DETAIL_CELL_RENDERER_COMP_NAME="agDetailCellRenderer",n}(xn),Rs=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Os=function(){return(Os=Object.assign||function(t){for(var e,o=1,n=arguments.length;o<n;o++)for(var i in e=arguments[o])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)},Ps=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Ss=function(t,e){return function(o,n){e(o,n,t)}},bs=(function(t){function n(){var e=null!==t&&t.apply(this,arguments)||this;return e.destroyFuncsForColumnListeners=[],e.rowCompsByIndex={},e.floatingTopRowComps=[],e.floatingBottomRowComps=[],e.refreshInProgress=!1,e}Rs(n,t),n.prototype.registerGridCore=function(t){this.gridCore=t},n.prototype.getGridCore=function(){return this.gridCore},n.prototype.agWire=function(t){this.logger=t.create("RowRenderer")},n.prototype.registerGridComp=function(t){this.gridPanel=t,this.rowContainers=this.gridPanel.getRowContainers(),this.addManagedListener(this.eventService,Wt.EVENT_PAGINATION_CHANGED,this.onPageLoaded.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_PINNED_ROW_DATA_CHANGED,this.onPinnedRowDataChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_DISPLAYED_COLUMNS_CHANGED,this.onDisplayedColumnsChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_BODY_SCROLL,this.redrawAfterScroll.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_BODY_HEIGHT_CHANGED,this.redrawAfterScroll.bind(this)),this.addManagedListener(this.gridOptionsWrapper,zr.PROP_DOM_LAYOUT,this.onDomLayoutChanged.bind(this)),this.registerCellEventListeners(),this.printLayout=this.gridOptionsWrapper.getDomLayout()===ht.DOM_LAYOUT_PRINT,this.embedFullWidthRows=this.printLayout||this.gridOptionsWrapper.isEmbedFullWidthRows(),this.redrawAfterModelUpdate()},n.prototype.registerCellEventListeners=function(){var t=this;this.addManagedListener(this.eventService,Wt.EVENT_CELL_FOCUSED,(function(e){t.forEachCellComp((function(t){return t.onCellFocused(e)})),t.forEachRowComp((function(t,o){o.isFullWidth()&&o.onFullWidthRowFocused(e)}))})),this.addManagedListener(this.eventService,Wt.EVENT_FLASH_CELLS,(function(e){t.forEachCellComp((function(t){return t.onFlashCells(e)}))})),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_HOVER_CHANGED,(function(){t.forEachCellComp((function(t){return t.onColumnHover()}))})),this.addManagedListener(this.eventService,Wt.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED,(function(){t.printLayout&&t.forEachCellComp((function(t){return t.onLeftChanged()}))})),this.gridOptionsWrapper.isEnableRangeSelection()&&(this.addManagedListener(this.eventService,Wt.EVENT_RANGE_SELECTION_CHANGED,(function(){t.forEachCellComp((function(t){return t.onRangeSelectionChanged()}))})),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_MOVED,(function(){t.forEachCellComp((function(t){return t.updateRangeBordersIfRangeCount()}))})),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_PINNED,(function(){t.forEachCellComp((function(t){return t.updateRangeBordersIfRangeCount()}))})),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_VISIBLE,(function(){t.forEachCellComp((function(t){return t.updateRangeBordersIfRangeCount()}))}))),this.refreshListenersToColumnsForCellComps(),this.addManagedListener(this.eventService,Wt.EVENT_GRID_COLUMNS_CHANGED,this.refreshListenersToColumnsForCellComps.bind(this)),this.addDestroyFunc(this.removeGridColumnListeners.bind(this))},n.prototype.removeGridColumnListeners=function(){this.destroyFuncsForColumnListeners.forEach((function(t){return t()})),this.destroyFuncsForColumnListeners.length=0},n.prototype.refreshListenersToColumnsForCellComps=function(){var t=this;this.removeGridColumnListeners();var e=this.columnController.getAllGridColumns();e&&e.forEach((function(e){var o=function(o){t.forEachCellComp((function(t){t.getColumn()===e&&o(t)}))},n=function(){o((function(t){return t.onLeftChanged()}))},i=function(){o((function(t){return t.onWidthChanged()}))},r=function(){o((function(t){return t.onFirstRightPinnedChanged()}))},s=function(){o((function(t){return t.onLastLeftPinnedChanged()}))};e.addEventListener(yt.EVENT_LEFT_CHANGED,n),e.addEventListener(yt.EVENT_WIDTH_CHANGED,i),e.addEventListener(yt.EVENT_FIRST_RIGHT_PINNED_CHANGED,r),e.addEventListener(yt.EVENT_LAST_LEFT_PINNED_CHANGED,s),t.destroyFuncsForColumnListeners.push((function(){e.removeEventListener(yt.EVENT_LEFT_CHANGED,n),e.removeEventListener(yt.EVENT_WIDTH_CHANGED,i),e.removeEventListener(yt.EVENT_FIRST_RIGHT_PINNED_CHANGED,r),e.removeEventListener(yt.EVENT_LAST_LEFT_PINNED_CHANGED,s)}))}))},n.prototype.onDomLayoutChanged=function(){var t=this.gridOptionsWrapper.getDomLayout()===ht.DOM_LAYOUT_PRINT,e=t||this.gridOptionsWrapper.isEmbedFullWidthRows(),o=e!==this.embedFullWidthRows||this.printLayout!==t;this.printLayout=t,this.embedFullWidthRows=e,o&&this.redrawAfterModelUpdate()},n.prototype.datasourceChanged=function(){this.firstRenderedRow=0,this.lastRenderedRow=-1;var t=Object.keys(this.rowCompsByIndex);this.removeRowComps(t)},n.prototype.onPageLoaded=function(t){o(t)&&(t={type:Wt.EVENT_MODEL_UPDATED,api:this.gridApi,columnApi:this.columnApi,animate:!1,keepRenderedRows:!1,newData:!1,newPage:!1}),this.onModelUpdated(t)},n.prototype.getAllCellsForColumn=function(t){var e=[];function o(o,n){var i=n.getCellForCol(t);i&&e.push(i)}return A(this.rowCompsByIndex,o),A(this.floatingBottomRowComps,o),A(this.floatingTopRowComps,o),e},n.prototype.refreshFloatingRowComps=function(){this.refreshFloatingRows(this.floatingTopRowComps,this.pinnedRowModel.getPinnedTopRowData(),this.rowContainers.floatingTopPinnedLeft,this.rowContainers.floatingTopPinnedRight,this.rowContainers.floatingTop,this.rowContainers.floatingTopFullWidth),this.refreshFloatingRows(this.floatingBottomRowComps,this.pinnedRowModel.getPinnedBottomRowData(),this.rowContainers.floatingBottomPinnedLeft,this.rowContainers.floatingBottomPinnedRight,this.rowContainers.floatingBottom,this.rowContainers.floatingBottomFullWidth)},n.prototype.refreshFloatingRows=function(t,e,o,n,i,r){var s=this;t.forEach((function(t){t.destroy()})),t.length=0,e&&e.forEach((function(e){var a=new Es(s.$scope,i,o,n,r,e,s.beans,!1,!1,s.printLayout,s.embedFullWidthRows);a.init(),t.push(a)})),this.flushContainers(t)},n.prototype.onPinnedRowDataChanged=function(){this.redrawAfterModelUpdate({recycleRows:!0})},n.prototype.onModelUpdated=function(t){var e={recycleRows:t.keepRenderedRows,animate:t.animate,newData:t.newData,newPage:t.newPage,onlyBody:!0};this.redrawAfterModelUpdate(e)},n.prototype.getRenderedIndexesForRowNodes=function(t){var e=[];return o(t)||A(this.rowCompsByIndex,(function(o,n){var i=n.getRowNode();t.indexOf(i)>=0&&e.push(o)})),e},n.prototype.redrawRows=function(t){if(t&&0!=t.length){var e=this.getRenderedIndexesForRowNodes(t);this.removeRowComps(e),this.redrawAfterModelUpdate({recycleRows:!0})}},n.prototype.getCellToRestoreFocusToAfterRefresh=function(t){var e=t.suppressKeepFocus?null:this.focusController.getFocusCellToUseAfterRefresh();if(o(e))return null;var n=document.activeElement;return o(this.gridOptionsWrapper.getDomData(n,vs.DOM_DATA_KEY_CELL_COMP))?null:e},n.prototype.redrawAfterModelUpdate=function(t){void 0===t&&(t={}),this.getLockOnRefresh();var e=this.getCellToRestoreFocusToAfterRefresh(t);this.sizeContainerToPageHeight(),this.scrollToTopIfNewData(t);var o=!this.printLayout&&!!t.recycleRows,n=t.animate&&this.gridOptionsWrapper.isAnimateRows(),i=this.binRowComps(o),r=function(){if(null==e||null==i)return!1;var t=!1;return A(i,(function(o,n){var i=n.getRowNode(),r=i.rowIndex==e.rowIndex,s=i.rowPinned==e.rowPinned;r&&s&&(t=!0)})),t}();this.redraw(i,n),t.onlyBody||this.refreshFloatingRowComps(),r||this.restoreFocusedCell(e),this.releaseLockOnRefresh()},n.prototype.scrollToTopIfNewData=function(t){var e=t.newData||t.newPage,o=this.gridOptionsWrapper.isSuppressScrollOnNewData();e&&!o&&this.gridPanel.scrollToTop()},n.prototype.sizeContainerToPageHeight=function(){var t=[this.rowContainers.body,this.rowContainers.fullWidth,this.rowContainers.pinnedLeft,this.rowContainers.pinnedRight];if(this.printLayout)t.forEach((function(t){return t.setHeight(null)}));else{var e=this.paginationProxy.getCurrentPageHeight();0===e&&(e=1),this.maxDivHeightScaler.setModelHeight(e);var o=this.maxDivHeightScaler.getUiContainerHeight();t.forEach((function(t){return t.setHeight(o)}))}},n.prototype.getLockOnRefresh=function(){if(this.refreshInProgress)throw new Error("AG Grid: cannot get grid to draw rows when it is in the middle of drawing rows. Your code probably called a grid API method while the grid was in the render stage. To overcome this, put the API call into a timeout, e.g. instead of api.refreshView(), call setTimeout(function() { api.refreshView(); }, 0). To see what part of your code that caused the refresh check this stacktrace.");this.refreshInProgress=!0},n.prototype.releaseLockOnRefresh=function(){this.refreshInProgress=!1},n.prototype.restoreFocusedCell=function(t){t&&this.focusController.setFocusedCell(t.rowIndex,t.column,t.rowPinned,!0)},n.prototype.stopEditing=function(t){void 0===t&&(t=!1),this.forEachRowComp((function(e,o){o.stopEditing(t)}))},n.prototype.forEachCellComp=function(t){this.forEachRowComp((function(e,o){return o.forEachCellComp(t)}))},n.prototype.forEachRowComp=function(t){A(this.rowCompsByIndex,t),A(this.floatingTopRowComps,t),A(this.floatingBottomRowComps,t)},n.prototype.addRenderedRowListener=function(t,e,o){var n=this.rowCompsByIndex[e];n&&n.addEventListener(t,o)},n.prototype.flashCells=function(t){void 0===t&&(t={});var e=t.flashDelay,o=t.fadeDelay;this.forEachCellCompFiltered(t.rowNodes,t.columns,(function(t){return t.flashCell({flashDelay:e,fadeDelay:o})}))},n.prototype.refreshCells=function(t){void 0===t&&(t={});var e={forceRefresh:t.force,newData:!1,suppressFlash:t.suppressFlash};this.forEachCellCompFiltered(t.rowNodes,t.columns,(function(t){if(t.refreshShouldDestroy()){var o=t.getRenderedRow();o&&o.refreshCell(t)}else t.refreshCell(e)}))},n.prototype.getCellRendererInstances=function(t){var e=[];return this.forEachCellCompFiltered(t.rowNodes,t.columns,(function(t){var o=t.getCellRenderer();o&&e.push(o)})),e},n.prototype.getCellEditorInstances=function(t){var e=[];return this.forEachCellCompFiltered(t.rowNodes,t.columns,(function(t){var o=t.getCellEditor();o&&e.push(o)})),e},n.prototype.getEditingCells=function(){var t=[];return this.forEachCellComp((function(e){if(e.isEditing()){var o=e.getCellPosition();t.push(o)}})),t},n.prototype.forEachCellCompFiltered=function(t,o,n){var i,r,s=this;e(t)&&(i={top:{},bottom:{},normal:{}},t.forEach((function(t){var e=t.id;t.rowPinned===ht.PINNED_TOP?i.top[e]=!0:t.rowPinned===ht.PINNED_BOTTOM?i.bottom[e]=!0:i.normal[e]=!0}))),e(o)&&(r={},o.forEach((function(t){var o=s.columnController.getGridColumn(t);e(o)&&(r[o.getId()]=!0)})));var a=function(t){var o=t.getRowNode(),s=o.id,a=o.rowPinned;if(e(i))if(a===ht.PINNED_BOTTOM){if(!i.bottom[s])return}else if(a===ht.PINNED_TOP){if(!i.top[s])return}else if(!i.normal[s])return;t.forEachCellComp((function(t){var e=t.getColumn().getId();r&&!r[e]||n&&n(t)}))};A(this.rowCompsByIndex,(function(t,e){a(e)})),this.floatingTopRowComps&&this.floatingTopRowComps.forEach(a),this.floatingBottomRowComps&&this.floatingBottomRowComps.forEach(a)},n.prototype.destroy=function(){var e=Object.keys(this.rowCompsByIndex);this.removeRowComps(e),t.prototype.destroy.call(this)},n.prototype.binRowComps=function(t){var o,n=this,i={};return t?(o=[],A(this.rowCompsByIndex,(function(t,r){var s=r.getRowNode();e(s.id)?(i[s.id]=r,delete n.rowCompsByIndex[t]):o.push(t)}))):o=Object.keys(this.rowCompsByIndex),this.removeRowComps(o),i},n.prototype.removeRowComps=function(t){var e=this;t.forEach((function(t){var o=e.rowCompsByIndex[t];o&&o.destroy(),delete e.rowCompsByIndex[t]}))},n.prototype.redrawAfterScroll=function(){this.getLockOnRefresh(),this.redraw(null,!1,!0),this.releaseLockOnRefresh()},n.prototype.removeRowCompsNotToDraw=function(t){var e={};t.forEach((function(t){return e[t]=!0}));var o=Object.keys(this.rowCompsByIndex).filter((function(t){return!e[t]}));this.removeRowComps(o)},n.prototype.calculateIndexesToDraw=function(t){var e=this,o=te(this.firstRenderedRow,this.lastRenderedRow),n=function(t,n){var i=n.getRowNode().rowIndex;null!=i&&(i<e.firstRenderedRow||i>e.lastRenderedRow)&&e.doNotUnVirtualiseRow(n)&&o.push(i)};return A(this.rowCompsByIndex,n),A(t,n),o.sort((function(t,e){return t-e})),o},n.prototype.redraw=function(t,o,n){var i=this;void 0===o&&(o=!1),void 0===n&&(n=!1),this.maxDivHeightScaler.updateOffset(),this.workOutFirstAndLastRowsToRender();var r=this.calculateIndexesToDraw(t);this.removeRowCompsNotToDraw(r),this.printLayout&&(o=!1);var s=[],a=[];r.forEach((function(r){var l=i.createOrUpdateRowComp(r,t,o,n);e(l)&&(a.push(l),w(s,l.getAndClearNextVMTurnFunctions()))})),this.flushContainers(a),X(s),n&&!this.gridOptionsWrapper.isSuppressAnimationFrame()&&!this.printLayout?this.beans.taskQueue.addDestroyTask(this.destroyRowComps.bind(this,t,o)):this.destroyRowComps(t,o),this.checkAngularCompile(),this.gridPanel.updateRowCount()},n.prototype.flushContainers=function(t){A(this.rowContainers,(function(t,e){e&&e.flushRowTemplates()})),t.forEach((function(t){return t.afterFlush()}))},n.prototype.onDisplayedColumnsChanged=function(){var t=this.columnController.isPinningLeft(),e=this.columnController.isPinningRight();(this.pinningLeft!==t||e!==this.pinningRight)&&(this.pinningLeft=t,this.pinningRight=e,this.embedFullWidthRows&&this.redrawFullWidthEmbeddedRows())},n.prototype.redrawFullWidthEmbeddedRows=function(){var t=[];A(this.rowCompsByIndex,(function(e,o){if(o.isFullWidth()){var n=o.getRowNode().rowIndex;t.push(n.toString())}})),this.refreshFloatingRowComps(),this.removeRowComps(t),this.redrawAfterScroll()},n.prototype.refreshFullWidthRows=function(t){var e=[],o=!!t,n=o?{}:void 0;o&&n&&t.forEach((function(t){return n[t.id]=!0})),A(this.rowCompsByIndex,(function(t,i){if(i.isFullWidth()){var r=i.getRowNode();if(o&&n){var s=r.level>0&&r.parent?r.parent.id:void 0;if(!n[r.id]&&!n[s])return}if(!i.refreshFullWidth()){var a=i.getRowNode().rowIndex;e.push(a.toString())}}})),this.removeRowComps(e),this.redrawAfterScroll()},n.prototype.createOrUpdateRowComp=function(t,o,n,i){var r=null,s=this.rowCompsByIndex[t];if(s||e(r=this.paginationProxy.getRow(t))&&e(o)&&o[r.id]&&r.alreadyRendered&&(s=o[r.id],o[r.id]=null),!s){if(r||(r=this.paginationProxy.getRow(t)),!e(r))return;s=this.createRowComp(r,n,i)}else s&&s.ensureDomOrder();return r&&(r.alreadyRendered=!0),this.rowCompsByIndex[t]=s,s},n.prototype.destroyRowComps=function(t,e){var o=[];A(t,(function(t,n){n&&(n.destroy(e),w(o,n.getAndClearDelayedDestroyFunctions()))})),q(o)},n.prototype.checkAngularCompile=function(){var t=this;this.gridOptionsWrapper.isAngularCompileRows()&&window.setTimeout((function(){t.$scope.$apply()}),0)},n.prototype.workOutFirstAndLastRowsToRender=function(){var t,e,o=this;if(this.paginationProxy.isRowsToRender())if(this.printLayout)t=this.paginationProxy.getPageFirstRow(),e=this.paginationProxy.getPageLastRow();else{var n=this.paginationProxy.getPixelOffset(),i=this.paginationProxy.getCurrentPagePixelRange(),r=i.pageFirstPixel,s=i.pageLastPixel,a=this.maxDivHeightScaler.getOffset(),l=this.gridPanel.getVScrollPosition(),p=l.top,u=l.bottom,c=this.gridOptionsWrapper.getRowBufferInPixels(),d=Math.max(p+n-c,r)+a,h=Math.min(u+n+c,s)+a;this.ensureAllRowsInRangeHaveHeightsCalculated(d,h);var f=this.paginationProxy.getRowIndexAtPixel(d),g=this.paginationProxy.getRowIndexAtPixel(h),y=this.paginationProxy.getPageFirstRow(),v=this.paginationProxy.getPageLastRow();f<y&&(f=y),g>v&&(g=v),t=f,e=g}else t=0,e=-1;var m=this.gridOptionsWrapper.getDomLayout()===ht.DOM_LAYOUT_NORMAL,C=this.gridOptionsWrapper.isSuppressMaxRenderedRowRestriction(),w=Math.max(this.gridOptionsWrapper.getRowBuffer(),500);m&&!C&&e-t>w&&(e=t+w);var E=t!==this.firstRenderedRow,R=e!==this.lastRenderedRow;if(E||R){this.firstRenderedRow=t,this.lastRenderedRow=e;var O={type:Wt.EVENT_VIEWPORT_CHANGED,firstRow:t,lastRow:e,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(O)}if(this.paginationProxy.isRowsToRender()){var P={type:Wt.EVENT_FIRST_DATA_RENDERED,firstRow:t,lastRow:e,api:this.gridApi,columnApi:this.columnApi};window.setTimeout((function(){return o.eventService.dispatchEventOnce(P)}),50)}},n.prototype.ensureAllRowsInRangeHaveHeightsCalculated=function(t,e){this.paginationProxy.ensureRowHeightsValid(t,e,-1,-1)&&(this.sizeContainerToPageHeight(),this.maxDivHeightScaler.updateOffset())},n.prototype.getFirstVirtualRenderedRow=function(){return this.firstRenderedRow},n.prototype.getLastVirtualRenderedRow=function(){return this.lastRenderedRow},n.prototype.doNotUnVirtualiseRow=function(t){var e=t.getRowNode(),o=this.focusController.isRowNodeFocused(e),n=t.isEditing(),i=e.detail;return!!(o||n||i)&&!!this.paginationProxy.isRowPresent(e)},n.prototype.createRowComp=function(t,e,o){var n=this.gridOptionsWrapper.isSuppressAnimationFrame(),i=o&&!n&&!this.printLayout,r=new Es(this.$scope,this.rowContainers.body,this.rowContainers.pinnedLeft,this.rowContainers.pinnedRight,this.rowContainers.fullWidth,t,this.beans,e,i,this.printLayout,this.embedFullWidthRows);return r.init(),r},n.prototype.getRenderedNodes=function(){var t=this.rowCompsByIndex;return Object.keys(t).map((function(e){return t[e].getRowNode()}))},n.prototype.navigateToNextCell=function(t,n,i,r){for(var s=i,a=!1;s&&(s===i||!this.isValidNavigateCell(s));)this.gridOptionsWrapper.isEnableRtl()?n===jn.LEFT&&(s=this.getLastCellOfColSpan(s)):n===jn.RIGHT&&(s=this.getLastCellOfColSpan(s)),a=o(s=this.cellNavigationService.getNextCellToFocus(n,s));if(a&&t&&t.keyCode===jn.UP&&(s={rowIndex:-1,rowPinned:null,column:i.column}),r){var l=this.gridOptionsWrapper.getNavigateToNextCellFunc();if(e(l)){var p=l({key:n,previousCellPosition:i,nextCellPosition:s||null,event:t});e(p)?(p.floating&&(z((function(){console.warn("AG Grid: tabToNextCellFunc return type should have attributes: rowIndex, rowPinned, column. However you had 'floating', maybe you meant 'rowPinned'?")}),"no floating in userCell"),p.rowPinned=p.floating),s={rowPinned:p.rowPinned,rowIndex:p.rowIndex,column:p.column}):s=null}}if(s)if(s.rowIndex<0){var u=this.beans.headerNavigationService.getHeaderRowCount();this.focusController.focusHeaderPosition({headerRowIndex:u+s.rowIndex,column:i.column})}else{var c=this.getNormalisedPosition(s);c?this.focusPosition(c):this.tryToFocusFullWidthRow(s)}},n.prototype.getNormalisedPosition=function(t){this.ensureCellVisible(t);var e=this.getComponentForCell(t);return e?(t=e.getCellPosition(),this.ensureCellVisible(t),t):null},n.prototype.tryToFocusFullWidthRow=function(t,e){void 0===e&&(e=!1);var o=this.columnController.getAllDisplayedColumns(),n=this.getRowCompByPosition(t);if(!n||!n.isFullWidth())return!1;var i={rowIndex:t.rowIndex,rowPinned:t.rowPinned,column:t.column||(e?d(o):o[0])};return this.focusPosition(i),!0},n.prototype.focusPosition=function(t){this.focusController.setFocusedCell(t.rowIndex,t.column,t.rowPinned,!0),this.rangeController&&this.rangeController.setRangeToCell(t)},n.prototype.isValidNavigateCell=function(t){return!!this.rowPositionUtils.getRowNode(t)},n.prototype.getLastCellOfColSpan=function(t){var e=this.getComponentForCell(t);if(!e)return t;var o=e.getColSpanningList();return 1===o.length?t:{rowIndex:t.rowIndex,column:d(o),rowPinned:t.rowPinned}},n.prototype.ensureCellVisible=function(t){o(t.rowPinned)&&this.gridPanel.ensureIndexVisible(t.rowIndex),t.column.isPinned()||this.gridPanel.ensureColumnVisible(t.column),this.gridPanel.horizontallyScrollHeaderCenterAndFloatingCenter(),this.animationFrameService.flushAllFrames()},n.prototype.startEditingCell=function(t,e,o){var n=this.getComponentForCell(t);n&&n.startRowOrCellEdit(e,o)},n.prototype.getRowCompByPosition=function(t){var e;switch(t.rowPinned){case ht.PINNED_TOP:e=this.floatingTopRowComps[t.rowIndex];break;case ht.PINNED_BOTTOM:e=this.floatingBottomRowComps[t.rowIndex];break;default:e=this.rowCompsByIndex[t.rowIndex]}return e},n.prototype.getComponentForCell=function(t){var e=this.getRowCompByPosition(t);return e?e.getRenderedCellForColumn(t.column):null},n.prototype.getRowNode=function(t){switch(t.rowPinned){case ht.PINNED_TOP:return this.pinnedRowModel.getPinnedTopRowData()[t.rowIndex];case ht.PINNED_BOTTOM:return this.pinnedRowModel.getPinnedBottomRowData()[t.rowIndex];default:return this.rowModel.getRow(t.rowIndex)}},n.prototype.onTabKeyDown=function(t,e){var o=e.shiftKey;if(this.moveToCellAfter(t,o))e.preventDefault();else if(o){var n=t.getRowPosition(),i=n.rowIndex;if(n.rowPinned?0===i:i===this.paginationProxy.getPageFirstRow()){e.preventDefault();var r=this.beans.headerNavigationService.getHeaderRowCount()-1,s=d(this.columnController.getAllDisplayedColumns());this.focusController.focusHeaderPosition({headerRowIndex:r,column:s})}}else t instanceof vs&&t.focusCell(!0),this.focusController.focusNextGridCoreContainer(!1)&&e.preventDefault()},n.prototype.tabToNextCell=function(t){var e=this.focusController.getFocusedCell();if(o(e))return!1;var n=this.getComponentForCell(e);return!!(!o(n)||(n=this.getRowCompByPosition(e))&&n.isFullWidth())&&this.moveToCellAfter(n,t)},n.prototype.moveToCellAfter=function(t,e){return(t.isEditing()?this.gridOptionsWrapper.isFullRowEdit()?this.moveToNextEditingRow(t,e):this.moveToNextEditingCell(t,e):this.moveToNextCellNotEditing(t,e))||!!this.focusController.getFocusedHeader()},n.prototype.moveToNextEditingCell=function(t,o){var n=t.getCellPosition();t.stopEditing();var i=this.findNextCellToFocusOn(n,o,!0),r=e(i);return r&&i&&(i.startEditingIfEnabled(null,null,!0),i.focusCell(!1)),r},n.prototype.moveToNextEditingRow=function(t,o){var n=t.getCellPosition(),i=this.findNextCellToFocusOn(n,o,!0),r=e(i);return r&&i&&this.moveEditToNextCellOrRow(t,i),r},n.prototype.moveToNextCellNotEditing=function(t,o){var n,i=this.columnController.getAllDisplayedColumns();n=t instanceof Es?Os(Os({},t.getRowPosition()),{column:o?i[0]:d(i)}):t.getCellPosition();var r=this.findNextCellToFocusOn(n,o,!1);if(r instanceof vs)r.focusCell(!0);else if(r)return this.tryToFocusFullWidthRow(r.getRowPosition(),o);return e(r)},n.prototype.moveEditToNextCellOrRow=function(t,e){var o=t.getCellPosition(),n=e.getCellPosition();if(n&&o.rowIndex===n.rowIndex&&o.rowPinned===n.rowPinned)t.setFocusOutOnEditor(),e.setFocusInOnEditor();else{var i=t.getRenderedRow(),r=e.getRenderedRow();t.setFocusOutOnEditor(),i.stopEditing(),r.startRowEditing(),e.setFocusInOnEditor()}e.focusCell()},n.prototype.findNextCellToFocusOn=function(t,o,n){for(var i=t;;){o||(i=this.getLastCellOfColSpan(i)),i=this.cellNavigationService.getNextTabbedCell(i,o);var r=this.gridOptionsWrapper.getTabToNextCellFunc();if(e(r)){var s=r({backwards:o,editing:n,previousCellPosition:t,nextCellPosition:i||null});e(s)?(s.floating&&(z((function(){console.warn("AG Grid: tabToNextCellFunc return type should have attributes: rowIndex, rowPinned, column. However you had 'floating', maybe you meant 'rowPinned'?")}),"no floating in userCell"),s.rowPinned=s.floating),i={rowIndex:s.rowIndex,column:s.column,rowPinned:s.rowPinned}):i=null}if(!i)return null;if(i.rowIndex<0){var a=this.beans.headerNavigationService.getHeaderRowCount();return this.focusController.focusHeaderPosition({headerRowIndex:a+i.rowIndex,column:i.column}),null}if(n){var l=this.lookupRowNodeForCell(i);if(!(l&&i.column.isCellEditable(l)))continue}this.ensureCellVisible(i);var p=this.getComponentForCell(i);if(p){if(!p.isSuppressNavigable())return this.rangeController&&this.rangeController.setRangeToCell(i),p}else{var u=this.getRowCompByPosition(i);if(u&&u.isFullWidth())return u}}},n.prototype.lookupRowNodeForCell=function(t){return t.rowPinned===ht.PINNED_TOP?this.pinnedRowModel.getPinnedTopRow(t.rowIndex):t.rowPinned===ht.PINNED_BOTTOM?this.pinnedRowModel.getPinnedBottomRow(t.rowIndex):this.paginationProxy.getRow(t.rowIndex)},n.prototype.isRangeInRenderedViewport=function(t,e){if(null==t||null==e)return!1;var o=t>this.lastRenderedRow;return!(e<this.firstRenderedRow)&&!o},Ps([it("paginationProxy")],n.prototype,"paginationProxy",void 0),Ps([it("columnController")],n.prototype,"columnController",void 0),Ps([it("$scope")],n.prototype,"$scope",void 0),Ps([it("pinnedRowModel")],n.prototype,"pinnedRowModel",void 0),Ps([it("rowModel")],n.prototype,"rowModel",void 0),Ps([it("focusController")],n.prototype,"focusController",void 0),Ps([it("cellNavigationService")],n.prototype,"cellNavigationService",void 0),Ps([it("columnApi")],n.prototype,"columnApi",void 0),Ps([it("gridApi")],n.prototype,"gridApi",void 0),Ps([it("beans")],n.prototype,"beans",void 0),Ps([it("maxDivHeightScaler")],n.prototype,"maxDivHeightScaler",void 0),Ps([it("animationFrameService")],n.prototype,"animationFrameService",void 0),Ps([it("rowPositionUtils")],n.prototype,"rowPositionUtils",void 0),Ps([rt("rangeController")],n.prototype,"rangeController",void 0),Ps([Ss(0,at("loggerFactory"))],n.prototype,"agWire",null),n=Ps([nt("rowRenderer")],n)}(Mt),function(){function t(){}return t.addHeaderClassesFromColDef=function(t,e,n,i,r){o(t)||this.addColumnClassesFromCollDef(t.headerClass,t,e,n,i,r)},t.addToolPanelClassesFromColDef=function(t,e,n,i,r){o(t)||this.addColumnClassesFromCollDef(t.toolPanelClass,t,e,n,i,r)},t.addColumnClassesFromCollDef=function(t,e,n,i,r,s){if(!o(t)){var a;if("function"==typeof t)a=t({colDef:e,column:r,columnGroup:s,context:i.getContext(),api:i.getApi()});else a=t;"string"==typeof a?Me(n,a):Array.isArray(a)&&a.forEach((function(t){Me(n,t)}))}},t}()),Ds=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),As=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Ts=function(t){function e(e,o){var n=t.call(this)||this;return n.columns=e,n.element=o,n}return Ds(e,t),e.prototype.postConstruct=function(){this.addMouseHoverListeners()},e.prototype.addMouseHoverListeners=function(){this.addManagedListener(this.element,"mouseout",this.onMouseOut.bind(this)),this.addManagedListener(this.element,"mouseover",this.onMouseOver.bind(this))},e.prototype.onMouseOut=function(){this.columnHoverService.clearMouseOver()},e.prototype.onMouseOver=function(){this.columnHoverService.setMouseOver(this.columns)},As([it("columnHoverService")],e.prototype,"columnHoverService",void 0),As([et],e.prototype,"postConstruct",null),e}(Mt),_s=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Fs=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Ns=function(t){function o(e,o,n,i){var r=t.call(this)||this;return r.columnOrGroup=e,r.eCell=o,r.ariaEl=r.eCell.querySelector("[role=columnheader]")||r.eCell,r.colsSpanning=i,r.beans=n,r.printLayout=n.gridOptionsWrapper.getDomLayout()===ht.DOM_LAYOUT_PRINT,r}return _s(o,t),o.prototype.setColsSpanning=function(t){this.colsSpanning=t,this.onLeftChanged()},o.prototype.getColumnOrGroup=function(){return this.beans.gridOptionsWrapper.isEnableRtl()&&this.colsSpanning?d(this.colsSpanning):this.columnOrGroup},o.prototype.postConstruct=function(){this.addManagedListener(this.columnOrGroup,yt.EVENT_LEFT_CHANGED,this.onLeftChanged.bind(this)),this.setLeftFirstTime(),this.printLayout&&this.addManagedListener(this.eventService,Wt.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED,this.onLeftChanged.bind(this))},o.prototype.setLeftFirstTime=function(){var t=this.beans.gridOptionsWrapper.isSuppressColumnMoveAnimation(),o=e(this.columnOrGroup.getOldLeft());this.beans.columnAnimationService.isActive()&&o&&!t?this.animateInLeft():this.onLeftChanged()},o.prototype.animateInLeft=function(){var t=this,e=this.getColumnOrGroup().getLeft(),o=this.getColumnOrGroup().getOldLeft();this.setLeft(o),this.actualLeft=e,this.beans.columnAnimationService.executeNextVMTurn((function(){t.actualLeft===e&&t.setLeft(e)}))},o.prototype.onLeftChanged=function(){var t=this.getColumnOrGroup(),e=t.getLeft();this.actualLeft=this.modifyLeftForPrintLayout(t,e),this.setLeft(this.actualLeft)},o.prototype.modifyLeftForPrintLayout=function(t,e){if(!this.printLayout)return e;if(t.getPinned()===ht.PINNED_LEFT)return e;var o=this.beans.columnController.getDisplayedColumnsLeftWidth();return t.getPinned()===ht.PINNED_RIGHT?o+this.beans.columnController.getBodyContainerWidth()+e:o+e},o.prototype.setLeft=function(t){var o;if(e(t)&&(this.eCell.style.left=t+"px"),this.columnOrGroup instanceof yt)o=this.columnOrGroup;else{var n=this.columnOrGroup.getLeafColumns();if(!n.length)return;n.length>1&&Yo(this.ariaEl,n.length),o=n[0]}var i=this.beans.columnController.getAriaColumnIndex(o);Ko(this.ariaEl,i)},Fs([et],o.prototype,"postConstruct",null),o}(Mt),Ls=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Is=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Gs=function(t){function e(e,o){var n=t.call(this,o)||this;return n.labelSeparator="",n.labelAlignment="left",n.label="",n.config=e||{},n}return Ls(e,t),e.prototype.postConstruct=function(){Me(this.getGui(),"ag-labeled"),Me(this.eLabel,"ag-label");var t=this.config,e=t.labelSeparator,o=t.label,n=t.labelWidth,i=t.labelAlignment;null!=e&&this.setLabelSeparator(e),null!=o&&this.setLabel(o),null!=n&&this.setLabelWidth(n),this.setLabelAlignment(i||this.labelAlignment),this.refreshLabel()},e.prototype.refreshLabel=function(){Je(this.eLabel),"string"==typeof this.label?this.eLabel.innerText=this.label+this.labelSeparator:this.label&&this.eLabel.appendChild(this.label),""===this.label?(Me(this.eLabel,"ag-hidden"),this.eLabel.setAttribute("role","presentation")):(xe(this.eLabel,"ag-hidden"),this.eLabel.removeAttribute("role"))},e.prototype.setLabelSeparator=function(t){return this.labelSeparator===t||(this.labelSeparator=t,null!=this.label&&this.refreshLabel()),this},e.prototype.getLabelId=function(){return this.eLabel.id=this.eLabel.id||"ag-"+this.getCompId()+"-label",this.eLabel.id},e.prototype.getLabel=function(){return this.label},e.prototype.setLabel=function(t){return this.label===t||(this.label=t,this.refreshLabel()),this},e.prototype.setLabelAlignment=function(t){var e=this.getGui();return Ve(e,"ag-label-align-left","left"===t),Ve(e,"ag-label-align-right","right"===t),Ve(e,"ag-label-align-top","top"===t),this},e.prototype.setLabelWidth=function(t){return null==this.label||ho(this.eLabel,t),this},Is([et],e.prototype,"postConstruct",null),e}(xn),Ms=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),xs=function(t){function e(e,o,n){var i=t.call(this,e,o)||this;return i.className=n,i.disabled=!1,i}return Ms(e,t),e.prototype.postConstruct=function(){t.prototype.postConstruct.call(this),this.className&&Me(this.getGui(),this.className)},e.prototype.onValueChange=function(t){var o=this;return this.addManagedListener(this,e.EVENT_CHANGED,(function(){return t(o.getValue())})),this},e.prototype.getWidth=function(){return this.getGui().clientWidth},e.prototype.setWidth=function(t){return fo(this.getGui(),t),this},e.prototype.getPreviousValue=function(){return this.previousValue},e.prototype.getValue=function(){return this.value},e.prototype.setValue=function(t,o){return this.value===t||(this.previousValue=this.value,this.value=t,o||this.dispatchEvent({type:e.EVENT_CHANGED})),this},e.prototype.setDisabled=function(t){t=!!t;var e=this.getGui();return je(e,t),Ve(e,"ag-disabled",t),this.disabled=t,this},e.prototype.isDisabled=function(){return!!this.disabled},e.EVENT_CHANGED="valueChange",e}(Gs),Vs=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Hs=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Ws=function(t){function o(e,o,n,i){void 0===n&&(n="text"),void 0===i&&(i="input");var r=t.call(this,e,'\n <div role="presentation">\n <div ref="eLabel" class="ag-input-field-label"></div>\n <div ref="eWrapper" class="ag-wrapper ag-input-wrapper" role="presentation">\n <'+i+' ref="eInput" class="ag-input-field-input"></'+i+">\n </div>\n </div>",o)||this;return r.inputType=n,r.displayFieldTag=i,r}return Vs(o,t),o.prototype.postConstruct=function(){t.prototype.postConstruct.call(this),this.setInputType(),Me(this.eLabel,this.className+"-label"),Me(this.eWrapper,this.className+"-input-wrapper"),Me(this.eInput,this.className+"-input"),Me(this.getGui(),"ag-input-field"),this.eInput.id=this.eInput.id||"ag-"+this.getCompId()+"-input";var e=this.config,o=e.width,n=e.value;null!=o&&this.setWidth(o),null!=n&&this.setValue(n),this.addInputListeners()},o.prototype.refreshLabel=function(){e(this.getLabel())?Go(this.eInput,this.getLabelId()):this.eInput.removeAttribute("aria-labelledby"),t.prototype.refreshLabel.call(this)},o.prototype.addInputListeners=function(){var t=this;this.addManagedListener(this.eInput,"input",(function(e){return t.setValue(e.target.value)}))},o.prototype.setInputType=function(){"input"===this.displayFieldTag&&this.eInput.setAttribute("type",this.inputType)},o.prototype.getInputElement=function(){return this.eInput},o.prototype.setInputWidth=function(t){return ho(this.eWrapper,t),this},o.prototype.setInputName=function(t){return this.getInputElement().setAttribute("name",t),this},o.prototype.getFocusableElement=function(){return this.eInput},o.prototype.setMaxLength=function(t){return this.eInput.maxLength=t,this},o.prototype.setInputPlaceholder=function(t){return Ro(this.eInput,"placeholder",t),this},o.prototype.setInputAriaLabel=function(t){return Io(this.eInput,t),this},o.prototype.setDisabled=function(e){return je(this.eInput,e),t.prototype.setDisabled.call(this,e)},Hs([Wn("eLabel")],o.prototype,"eLabel",void 0),Hs([Wn("eWrapper")],o.prototype,"eWrapper",void 0),Hs([Wn("eInput")],o.prototype,"eInput",void 0),o}(xs),ks=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Bs=function(t){function e(e,o,n){void 0===o&&(o="ag-checkbox"),void 0===n&&(n="checkbox");var i=t.call(this,e,o,n)||this;return i.labelAlignment="right",i.selected=!1,i.readOnly=!1,i.passive=!1,i}return ks(e,t),e.prototype.addInputListeners=function(){this.addManagedListener(this.eInput,"click",this.onCheckboxClick.bind(this)),this.addManagedListener(this.eLabel,"click",this.toggle.bind(this))},e.prototype.getNextValue=function(){return void 0===this.selected||!this.selected},e.prototype.setPassive=function(t){this.passive=t},e.prototype.isReadOnly=function(){return this.readOnly},e.prototype.setReadOnly=function(t){Ve(this.eWrapper,"ag-disabled",t),this.eInput.disabled=t,this.readOnly=t},e.prototype.setDisabled=function(e){return Ve(this.eWrapper,"ag-disabled",e),t.prototype.setDisabled.call(this,e)},e.prototype.toggle=function(){var t=this.isSelected(),e=this.getNextValue();this.passive?this.dispatchChange(e,t):this.setValue(e)},e.prototype.getValue=function(){return this.isSelected()},e.prototype.setValue=function(t,e){return this.refreshSelectedClass(t),this.setSelected(t,e),this},e.prototype.setName=function(t){return this.getInputElement().name=t,this},e.prototype.isSelected=function(){return this.selected},e.prototype.setSelected=function(t,e){this.isSelected()!==t&&(this.previousValue=this.isSelected(),t=this.selected="boolean"==typeof t?t:void 0,this.eInput.checked=t,this.eInput.indeterminate=void 0===t,e||this.dispatchChange(this.selected,this.previousValue))},e.prototype.dispatchChange=function(t,o,n){this.dispatchEvent({type:e.EVENT_CHANGED,selected:t,previousValue:o,event:n});var i=this.getInputElement(),r={type:Wt.EVENT_CHECKBOX_CHANGED,id:i.id,name:i.name,selected:t,previousValue:o};this.eventService.dispatchEvent(r)},e.prototype.onCheckboxClick=function(t){if(!this.passive){var e=this.isSelected(),o=this.selected=t.target.checked;this.refreshSelectedClass(o),this.dispatchChange(o,e,t)}},e.prototype.refreshSelectedClass=function(t){Ve(this.eWrapper,"ag-checked",!0===t),Ve(this.eWrapper,"ag-indeterminate",null==t)},e}(Ws),js=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Us=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},zs=function(t){function e(e,o){var n=t.call(this)||this;n.cbSelectAllVisible=!1,n.processingEventFromCheckbox=!1,n.cbSelectAll=e,n.column=o;var i=o.getColDef();return n.filteredOnly=!!i&&!!i.headerCheckboxSelectionFilteredOnly,n}return js(e,t),e.prototype.postConstruct=function(){this.showOrHideSelectAll(),this.addManagedListener(this.eventService,Wt.EVENT_NEW_COLUMNS_LOADED,this.showOrHideSelectAll.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_DISPLAYED_COLUMNS_CHANGED,this.showOrHideSelectAll.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_SELECTION_CHANGED,this.onSelectionChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_MODEL_UPDATED,this.onModelChanged.bind(this)),this.addManagedListener(this.cbSelectAll,Bs.EVENT_CHANGED,this.onCbSelectAll.bind(this)),this.cbSelectAll.getInputElement().setAttribute("tabindex","-1"),this.refreshSelectAllLabel()},e.prototype.showOrHideSelectAll=function(){this.cbSelectAllVisible=this.isCheckboxSelection(),this.cbSelectAll.setDisplayed(this.cbSelectAllVisible),this.cbSelectAllVisible&&(this.checkRightRowModelType(),this.updateStateOfCheckbox()),this.refreshHeaderAriaDescribedBy(this.cbSelectAllVisible)},e.prototype.refreshHeaderAriaDescribedBy=function(t){var e=this.cbSelectAll.getParentComponent(),o=e&&e.getGui();if(o&&eo(o)){var n="";o&&(n=Lo(o));var i=this.cbSelectAll.getInputElement().id,r=-1!==n.indexOf(i);t?r||Mo(o,i+" "+n.trim()):r&&Mo(o,n.trim().split(" ").filter((function(t){return t===i})).join(" "))}},e.prototype.onModelChanged=function(){this.cbSelectAllVisible&&this.updateStateOfCheckbox()},e.prototype.onSelectionChanged=function(){this.cbSelectAllVisible&&this.updateStateOfCheckbox()},e.prototype.getNextCheckboxState=function(t){return(0!==t.selected||0!==t.notSelected)&&(t.selected>0&&t.notSelected>0?null:t.selected>0)},e.prototype.updateStateOfCheckbox=function(){if(!this.processingEventFromCheckbox){this.processingEventFromCheckbox=!0;var t=this.getSelectionCount(),e=this.getNextCheckboxState(t);this.cbSelectAll.setValue(e),this.refreshSelectAllLabel(),this.processingEventFromCheckbox=!1}},e.prototype.refreshSelectAllLabel=function(){var t=this.gridOptionsWrapper.getLocaleTextFunc(),e=this.cbSelectAll.getValue()?t("ariaChecked","checked"):t("ariaUnchecked","unchecked"),o=t("ariaRowSelectAll","Press Space to toggle all rows selection");this.cbSelectAll.setInputAriaLabel(o+" ("+e+")")},e.prototype.getSelectionCount=function(){var t=this,e=0,o=0,n=function(n){t.gridOptionsWrapper.isGroupSelectsChildren()&&n.group||(n.isSelected()?e++:n.selectable&&o++)};return this.filteredOnly?this.gridApi.forEachNodeAfterFilter(n):this.gridApi.forEachNode(n),{notSelected:o,selected:e}},e.prototype.checkRightRowModelType=function(){var t=this.rowModel.getType();t===ht.ROW_MODEL_TYPE_CLIENT_SIDE||console.warn("AG Grid: selectAllCheckbox is only available if using normal row model, you are using "+t)},e.prototype.onCbSelectAll=function(){this.processingEventFromCheckbox||this.cbSelectAllVisible&&(this.cbSelectAll.getValue()?this.selectionController.selectAllRowNodes(this.filteredOnly):this.selectionController.deselectAllRowNodes(this.filteredOnly))},e.prototype.isCheckboxSelection=function(){var t=this.column.getColDef().headerCheckboxSelection;"function"==typeof t&&(t=t({column:this.column,colDef:this.column.getColDef(),columnApi:this.columnApi,api:this.gridApi}));return!!t&&(this.gridOptionsWrapper.isRowModelServerSide()?(console.warn("headerCheckboxSelection is not supported for Server Side Row Model"),!1):this.gridOptionsWrapper.isRowModelInfinite()?(console.warn("headerCheckboxSelection is not supported for Infinite Row Model"),!1):!this.gridOptionsWrapper.isRowModelViewport()||(console.warn("headerCheckboxSelection is not supported for Viewport Row Model"),!1))},Us([it("gridApi")],e.prototype,"gridApi",void 0),Us([it("columnApi")],e.prototype,"columnApi",void 0),Us([it("rowModel")],e.prototype,"rowModel",void 0),Us([it("selectionController")],e.prototype,"selectionController",void 0),Us([et],e.prototype,"postConstruct",null),e}(Mt),Ks=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Ys=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Ks(e,t),e.prototype.shouldStopEventPropagation=function(t){var e=this.focusController.getFocusedHeader(),o=e.headerRowIndex,n=e.column;return yn(this.gridOptionsWrapper,t,o,n)},e.prototype.getColumn=function(){return this.column},e.prototype.getPinned=function(){return this.pinned},e}(Zn),qs=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Xs=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Qs=function(t){function e(o,n){var i=t.call(this,e.TEMPLATE)||this;return i.headerCompVersion=0,i.refreshFunctions=[],i.column=o,i.pinned=n,i}return qs(e,t),e.prototype.postConstruct=function(){t.prototype.postConstruct.call(this),this.colDefVersion=this.columnController.getColDefVersion(),this.updateState(),this.setupWidth(),this.setupMovingCss(),this.setupTooltip(),this.setupResize(),this.setupMenuClass(),this.setupSortableClass(),this.addColumnHoverListener(),this.addActiveHeaderMouseListeners(),this.createManagedBean(new Ts([this.column],this.getGui())),this.addManagedListener(this.column,yt.EVENT_FILTER_ACTIVE_CHANGED,this.onFilterChanged.bind(this)),this.onFilterChanged(),this.createManagedBean(new zs(this.cbSelectAll,this.column)),this.cbSelectAll.setParentComponent(this),this.createManagedBean(new Ns(this.column,this.getGui(),this.beans)),this.addAttributes(),bs.addHeaderClassesFromColDef(this.column.getColDef(),this.getGui(),this.gridOptionsWrapper,this.column,null),this.addManagedListener(this.eventService,Wt.EVENT_NEW_COLUMNS_LOADED,this.onNewColumnsLoaded.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_VALUE_CHANGED,this.onColumnValueChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_ROW_GROUP_CHANGED,this.onColumnRowGroupChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_PIVOT_CHANGED,this.onColumnPivotChanged.bind(this)),this.appendHeaderComp()},e.prototype.onColumnRowGroupChanged=function(){this.checkDisplayName()},e.prototype.onColumnPivotChanged=function(){this.checkDisplayName()},e.prototype.onColumnValueChanged=function(){this.checkDisplayName()},e.prototype.checkDisplayName=function(){this.displayName!==this.calculateDisplayName()&&this.refresh()},e.prototype.updateState=function(){var t=this.column.getColDef();this.sortable=t.sortable,this.displayName=this.calculateDisplayName(),this.draggable=this.workOutDraggable()},e.prototype.calculateDisplayName=function(){return this.columnController.getDisplayNameForColumn(this.column,"header",!0)},e.prototype.onNewColumnsLoaded=function(){var t=this.columnController.getColDefVersion();t!=this.colDefVersion&&(this.colDefVersion=t,this.refresh())},e.prototype.refresh=function(){this.updateState();var t=this.column.getColDef();if(!(this.colDefHeaderComponent!=t.headerComponent||this.colDefHeaderComponentFramework!=t.headerComponentFramework)&&this.attemptHeaderCompRefresh()){var e=this.draggable&&!this.moveDragSource,o=!this.draggable&&this.moveDragSource;(e||o)&&this.attachDraggingToHeaderComp()}else this.appendHeaderComp();this.refreshFunctions.forEach((function(t){return t()}))},e.prototype.destroyHeaderComp=function(){this.headerComp&&(this.getGui().removeChild(this.headerCompGui),this.headerComp=this.destroyBean(this.headerComp),this.headerCompGui=void 0),this.removeMoveDragSource()},e.prototype.removeMoveDragSource=function(){this.moveDragSource&&(this.dragAndDropService.removeDragSource(this.moveDragSource),this.moveDragSource=void 0)},e.prototype.attemptHeaderCompRefresh=function(){if(!this.headerComp)return!0;if(!this.headerComp.refresh)return!1;var t=this.createParams(),e=this.userComponentFactory.createFinalParams(this.getComponentHolder(),"headerComponent",t);return this.headerComp.refresh(e)},e.prototype.addActiveHeaderMouseListeners=function(){var t=this,e=function(e){return t.setActiveHeader("mouseenter"===e.type)};this.addManagedListener(this.getGui(),"mouseenter",e),this.addManagedListener(this.getGui(),"mouseleave",e)},e.prototype.setActiveHeader=function(t){Ve(this.getGui(),"ag-header-active",t)},e.prototype.onFocusIn=function(t){if(!this.getGui().contains(t.relatedTarget)){var e=this.getParentComponent();this.focusController.setFocusedHeader(e.getRowIndex(),this.getColumn())}this.setActiveHeader(!0)},e.prototype.onFocusOut=function(t){this.getGui().contains(t.relatedTarget)||this.setActiveHeader(!1)},e.prototype.handleKeyDown=function(t){var e=this.headerComp;if(e){if(t.keyCode===jn.SPACE){var o=this.cbSelectAll;o.isDisplayed()&&!o.getGui().contains(document.activeElement)&&(t.preventDefault(),o.setValue(!o.getValue()))}if(t.keyCode===jn.ENTER)if(t.ctrlKey||t.metaKey)this.menuEnabled&&e.showMenu&&(t.preventDefault(),e.showMenu());else if(this.sortable){var n=t.shiftKey;this.sortController.progressSort(this.column,n,"uiColumnSorted")}}},e.prototype.onTabKeyDown=function(){},e.prototype.getComponentHolder=function(){return this.column.getColDef()},e.prototype.addColumnHoverListener=function(){this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_HOVER_CHANGED,this.onColumnHover.bind(this)),this.onColumnHover()},e.prototype.onColumnHover=function(){var t=this.columnHoverService.isHovered(this.column);Ve(this.getGui(),"ag-column-hover",t)},e.prototype.setupSortableClass=function(){var t=this,e=this.getGui(),o=function(){Ve(e,"ag-header-cell-sortable",!!t.sortable)},n=function(){t.sortable?qo(e,Fo(t.column)):Xo(e)};o(),n(),this.refreshFunctions.push(o),this.refreshFunctions.push(n),this.addManagedListener(this.column,yt.EVENT_SORT_CHANGED,n.bind(this))},e.prototype.onFilterChanged=function(){var t=this.column.isFilterActive();Ve(this.getGui(),"ag-header-cell-filtered",t)},e.prototype.appendHeaderComp=function(){this.headerCompVersion++;var t=this.column.getColDef();this.colDefHeaderComponent=t.headerComponent,this.colDefHeaderComponentFramework=t.headerComponentFramework;var e=this.createParams(),o=this.afterHeaderCompCreated.bind(this,this.headerCompVersion);this.userComponentFactory.newHeaderComponent(e).then(o)},e.prototype.createParams=function(){var t=this,e=this.column.getColDef();return this.menuEnabled=this.menuFactory.isMenuEnabled(this.column)&&!e.suppressMenu,{column:this.column,displayName:this.displayName,enableSorting:e.sortable,enableMenu:this.menuEnabled,showColumnMenu:function(e){t.gridApi.showColumnMenuAfterButtonClick(t.column,e)},progressSort:function(e){t.sortController.progressSort(t.column,!!e,"uiColumnSorted")},setSort:function(e,o){t.sortController.setSortForColumn(t.column,e,!!o,"uiColumnSorted")},api:this.gridApi,columnApi:this.columnApi,context:this.gridOptionsWrapper.getContext(),eGridHeader:this.getGui()}},e.prototype.afterHeaderCompCreated=function(t,e){t==this.headerCompVersion&&this.isAlive()?(this.destroyHeaderComp(),this.headerComp=e,this.headerCompGui=e.getGui(),this.getGui().appendChild(this.headerCompGui),this.attachDraggingToHeaderComp()):this.destroyBean(e)},e.prototype.onColumnMovingChanged=function(){this.column.isMoving()?Me(this.getGui(),"ag-header-cell-moving"):xe(this.getGui(),"ag-header-cell-moving")},e.prototype.workOutDraggable=function(){var t=this.column.getColDef();return!!(!this.gridOptionsWrapper.isSuppressMovableColumns()&&!t.suppressMovable&&!t.lockPosition)||!!t.enableRowGroup||!!t.enablePivot},e.prototype.attachDraggingToHeaderComp=function(){var t=this;this.removeMoveDragSource(),this.draggable&&(this.moveDragSource={type:$r.HeaderCell,eElement:this.headerCompGui,defaultIconName:ns.ICON_HIDE,getDragItem:function(){return t.createDragItem()},dragItemName:this.displayName,onDragStarted:function(){return t.column.setMoving(!0,"uiColumnMoved")},onDragStopped:function(){return t.column.setMoving(!1,"uiColumnMoved")}},this.dragAndDropService.addDragSource(this.moveDragSource,!0))},e.prototype.createDragItem=function(){var t={};return t[this.column.getId()]=this.column.isVisible(),{columns:[this.column],visibleState:t}},e.prototype.setupResize=function(){var t,e,o=this,n=this.getComponentHolder(),i=[],r=function(){i.forEach((function(t){return t()})),i.length=0},s=function(){var s=o.column.isResizable(),a=!o.gridOptionsWrapper.isSuppressAutoSize()&&!n.suppressAutoSize;(s!==t||a!==e)&&(t=s,e=a,r(),function(){if(ke(o.eResize,t),t){var n=o.horizontalResizeService.addResizeBar({eResizeBar:o.eResize,onResizeStart:o.onResizeStart.bind(o),onResizing:o.onResizing.bind(o,!1),onResizeEnd:o.onResizing.bind(o,!0)});if(i.push(n),e){var r=o.gridOptionsWrapper.isSkipHeaderOnAutoSize(),s=function(){o.columnController.autoSizeColumn(o.column,r,"uiColumnResized")};o.eResize.addEventListener("dblclick",s);var a=new ci(o.eResize);a.addEventListener(ci.EVENT_DOUBLE_TAP,s),o.addDestroyFunc((function(){o.eResize.removeEventListener("dblclick",s),a.removeEventListener(ci.EVENT_DOUBLE_TAP,s),a.destroy()}))}}}())};s(),this.addDestroyFunc(r),this.refreshFunctions.push(s)},e.prototype.onResizing=function(t,e){var o=this.normaliseResizeAmount(e),n=[{key:this.column,newWidth:this.resizeStartWidth+o}];this.columnController.setColumnWidths(n,this.resizeWithShiftKey,t,"uiColumnDragged"),t&&xe(this.getGui(),"ag-column-resizing")},e.prototype.onResizeStart=function(t){this.resizeStartWidth=this.column.getActualWidth(),this.resizeWithShiftKey=t,Me(this.getGui(),"ag-column-resizing")},e.prototype.getTooltipParams=function(){var e=t.prototype.getTooltipParams.call(this);return e.location="header",e.colDef=this.column.getColDef(),e},e.prototype.setupTooltip=function(){var t=this,e=function(){var e=t.column.getColDef().headerTooltip;t.setTooltip(e)};e(),this.refreshFunctions.push(e)},e.prototype.setupMovingCss=function(){this.addManagedListener(this.column,yt.EVENT_MOVING_CHANGED,this.onColumnMovingChanged.bind(this)),this.onColumnMovingChanged()},e.prototype.addAttributes=function(){this.getGui().setAttribute("col-id",this.column.getColId())},e.prototype.setupWidth=function(){this.addManagedListener(this.column,yt.EVENT_WIDTH_CHANGED,this.onColumnWidthChanged.bind(this)),this.onColumnWidthChanged()},e.prototype.setupMenuClass=function(){this.addManagedListener(this.column,yt.EVENT_MENU_VISIBLE_CHANGED,this.onMenuVisible.bind(this))},e.prototype.onMenuVisible=function(){this.addOrRemoveCssClass("ag-column-menu-visible",this.column.isMenuVisible())},e.prototype.onColumnWidthChanged=function(){this.getGui().style.width=this.column.getActualWidth()+"px"},e.prototype.normaliseResizeAmount=function(t){var e=t;return this.gridOptionsWrapper.isEnableRtl()?this.pinned!==ht.PINNED_LEFT&&(e*=-1):this.pinned===ht.PINNED_RIGHT&&(e*=-1),e},e.TEMPLATE='<div class="ag-header-cell" role="columnheader" unselectable="on" tabindex="-1">\n <div ref="eResize" class="ag-header-cell-resize" role="presentation"></div>\n <ag-checkbox ref="cbSelectAll" class="ag-header-select-all" role="presentation"></ag-checkbox>\n </div>',Xs([it("dragAndDropService")],e.prototype,"dragAndDropService",void 0),Xs([it("columnController")],e.prototype,"columnController",void 0),Xs([it("horizontalResizeService")],e.prototype,"horizontalResizeService",void 0),Xs([it("menuFactory")],e.prototype,"menuFactory",void 0),Xs([it("gridApi")],e.prototype,"gridApi",void 0),Xs([it("columnApi")],e.prototype,"columnApi",void 0),Xs([it("sortController")],e.prototype,"sortController",void 0),Xs([it("userComponentFactory")],e.prototype,"userComponentFactory",void 0),Xs([it("columnHoverService")],e.prototype,"columnHoverService",void 0),Xs([it("beans")],e.prototype,"beans",void 0),Xs([Wn("eResize")],e.prototype,"eResize",void 0),Xs([Wn("cbSelectAll")],e.prototype,"cbSelectAll",void 0),Xs([ot],e.prototype,"destroyHeaderComp",null),e}(Ys),$s=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Zs=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Js=function(t){function e(o,n){var i=t.call(this,e.TEMPLATE)||this;return i.removeChildListenersFuncs=[],i.column=o,i.pinned=n,i}return $s(e,t),e.prototype.postConstruct=function(){t.prototype.postConstruct.call(this),bs.addHeaderClassesFromColDef(this.getComponentHolder(),this.getGui(),this.gridOptionsWrapper,null,this.column);var e=this.columnController.getDisplayNameForColumnGroup(this.column,"header");this.appendHeaderGroupComp(e),this.setupResize(),this.addClasses(),this.setupWidth(),this.addAttributes(),this.setupMovingCss(),this.setupTooltip(),this.setupExpandable(),this.createManagedBean(new Ts(this.column.getOriginalColumnGroup().getLeafColumns(),this.getGui())),this.createManagedBean(new Ns(this.column,this.getGui(),this.beans))},e.prototype.onFocusIn=function(t){if(!this.getGui().contains(t.relatedTarget)){var e=this.getParentComponent();this.beans.focusController.setFocusedHeader(e.getRowIndex(),this.getColumn())}},e.prototype.handleKeyDown=function(t){var e=document.activeElement===this.getGui();if(this.expandable&&e&&t.keyCode===jn.ENTER){var o=this.getColumn(),n=!o.isExpanded();this.columnController.setColumnGroupOpened(o.getOriginalColumnGroup(),n,"uiColumnExpanded")}},e.prototype.onTabKeyDown=function(){},e.prototype.setupExpandable=function(){var t=this.getColumn().getOriginalColumnGroup();this.refreshExpanded(),this.addManagedListener(t,Ct.EVENT_EXPANDABLE_CHANGED,this.refreshExpanded.bind(this)),this.addManagedListener(t,Ct.EVENT_EXPANDED_CHANGED,this.refreshExpanded.bind(this))},e.prototype.refreshExpanded=function(){var t=this.getColumn(),e=this.getGui(),o=t.isExpandable(),n=t.isExpanded();this.expandable=o,o?Vo(e,n):e.removeAttribute("aria-expanded")},e.prototype.setupMovingCss=function(){var t=this;this.column.getOriginalColumnGroup().getLeafColumns().forEach((function(e){t.addManagedListener(e,yt.EVENT_MOVING_CHANGED,t.onColumnMovingChanged.bind(t))})),this.onColumnMovingChanged()},e.prototype.getComponentHolder=function(){return this.column.getColGroupDef()},e.prototype.getTooltipParams=function(){var e=t.prototype.getTooltipParams.call(this);return e.location="headerGroup",e.colDef=this.getComponentHolder(),e.column=this.getColumn(),e},e.prototype.setupTooltip=function(){var t=this.getComponentHolder(),e=t&&t.headerTooltip;null!=e&&this.setTooltip(e)},e.prototype.onColumnMovingChanged=function(){Ve(this.getGui(),"ag-header-cell-moving",this.column.isMoving())},e.prototype.addAttributes=function(){this.getGui().setAttribute("col-id",this.column.getUniqueId())},e.prototype.appendHeaderGroupComp=function(t){var e=this,o={displayName:t,columnGroup:this.column,setExpanded:function(t){e.columnController.setColumnGroupOpened(e.column.getOriginalColumnGroup(),t,"gridInitializing")},api:this.gridApi,columnApi:this.columnApi,context:this.gridOptionsWrapper.getContext()};if(!t){for(var n=this.column,i=n.getLeafColumns();n.getParent()&&n.getParent().getLeafColumns().length===i.length;)n=n.getParent();var r=n.getColGroupDef();r&&(t=r.headerName),t||(t=i?this.columnController.getDisplayNameForColumn(i[0],"header",!0):"")}var s=this.afterHeaderCompCreated.bind(this,t);this.userComponentFactory.newHeaderGroupComponent(o).then(s)},e.prototype.afterHeaderCompCreated=function(t,e){var o=this;this.getGui().appendChild(e.getGui()),this.addDestroyFunc((function(){o.getContext().destroyBean(e)})),this.setupMove(e.getGui(),t)},e.prototype.addClasses=function(){var t=this.column.isPadding()?"no":"with";this.addCssClass("ag-header-group-cell-"+t+"-group")},e.prototype.setupMove=function(t,e){var o=this;if(t&&!this.isSuppressMoving()){var n=this.column.getOriginalColumnGroup().getLeafColumns(),i={type:$r.HeaderCell,eElement:t,defaultIconName:ns.ICON_HIDE,dragItemName:e,getDragItem:this.getDragItemForGroup.bind(this),onDragStarted:function(){return n.forEach((function(t){return t.setMoving(!0,"uiColumnDragged")}))},onDragStopped:function(){return n.forEach((function(t){return t.setMoving(!1,"uiColumnDragged")}))}};this.dragAndDropService.addDragSource(i,!0),this.addDestroyFunc((function(){return o.dragAndDropService.removeDragSource(i)}))}},e.prototype.getDragItemForGroup=function(){var t=this.column.getOriginalColumnGroup().getLeafColumns(),e={};t.forEach((function(t){return e[t.getId()]=t.isVisible()}));var o=[];return this.columnController.getAllDisplayedColumns().forEach((function(e){t.indexOf(e)>=0&&(o.push(e),g(t,e))})),t.forEach((function(t){return o.push(t)})),{columns:o,visibleState:e}},e.prototype.isSuppressMoving=function(){var t=!1;return this.column.getLeafColumns().forEach((function(e){(e.getColDef().suppressMovable||e.getColDef().lockPosition)&&(t=!0)})),t||this.gridOptionsWrapper.isSuppressMovableColumns()},e.prototype.setupWidth=function(){this.addListenersToChildrenColumns(),this.addManagedListener(this.column,mt.EVENT_DISPLAYED_CHILDREN_CHANGED,this.onDisplayedChildrenChanged.bind(this)),this.onWidthChanged(),this.addDestroyFunc(this.removeListenersOnChildrenColumns.bind(this))},e.prototype.onDisplayedChildrenChanged=function(){this.addListenersToChildrenColumns(),this.onWidthChanged()},e.prototype.addListenersToChildrenColumns=function(){var t=this;this.removeListenersOnChildrenColumns();var e=this.onWidthChanged.bind(this);this.column.getLeafColumns().forEach((function(o){o.addEventListener(yt.EVENT_WIDTH_CHANGED,e),o.addEventListener(yt.EVENT_VISIBLE_CHANGED,e),t.removeChildListenersFuncs.push((function(){o.removeEventListener(yt.EVENT_WIDTH_CHANGED,e),o.removeEventListener(yt.EVENT_VISIBLE_CHANGED,e)}))}))},e.prototype.removeListenersOnChildrenColumns=function(){this.removeChildListenersFuncs.forEach((function(t){return t()})),this.removeChildListenersFuncs=[]},e.prototype.onWidthChanged=function(){this.getGui().style.width=this.column.getActualWidth()+"px"},e.prototype.setupResize=function(){var t=this;if(this.eHeaderCellResize=this.getRefElement("agResize"),this.column.isResizable()){var e=this.horizontalResizeService.addResizeBar({eResizeBar:this.eHeaderCellResize,onResizeStart:this.onResizeStart.bind(this),onResizing:this.onResizing.bind(this,!1),onResizeEnd:this.onResizing.bind(this,!0)});if(this.addDestroyFunc(e),!this.gridOptionsWrapper.isSuppressAutoSize()){var o=this.gridOptionsWrapper.isSkipHeaderOnAutoSize();this.eHeaderCellResize.addEventListener("dblclick",(function(e){var n=[];t.column.getDisplayedLeafColumns().forEach((function(t){t.getColDef().suppressAutoSize||n.push(t.getColId())})),n.length>0&&t.columnController.autoSizeColumns(n,o,"uiColumnResized")}))}}else to(this.eHeaderCellResize)},e.prototype.onResizeStart=function(t){var e=this,o=this.column.getDisplayedLeafColumns();this.resizeCols=o.filter((function(t){return t.isResizable()})),this.resizeStartWidth=0,this.resizeCols.forEach((function(t){return e.resizeStartWidth+=t.getActualWidth()})),this.resizeRatios=[],this.resizeCols.forEach((function(t){return e.resizeRatios.push(t.getActualWidth()/e.resizeStartWidth)}));var n=null;if(t&&(n=this.columnController.getDisplayedGroupAfter(this.column)),n){var i=n.getDisplayedLeafColumns();this.resizeTakeFromCols=i.filter((function(t){return t.isResizable()})),this.resizeTakeFromStartWidth=0,this.resizeTakeFromCols.forEach((function(t){return e.resizeTakeFromStartWidth+=t.getActualWidth()})),this.resizeTakeFromRatios=[],this.resizeTakeFromCols.forEach((function(t){return e.resizeTakeFromRatios.push(t.getActualWidth()/e.resizeTakeFromStartWidth)}))}else this.resizeTakeFromCols=null,this.resizeTakeFromStartWidth=null,this.resizeTakeFromRatios=null;Me(this.getGui(),"ag-column-resizing")},e.prototype.onResizing=function(t,e){var o=[],n=this.normaliseDragChange(e);o.push({columns:this.resizeCols,ratios:this.resizeRatios,width:this.resizeStartWidth+n}),this.resizeTakeFromCols&&o.push({columns:this.resizeTakeFromCols,ratios:this.resizeTakeFromRatios,width:this.resizeTakeFromStartWidth-n}),this.columnController.resizeColumnSets(o,t,"uiColumnDragged"),t&&xe(this.getGui(),"ag-column-resizing")},e.prototype.normaliseDragChange=function(t){var e=t;return this.gridOptionsWrapper.isEnableRtl()?this.pinned!==ht.PINNED_LEFT&&(e*=-1):this.pinned===ht.PINNED_RIGHT&&(e*=-1),e},e.TEMPLATE='<div class="ag-header-group-cell" role="columnheader" tabindex="-1">\n <div ref="agResize" class="ag-header-cell-resize" role="presentation"></div>\n </div>',Zs([it("columnController")],e.prototype,"columnController",void 0),Zs([it("horizontalResizeService")],e.prototype,"horizontalResizeService",void 0),Zs([it("dragAndDropService")],e.prototype,"dragAndDropService",void 0),Zs([it("userComponentFactory")],e.prototype,"userComponentFactory",void 0),Zs([it("beans")],e.prototype,"beans",void 0),Zs([it("gridApi")],e.prototype,"gridApi",void 0),Zs([it("columnApi")],e.prototype,"columnApi",void 0),e}(Ys),ta=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),ea=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},oa=function(t){function e(){return t.call(this,'\n <div class="ag-floating-filter-input" role="presentation">\n <ag-input-text-field ref="eFloatingFilterText"></ag-input-text-field>\n </div>')||this}return ta(e,t),e.prototype.destroy=function(){t.prototype.destroy.call(this)},e.prototype.init=function(t){this.params=t;var e=this.columnController.getDisplayNameForColumn(t.column,"header",!0),o=this.gridOptionsWrapper.getLocaleTextFunc();this.eFloatingFilterText.setDisabled(!0).setInputAriaLabel(e+" "+o("ariaFilterInput","Filter Input"))},e.prototype.onParentModelChanged=function(t){var e=this;t?this.params.parentFilterInstance((function(o){if(o.getModelAsString){var n=o.getModelAsString(t);e.eFloatingFilterText.setValue(n)}})):this.eFloatingFilterText.setValue("")},ea([Wn("eFloatingFilterText")],e.prototype,"eFloatingFilterText",void 0),ea([it("columnController")],e.prototype,"columnController",void 0),e}(xn),na=function(){function t(){}return t.getFloatingFilterType=function(t){return this.filterToFloatingFilterMapping[t]},t.filterToFloatingFilterMapping={set:"agSetColumnFloatingFilter",agSetColumnFilter:"agSetColumnFloatingFilter",multi:"agMultiColumnFloatingFilter",agMultiColumnFilter:"agMultiColumnFloatingFilter",number:"agNumberColumnFloatingFilter",agNumberColumnFilter:"agNumberColumnFloatingFilter",date:"agDateColumnFloatingFilter",agDateColumnFilter:"agDateColumnFloatingFilter",text:"agTextColumnFloatingFilter",agTextColumnFilter:"agTextColumnFloatingFilter"},t}(),ia=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),ra=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},sa=function(t){function e(o,n){var i=t.call(this,e.TEMPLATE)||this;return i.column=o,i.pinned=n,i}return ia(e,t),e.prototype.postConstruct=function(){t.prototype.postConstruct.call(this),this.setupFloatingFilter(),this.setupWidth(),this.setupLeftPositioning(),this.setupColumnHover(),this.createManagedBean(new Ts([this.column],this.getGui())),this.addManagedListener(this.eButtonShowMainFilter,"click",this.showParentFilter.bind(this))},e.prototype.onTabKeyDown=function(t){var e=document.activeElement,o=this.getGui();if(!(e===o)){t.preventDefault();var n=this.focusController.findNextFocusableElement(o,null,t.shiftKey);n?n.focus():o.focus()}},e.prototype.handleKeyDown=function(t){var e=document.activeElement,o=this.getGui(),n=e===o;switch(t.keyCode){case jn.UP:case jn.DOWN:n||t.preventDefault();case jn.LEFT:case jn.RIGHT:if(n)return;t.stopPropagation();case jn.ENTER:n&&this.focusController.focusInto(o)&&t.preventDefault();break;case jn.ESCAPE:n||this.getGui().focus()}},e.prototype.onFocusIn=function(t){if(!this.getGui().contains(t.relatedTarget)){var e=this.getParentComponent();this.beans.focusController.setFocusedHeader(e.getRowIndex(),this.getColumn())}},e.prototype.setupFloatingFilter=function(){var t=this,e=this.column.getColDef();e.filter&&e.floatingFilter&&(this.floatingFilterCompPromise=this.getFloatingFilterInstance(),this.floatingFilterCompPromise&&this.floatingFilterCompPromise.then((function(e){e&&(t.setupWithFloatingFilter(e),t.setupSyncWithFilter())})))},e.prototype.setupLeftPositioning=function(){var t=new Ns(this.column,this.getGui(),this.beans);this.createManagedBean(t)},e.prototype.setupSyncWithFilter=function(){var t=this,e=function(e){t.onParentModelChanged(t.currentParentModel(),e)};this.addManagedListener(this.column,yt.EVENT_FILTER_CHANGED,e),this.filterManager.isFilterActive(this.column)&&e(null)},e.prototype.showParentFilter=function(){var t=this.suppressFilterButton?this.eFloatingFilterBody:this.eButtonShowMainFilter;this.menuFactory.showMenuAfterButtonClick(this.column,t,"filterMenuTab",["filterMenuTab"])},e.prototype.setupColumnHover=function(){this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_HOVER_CHANGED,this.onColumnHover.bind(this)),this.onColumnHover()},e.prototype.onColumnHover=function(){Ve(this.getGui(),"ag-column-hover",this.columnHoverService.isHovered(this.column))},e.prototype.setupWidth=function(){this.addManagedListener(this.column,yt.EVENT_WIDTH_CHANGED,this.onColumnWidthChanged.bind(this)),this.onColumnWidthChanged()},e.prototype.onColumnWidthChanged=function(){this.getGui().style.width=this.column.getActualWidth()+"px"},e.prototype.setupWithFloatingFilter=function(t){var e=this,o=function(){e.getContext().destroyBean(t)};if(this.isAlive()){this.addDestroyFunc(o);var n=t.getGui();Ve(this.eFloatingFilterBody,"ag-floating-filter-full-body",this.suppressFilterButton),Ve(this.eFloatingFilterBody,"ag-floating-filter-body",!this.suppressFilterButton),ke(this.eButtonWrapper,!this.suppressFilterButton);var i=cn("filter",this.gridOptionsWrapper,this.column);this.eButtonShowMainFilter.appendChild(i),this.eFloatingFilterBody.appendChild(n),t.afterGuiAttached&&t.afterGuiAttached()}else o()},e.prototype.parentFilterInstance=function(t){var e=this.getFilterComponent();e&&e.then(t)},e.prototype.getFilterComponent=function(t){return void 0===t&&(t=!0),this.filterManager.getFilterComponent(this.column,"NO_UI",t)},e.getDefaultFloatingFilterType=function(t){if(null==t)return null;var e=null;if("string"==typeof t.filter)e=na.getFloatingFilterType(t.filter);else if(t.filterFramework);else if(!0===t.filter){e=ft.isRegistered(pt.SetFilterModule)?"agSetColumnFloatingFilter":"agTextColumnFloatingFilter"}return e},e.prototype.getFloatingFilterInstance=function(){var t=this.column.getColDef(),o=e.getDefaultFloatingFilterType(t),n=this.filterManager.createFilterParams(this.column,t),i=this.userComponentFactory.createFinalParams(t,"filter",n),r={api:this.gridApi,column:this.column,filterParams:i,currentParentModel:this.currentParentModel.bind(this),parentFilterInstance:this.parentFilterInstance.bind(this),showParentFilter:this.showParentFilter.bind(this),onFloatingFilterChanged:this.onFloatingFilterChanged.bind(this),suppressFilterButton:!1};this.suppressFilterButton=!!t.floatingFilterComponentParams&&!!t.floatingFilterComponentParams.suppressFilterButton;var s=this.userComponentFactory.newFloatingFilterComponent(t,r,o);if(!s){var a=this.getFilterComponentPrototype(t);if(a&&a.prototype&&a.prototype.getModelAsString){var l=this.userComponentFactory.createUserComponentFromConcreteClass(oa,r);s=Tn.resolve(l)}}return s},e.prototype.createDynamicParams=function(){return{column:this.column,colDef:this.column.getColDef(),api:this.gridApi,columnApi:this.columnApi}},e.prototype.getFilterComponentPrototype=function(t){var e=this.userComponentFactory.lookupComponentClassDef(t,"filter",this.createDynamicParams());return e?e.component:null},e.prototype.currentParentModel=function(){var t=this.getFilterComponent(!1);return t?t.resolveNow(null,(function(t){return t&&t.getModel()})):null},e.prototype.onParentModelChanged=function(t,e){this.floatingFilterCompPromise&&this.floatingFilterCompPromise.then((function(o){return o&&o.onParentModelChanged(t,e)}))},e.prototype.onFloatingFilterChanged=function(){console.warn("AG Grid: since version 21.x, how floating filters are implemented has changed. Instead of calling params.onFloatingFilterChanged(), get a reference to the main filter via params.parentFilterInstance() and then set a value on the parent filter directly.")},e.TEMPLATE='<div class="ag-header-cell" role="columnheader" tabindex="-1">\n <div class="ag-floating-filter-full-body" ref="eFloatingFilterBody" role="presentation"></div>\n <div class="ag-floating-filter-button ag-hidden" ref="eButtonWrapper" role="presentation">\n <button type="button" aria-label="Open Filter Menu" class="ag-floating-filter-button-button" ref="eButtonShowMainFilter" tabindex="-1"></button>\n </div>\n </div>',ra([it("columnHoverService")],e.prototype,"columnHoverService",void 0),ra([it("userComponentFactory")],e.prototype,"userComponentFactory",void 0),ra([it("gridApi")],e.prototype,"gridApi",void 0),ra([it("columnApi")],e.prototype,"columnApi",void 0),ra([it("filterManager")],e.prototype,"filterManager",void 0),ra([it("menuFactory")],e.prototype,"menuFactory",void 0),ra([it("beans")],e.prototype,"beans",void 0),ra([Wn("eFloatingFilterBody")],e.prototype,"eFloatingFilterBody",void 0),ra([Wn("eButtonWrapper")],e.prototype,"eButtonWrapper",void 0),ra([Wn("eButtonShowMainFilter")],e.prototype,"eButtonShowMainFilter",void 0),e}(Ys),aa=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),la=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s};
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/!function(t){t[t.COLUMN_GROUP=0]="COLUMN_GROUP",t[t.COLUMN=1]="COLUMN",t[t.FLOATING_FILTER=2]="FLOATING_FILTER"}(os||(os={}));var pa,ua=function(t){function e(e,o,n){var i=t.call(this,'<div class="ag-header-row" role="row"></div>')||this;i.headerComps={},i.setRowIndex(e),i.type=o,i.pinned=n;var r=os[o].toLowerCase().replace(/_/g,"-");return i.addCssClass("ag-header-row-"+r),Se()&&(i.getGui().style.transform="translateZ(0)"),i}return aa(e,t),e.prototype.forEachHeaderElement=function(t){var e=this;Object.keys(this.headerComps).forEach((function(o){t(e.headerComps[o])}))},e.prototype.setRowIndex=function(t){this.dept=t,Uo(this.getGui(),t+1)},e.prototype.getRowIndex=function(){return this.dept},e.prototype.getType=function(){return this.type},e.prototype.destroyAllChildComponents=function(){var t=Object.keys(this.headerComps);this.destroyChildComponents(t)},e.prototype.destroyChildComponents=function(t){var e=this;t.forEach((function(t){var o=e.headerComps[t];e.getGui().removeChild(o.getGui()),e.destroyBean(o),delete e.headerComps[t]}))},e.prototype.onRowHeightChanged=function(){var t,e,o=this.columnController.getHeaderRowCount(),n=[],i=0;this.columnController.isPivotMode()?(t=this.gridOptionsWrapper.getPivotGroupHeaderHeight(),e=this.gridOptionsWrapper.getPivotHeaderHeight()):(this.columnController.hasFloatingFilters()&&(o++,i=1),t=this.gridOptionsWrapper.getGroupHeaderHeight(),e=this.gridOptionsWrapper.getHeaderHeight());for(var r=o-(1+i),s=0;s<r;s++)n.push(t);n.push(e);for(s=0;s<i;s++)n.push(this.gridOptionsWrapper.getFloatingFiltersHeight());var a=0;for(s=0;s<this.dept;s++)a+=n[s];this.getGui().style.top=a+"px",this.getGui().style.height=n[this.dept]+"px"},e.prototype.init=function(){this.onRowHeightChanged(),this.onVirtualColumnsChanged(),this.setWidth(),this.addManagedListener(this.gridOptionsWrapper,zr.PROP_HEADER_HEIGHT,this.onRowHeightChanged.bind(this)),this.addManagedListener(this.gridOptionsWrapper,zr.PROP_PIVOT_HEADER_HEIGHT,this.onRowHeightChanged.bind(this)),this.addManagedListener(this.gridOptionsWrapper,zr.PROP_GROUP_HEADER_HEIGHT,this.onRowHeightChanged.bind(this)),this.addManagedListener(this.gridOptionsWrapper,zr.PROP_PIVOT_GROUP_HEADER_HEIGHT,this.onRowHeightChanged.bind(this)),this.addManagedListener(this.gridOptionsWrapper,zr.PROP_FLOATING_FILTERS_HEIGHT,this.onRowHeightChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_VIRTUAL_COLUMNS_CHANGED,this.onVirtualColumnsChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_DISPLAYED_COLUMNS_CHANGED,this.onDisplayedColumnsChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_RESIZED,this.onColumnResized.bind(this))},e.prototype.onColumnResized=function(){this.setWidth()},e.prototype.setWidth=function(){var t=this.getWidthForRow();this.getGui().style.width=t+"px"},e.prototype.getWidthForRow=function(){return this.gridOptionsWrapper.getDomLayout()===ht.DOM_LAYOUT_PRINT?o(this.pinned)?this.columnController.getContainerWidth(ht.PINNED_RIGHT)+this.columnController.getContainerWidth(ht.PINNED_LEFT)+this.columnController.getContainerWidth(null):0:this.columnController.getContainerWidth(this.pinned)},e.prototype.onDisplayedColumnsChanged=function(){this.onVirtualColumnsChanged(),this.setWidth()},e.prototype.getColumnsInViewport=function(){return this.gridOptionsWrapper.getDomLayout()===ht.DOM_LAYOUT_PRINT?this.getColumnsInViewportPrintLayout():this.getColumnsInViewportNormalLayout()},e.prototype.getColumnsInViewportPrintLayout=function(){var t=this;if(null!=this.pinned)return[];var e=[],o=this.getActualDepth();return[ht.PINNED_LEFT,null,ht.PINNED_RIGHT].forEach((function(n){var i=t.columnController.getVirtualHeaderGroupRow(n,o);e=e.concat(i)})),e},e.prototype.getActualDepth=function(){return this.type==os.FLOATING_FILTER?this.dept-1:this.dept},e.prototype.getColumnsInViewportNormalLayout=function(){return this.columnController.getVirtualHeaderGroupRow(this.pinned,this.getActualDepth())},e.prototype.onVirtualColumnsChanged=function(){var t=this,e=Object.keys(this.headerComps),o=[];this.getColumnsInViewport().forEach((function(n){if(!n.isEmptyGroup()){var i=n.getUniqueId(),r=t.getGui(),s=t.headerComps[i];if(s&&s.getColumn()!=n&&(t.destroyChildComponents([i]),g(e,i),s=void 0),s)g(e,i);else{var a=t.createHeaderComp(n);t.headerComps[i]=a,r.appendChild(a.getGui())}o.push(i)}}));if(e.filter((function(e){var o=t.headerComps[e];return!!t.focusController.isHeaderWrapperFocused(o)&&t.columnController.isDisplayed(o.getColumn())})).forEach((function(t){g(e,t),o.push(t)})),this.destroyChildComponents(e),this.gridOptionsWrapper.isEnsureDomOrder()){var n=o.map((function(e){return t.headerComps[e].getGui()}));ao(this.getGui(),n)}},e.prototype.createHeaderComp=function(t){var e;switch(this.type){case os.COLUMN_GROUP:e=new Js(t,this.pinned);break;case os.FLOATING_FILTER:e=new sa(t,this.pinned);break;default:e=new Qs(t,this.pinned)}return this.createBean(e),e.setParentComponent(this),e},e.prototype.getHeaderComps=function(){return this.headerComps},la([it("columnController")],e.prototype,"columnController",void 0),la([it("focusController")],e.prototype,"focusController",void 0),la([ot],e.prototype,"destroyAllChildComponents",null),la([et],e.prototype,"init",null),e}(xn),ca=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},da=function(){function t(t,o){this.needToMoveLeft=!1,this.needToMoveRight=!1,this.pinned=t,this.eContainer=o,this.centerContainer=!e(t)}return t.prototype.registerGridComp=function(t){this.gridPanel=t},t.prototype.init=function(){this.logger=this.loggerFactory.create("MoveColumnController")},t.prototype.getIconName=function(){return this.pinned?ns.ICON_PINNED:ns.ICON_MOVE},t.prototype.onDragEnter=function(t){var e=t.dragItem.columns;if(t.dragSource.type===$r.ToolPanel)this.setColumnsVisible(e,!0,"uiColumnDragged");else{var o=t.dragItem.visibleState,n=(e||[]).filter((function(t){return o[t.getId()]}));this.setColumnsVisible(n,!0,"uiColumnDragged")}this.setColumnsPinned(e,this.pinned,"uiColumnDragged"),this.onDragging(t,!0)},t.prototype.onDragLeave=function(t){if(!this.gridOptionsWrapper.isSuppressDragLeaveHidesColumns()&&!t.fromNudge){var e=t.dragSource.getDragItem().columns;this.setColumnsVisible(e,!1,"uiColumnDragged")}this.ensureIntervalCleared()},t.prototype.setColumnsVisible=function(t,e,o){if(void 0===o&&(o="api"),t){var n=t.filter((function(t){return!t.getColDef().lockVisible}));this.columnController.setColumnsVisible(n,e,o)}},t.prototype.setColumnsPinned=function(t,e,o){if(void 0===o&&(o="api"),t){var n=t.filter((function(t){return!t.getColDef().lockPinned}));this.columnController.setColumnsPinned(n,e,o)}},t.prototype.onDragStop=function(){this.ensureIntervalCleared()},t.prototype.normaliseX=function(t){this.gridOptionsWrapper.isEnableRtl()&&(t=this.eContainer.clientWidth-t);return this.centerContainer&&(t+=this.gridPanel.getCenterViewportScrollLeft()),t},t.prototype.checkCenterForScrolling=function(t){if(this.centerContainer){var e=this.gridPanel.getCenterViewportScrollLeft(),o=e+this.gridPanel.getCenterWidth();this.gridOptionsWrapper.isEnableRtl()?(this.needToMoveRight=t<e+50,this.needToMoveLeft=t>o-50):(this.needToMoveLeft=t<e+50,this.needToMoveRight=t>o-50),this.needToMoveLeft||this.needToMoveRight?this.ensureIntervalStarted():this.ensureIntervalCleared()}},t.prototype.onDragging=function(t,e){var n=this;if(void 0===e&&(e=!1),this.lastDraggingEvent=t,!o(t.hDirection)){var i=this.normaliseX(t.x);e||this.checkCenterForScrolling(i);var r=this.normaliseDirection(t.hDirection),s=t.dragSource.type,a=t.dragSource.getDragItem().columns;a=a.filter((function(t){return!t.getColDef().lockPinned||t.getPinned()==n.pinned})),this.attemptMoveColumns(s,a,r,i,e)}},t.prototype.normaliseDirection=function(t){if(!this.gridOptionsWrapper.isEnableRtl())return t;switch(t){case Jr.Left:return Jr.Right;case Jr.Right:return Jr.Left;default:console.error("AG Grid: Unknown direction "+t)}},t.prototype.calculateOldIndex=function(t){var e=this.columnController.getAllGridColumns(),o=f(t.map((function(t){return e.indexOf(t)}))),n=o[0];return d(o)-n!==o.length-1?null:n},t.prototype.attemptMoveColumns=function(t,e,o,n,i){var r=o===Jr.Left,s=o===Jr.Right,a=e.slice();this.columnController.sortColumnsLikeGridColumns(a);var l=this.calculateValidMoves(a,s,n),p=this.calculateOldIndex(a);if(0!==l.length){var u=l[0],c=null!==p&&!i;if(t==$r.HeaderCell&&(c=null!==p),c){if(r&&u>=p)return;if(s&&u<=p)return}for(var d=0;d<l.length;d++){var h=l[d];if(this.columnController.doesMovePassRules(a,h))return void this.columnController.moveColumns(a,h,"uiColumnDragged")}}},t.prototype.calculateValidMoves=function(t,e,o){if(this.gridOptionsWrapper.isSuppressMovableColumns()||t.some((function(t){return t.getColDef().suppressMovable})))return[];var n,i=this.columnController.getDisplayedColumns(this.pinned),r=this.columnController.getAllGridColumns(),s=i.filter((function(e){return C(t,e)})),a=i.filter((function(e){return!C(t,e)})),l=r.filter((function(e){return!C(t,e)})),p=0,u=o;if(e){var c=0;s.forEach((function(t){return c+=t.getActualWidth()})),u-=c}if(u>0){for(var d=0;d<a.length;d++){if((u-=a[d].getActualWidth())<0)break;p++}e&&p++}if(p>0){var h=a[p-1];n=l.indexOf(h)+1}else-1===(n=l.indexOf(a[0]))&&(n=0);var f=[n],g=function(t,e){return t-e};if(e){for(var y=n+1,v=r.length-1;y<=v;)f.push(y),y++;f.sort(g)}else{y=n,v=r.length-1;for(var m=r[y];y<=v&&this.isColumnHidden(i,m);)y++,f.push(y),m=r[y];y=n-1;for(;y>=0;)f.push(y),y--;f.sort(g).reverse()}return f},t.prototype.isColumnHidden=function(t,e){return t.indexOf(e)<0},t.prototype.ensureIntervalStarted=function(){this.movingIntervalId||(this.intervalCount=0,this.failedMoveAttempts=0,this.movingIntervalId=window.setInterval(this.moveInterval.bind(this),100),this.needToMoveLeft?this.dragAndDropService.setGhostIcon(ns.ICON_LEFT,!0):this.dragAndDropService.setGhostIcon(ns.ICON_RIGHT,!0))},t.prototype.ensureIntervalCleared=function(){this.movingIntervalId&&(window.clearInterval(this.movingIntervalId),this.movingIntervalId=null,this.dragAndDropService.setGhostIcon(ns.ICON_MOVE))},t.prototype.moveInterval=function(){var t;this.intervalCount++,(t=10+5*this.intervalCount)>100&&(t=100);var e=null;if(this.needToMoveLeft?e=this.gridPanel.scrollHorizontally(-t):this.needToMoveRight&&(e=this.gridPanel.scrollHorizontally(t)),0!==e)this.onDragging(this.lastDraggingEvent),this.failedMoveAttempts=0;else{this.failedMoveAttempts++;var o=this.lastDraggingEvent.dragItem.columns.filter((function(t){return!t.getColDef().lockPinned}));if(o.length>0&&(this.dragAndDropService.setGhostIcon(ns.ICON_PINNED),this.failedMoveAttempts>7)){var n=this.needToMoveLeft?ht.PINNED_LEFT:ht.PINNED_RIGHT;this.setColumnsPinned(o,n,"uiColumnDragged"),this.dragAndDropService.nudge()}}},ca([it("loggerFactory")],t.prototype,"loggerFactory",void 0),ca([it("columnController")],t.prototype,"columnController",void 0),ca([it("dragAndDropService")],t.prototype,"dragAndDropService",void 0),ca([it("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),ca([et],t.prototype,"init",null),t}(),ha=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},fa=function(){function t(t){this.columnsToAggregate=[],this.columnsToGroup=[],this.columnsToPivot=[],this.pinned=t}return t.prototype.onDragEnter=function(t){var e=this;if(this.clearColumnsList(),!this.gridOptionsWrapper.isFunctionsReadOnly()){var o=t.dragItem.columns;o&&o.forEach((function(t){t.isPrimary()&&(t.isAnyFunctionActive()||(t.isAllowValue()?e.columnsToAggregate.push(t):t.isAllowRowGroup()?e.columnsToGroup.push(t):t.isAllowPivot()&&e.columnsToPivot.push(t)))}))}},t.prototype.getIconName=function(){return this.columnsToAggregate.length+this.columnsToGroup.length+this.columnsToPivot.length>0?this.pinned?ns.ICON_PINNED:ns.ICON_MOVE:null},t.prototype.onDragLeave=function(t){this.clearColumnsList()},t.prototype.clearColumnsList=function(){this.columnsToAggregate.length=0,this.columnsToGroup.length=0,this.columnsToPivot.length=0},t.prototype.onDragging=function(t){},t.prototype.onDragStop=function(t){this.columnsToAggregate.length>0&&this.columnController.addValueColumns(this.columnsToAggregate,"toolPanelDragAndDrop"),this.columnsToGroup.length>0&&this.columnController.addRowGroupColumns(this.columnsToGroup,"toolPanelDragAndDrop"),this.columnsToPivot.length>0&&this.columnController.addPivotColumns(this.columnsToPivot,"toolPanelDragAndDrop")},ha([it("columnController")],t.prototype,"columnController",void 0),ha([it("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),t}(),ga=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),ya=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s};
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/!function(t){t[t.ColumnMove=0]="ColumnMove",t[t.Pivot=1]="Pivot"}(pa||(pa={}));var va,ma=function(t){function e(e,o){var n=t.call(this)||this;return n.dropListeners={},n.pinned=e,n.eContainer=o,n}return ga(e,t),e.prototype.registerGridComp=function(t){switch(this.gridPanel=t,this.moveColumnController.registerGridComp(t),this.pinned){case ht.PINNED_LEFT:this.eSecondaryContainers=this.gridPanel.getDropTargetLeftContainers();break;case ht.PINNED_RIGHT:this.eSecondaryContainers=this.gridPanel.getDropTargetRightContainers();break;default:this.eSecondaryContainers=this.gridPanel.getDropTargetBodyContainers()}},e.prototype.isInterestedIn=function(t){return t===$r.HeaderCell||t===$r.ToolPanel&&this.gridOptionsWrapper.isAllowDragFromColumnsToolPanel()},e.prototype.getSecondaryContainers=function(){return this.eSecondaryContainers},e.prototype.getContainer=function(){return this.eContainer},e.prototype.init=function(){this.moveColumnController=this.createBean(new da(this.pinned,this.eContainer));var t=new fa(this.pinned);this.createBean(t),this.dropListeners[pa.ColumnMove]=this.moveColumnController,this.dropListeners[pa.Pivot]=t,this.dragAndDropService.addDropTarget(this)},e.prototype.getIconName=function(){return this.currentDropListener.getIconName()},e.prototype.getDropType=function(t){return this.columnController.isPivotMode()&&t.dragSource.type===$r.ToolPanel?pa.Pivot:pa.ColumnMove},e.prototype.onDragEnter=function(t){var e=this.getDropType(t);this.currentDropListener=this.dropListeners[e],this.currentDropListener.onDragEnter(t)},e.prototype.onDragLeave=function(t){this.currentDropListener.onDragLeave(t)},e.prototype.onDragging=function(t){this.currentDropListener.onDragging(t)},e.prototype.onDragStop=function(t){this.currentDropListener.onDragStop(t)},ya([it("dragAndDropService")],e.prototype,"dragAndDropService",void 0),ya([it("columnController")],e.prototype,"columnController",void 0),ya([et],e.prototype,"init",null),e}(Mt),Ca=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),wa=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Ea=function(t){function e(e,o,n){var i=t.call(this)||this;return i.groupsRowComps=[],i.eContainer=e,i.pinned=n,i.eViewport=o,i}return Ca(e,t),e.prototype.forEachHeaderElement=function(t){this.groupsRowComps&&this.groupsRowComps.forEach((function(e){return e.forEachHeaderElement(t)})),this.columnsRowComp&&this.columnsRowComp.forEachHeaderElement(t),this.filtersRowComp&&this.filtersRowComp.forEachHeaderElement(t)},e.prototype.init=function(){this.addManagedListener(this.eventService,Wt.EVENT_GRID_COLUMNS_CHANGED,this.onGridColumnsChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_SCROLL_VISIBILITY_CHANGED,this.onScrollVisibilityChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_RESIZED,this.onColumnResized.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_DISPLAYED_COLUMNS_CHANGED,this.onDisplayedColumnsChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_SCROLLBAR_WIDTH_CHANGED,this.onScrollbarWidthChanged.bind(this))},e.prototype.onColumnResized=function(){this.setWidthOfPinnedContainer()},e.prototype.onDisplayedColumnsChanged=function(){this.setWidthOfPinnedContainer()},e.prototype.onScrollVisibilityChanged=function(){this.setWidthOfPinnedContainer()},e.prototype.onScrollbarWidthChanged=function(){this.setWidthOfPinnedContainer()},e.prototype.setWidthOfPinnedContainer=function(){var t=this.pinned===ht.PINNED_LEFT,e=this.pinned===ht.PINNED_RIGHT,o=this.columnController,n=this.gridOptionsWrapper.isEnableRtl(),i=this.gridOptionsWrapper.getScrollbarWidth();if(t||e){var r=o[t?"getDisplayedColumnsLeftWidth":"getDisplayedColumnsRightWidth"]();this.scrollVisibleService.isVerticalScrollShowing()&&(n&&t||!n&&e)&&(r+=i),fo(this.eContainer,r)}},e.prototype.getRowComps=function(){var t=[];return this.groupsRowComps&&(t=t.concat(this.groupsRowComps)),this.columnsRowComp&&t.push(this.columnsRowComp),this.filtersRowComp&&t.push(this.filtersRowComp),t},e.prototype.onGridColumnsChanged=function(){this.refresh(!0)},e.prototype.refresh=function(t){void 0===t&&(t=!1),this.refreshRowComps(t)},e.prototype.setupDragAndDrop=function(t){var e=this.eViewport?this.eViewport:this.eContainer,o=new ma(this.pinned,e);this.createManagedBean(o),o.registerGridComp(t)},e.prototype.destroyRowComps=function(t){void 0===t&&(t=!1),this.groupsRowComps.forEach(this.destroyRowComp.bind(this)),this.groupsRowComps=[],this.destroyRowComp(this.filtersRowComp),this.filtersRowComp=void 0,t||(this.destroyRowComp(this.columnsRowComp),this.columnsRowComp=void 0)},e.prototype.destroyRowComp=function(t){t&&(this.destroyBean(t),this.eContainer.removeChild(t.getGui()))},e.prototype.refreshRowComps=function(t){var e=this;void 0===t&&(t=!1);var o=new Dn;!function(){var t=e.columnController.getHeaderRowCount()-1;e.groupsRowComps.forEach(e.destroyRowComp.bind(e)),e.groupsRowComps=[];for(var n=0;n<t;n++){var i=e.createBean(new ua(o.next(),os.COLUMN_GROUP,e.pinned));e.groupsRowComps.push(i)}}(),function(){var n=o.next();if(e.columnsRowComp){var i=e.columnsRowComp.getRowIndex()!==n;t&&!i||(e.destroyRowComp(e.columnsRowComp),e.columnsRowComp=void 0)}e.columnsRowComp||(e.columnsRowComp=e.createBean(new ua(n,os.COLUMN,e.pinned)))}(),function(){var n=function(){e.destroyRowComp(e.filtersRowComp),e.filtersRowComp=void 0};if(!e.columnController.isPivotMode()&&e.columnController.hasFloatingFilters()){var i=o.next();if(e.filtersRowComp){var r=e.filtersRowComp.getRowIndex()!==i;t&&!r||n()}e.filtersRowComp||(e.filtersRowComp=e.createBean(new ua(i,os.FLOATING_FILTER,e.pinned)))}else n()}(),this.getRowComps().forEach((function(t){return e.eContainer.appendChild(t.getGui())}))},wa([it("columnController")],e.prototype,"columnController",void 0),wa([it("scrollVisibleService")],e.prototype,"scrollVisibleService",void 0),wa([et],e.prototype,"init",null),wa([ot],e.prototype,"destroyRowComps",null),e}(Mt),Ra=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Oa=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s};
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/!function(t){t[t.UP=0]="UP",t[t.DOWN=1]="DOWN",t[t.LEFT=2]="LEFT",t[t.RIGHT=3]="RIGHT"}(va||(va={}));!function(t){function e(){return null!==t&&t.apply(this,arguments)||this}Ra(e,t),e.prototype.registerGridComp=function(t){this.gridPanel=t},e.prototype.registerHeaderRoot=function(t){this.headerRoot=t},e.prototype.getHeaderRowCount=function(){return 0===this.headerRoot.getHeaderContainers().size?0:this.getHeaderContainer().getRowComps().length},e.prototype.getHeaderRowType=function(t){if(this.getHeaderRowCount())return this.getHeaderContainer().getRowComps()[t].getType()},e.prototype.getHeaderContainer=function(t){return void 0===t&&(t="center"),null===t&&(t="center"),this.headerRoot.getHeaderContainers().get(t)},e.prototype.navigateVertically=function(t,e,o){if(e||(e=this.focusController.getFocusedHeader()),!e)return!1;var n=e.headerRowIndex,i=e.column,r=this.getHeaderRowCount(),s=t===va.UP,a=s?n-1:n+1,l=null,p=!1;a<0&&(a=0,l=i,p=!0),a>=r&&(a=-1);var u=this.getHeaderRowType(n);if(!p){if(u===os.COLUMN_GROUP){var c=i;l=s?i.getParent():c.getDisplayedChildren()[0]}else if(u===os.FLOATING_FILTER)l=i;else{c=i;l=s?c.getParent():c}if(!l)return!1}return this.focusController.focusHeaderPosition({headerRowIndex:a,column:l},void 0,!1,!0,o)},e.prototype.navigateHorizontally=function(t,e,o){void 0===e&&(e=!1);var n,i,r=this.focusController.getFocusedHeader();return t===va.LEFT!==this.gridOptionsWrapper.isEnableRtl()?(i="Before",n=this.headerPositionUtils.findHeader(r,i)):(i="After",n=this.headerPositionUtils.findHeader(r,i)),n?this.focusController.focusHeaderPosition(n,i,e,!0,o):!e||this.focusNextHeaderRow(r,i,o)},e.prototype.focusNextHeaderRow=function(t,e,o){var n,i=t.headerRowIndex,r=null;return"Before"===e?i>0&&(n=i-1,r=this.headerPositionUtils.findColAtEdgeForHeaderRow(n,"end")):(n=i+1,r=this.headerPositionUtils.findColAtEdgeForHeaderRow(n,"start")),this.focusController.focusHeaderPosition(r,e,!0,!0,o)},e.prototype.scrollToColumn=function(t,e){if(void 0===e&&(e="After"),!t.getPinned()){var o;if(t instanceof mt){var n=t.getDisplayedLeafColumns();o="Before"===e?d(n):n[0]}else o=t;this.gridPanel.ensureColumnVisible(o),this.gridPanel.horizontallyScrollHeaderCenterAndFloatingCenter(),this.animationFrameService.flushAllFrames()}},Oa([it("focusController")],e.prototype,"focusController",void 0),Oa([it("headerPositionUtils")],e.prototype,"headerPositionUtils",void 0),Oa([it("animationFrameService")],e.prototype,"animationFrameService",void 0),e=Oa([nt("headerNavigationService")],e)}(Mt);
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/var Pa,Sa=function(){function t(){}return t.BACKSPACE="Backspace",t.TAB="Tab",t.ENTER="Enter",t.SHIFT="Shift",t.ESCAPE="Escape",t.SPACE=" ",t.LEFT="ArrowLeft",t.UP="ArrowUp",t.RIGHT="ArrowRight",t.DOWN="ArrowDown",t.DELETE="Delete",t.NUM_PAD_DELETE="Del",t.A="a",t.C="c",t.V="v",t.D="d",t.Z="z",t.Y="y",t.F2="F2",t.PAGE_UP="PageUp",t.PAGE_DOWN="PageDown",t.PAGE_HOME="Home",t.PAGE_END="End",t}(),ba=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Da=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Aa=(function(t){function o(){var e=t.call(this,o.TEMPLATE)||this;return e.headerContainers=new Map,e}ba(o,t),o.prototype.postConstruct=function(){var e=this;t.prototype.postConstruct.call(this),this.printLayout=this.gridOptionsWrapper.getDomLayout()===ht.DOM_LAYOUT_PRINT,this.gridApi.registerHeaderRootComp(this),this.autoWidthCalculator.registerHeaderRootComp(this),this.registerHeaderContainer(new Ea(this.eHeaderContainer,this.eHeaderViewport,null),"center"),this.registerHeaderContainer(new Ea(this.ePinnedLeftHeader,null,ht.PINNED_LEFT),"left"),this.registerHeaderContainer(new Ea(this.ePinnedRightHeader,null,ht.PINNED_RIGHT),"right"),this.headerContainers.forEach((function(t){return e.createManagedBean(t)})),this.headerNavigationService.registerHeaderRoot(this),this.addManagedListener(this.gridOptionsWrapper,zr.PROP_DOM_LAYOUT,this.onDomLayoutChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_PIVOT_MODE_CHANGED,this.onPivotModeChanged.bind(this)),this.onPivotModeChanged(),this.addPreventHeaderScroll(),this.columnController.isReady()&&this.refreshHeader()},o.prototype.registerGridComp=function(t){this.gridPanel=t,this.headerContainers.forEach((function(e){return e.setupDragAndDrop(t)}))},o.prototype.registerHeaderContainer=function(t,e){this.headerContainers.set(e,t)},o.prototype.onTabKeyDown=function(t){var e=this.gridOptionsWrapper.isEnableRtl(),o=t.shiftKey!==e?va.LEFT:va.RIGHT;(this.headerNavigationService.navigateHorizontally(o,!0,t)||this.focusController.focusNextGridCoreContainer(t.shiftKey))&&t.preventDefault()},o.prototype.handleKeyDown=function(t){var o=null;switch(t.key){case Sa.LEFT:o=va.LEFT;case Sa.RIGHT:e(o)||(o=va.RIGHT),this.headerNavigationService.navigateHorizontally(o,!1,t);break;case Sa.UP:o=va.UP;case Sa.DOWN:e(o)||(o=va.DOWN),this.headerNavigationService.navigateVertically(o,null,t)&&t.preventDefault();break;default:return}},o.prototype.onFocusOut=function(t){var e=t.relatedTarget,o=this.getGui();!e&&o.contains(document.activeElement)||o.contains(e)||this.focusController.clearFocusedHeader()},o.prototype.onDomLayoutChanged=function(){var t=this.gridOptionsWrapper.getDomLayout()===ht.DOM_LAYOUT_PRINT;this.printLayout!==t&&(this.printLayout=t,this.refreshHeader())},o.prototype.setHorizontalScroll=function(t){this.eHeaderContainer.style.transform="translateX("+t+"px)"},o.prototype.forEachHeaderElement=function(t){this.headerContainers.forEach((function(e){return e.forEachHeaderElement(t)}))},o.prototype.refreshHeader=function(){this.headerContainers.forEach((function(t){return t.refresh()}))},o.prototype.onPivotModeChanged=function(){var t=this.columnController.isPivotMode();Ve(this.getGui(),"ag-pivot-on",t),Ve(this.getGui(),"ag-pivot-off",!t)},o.prototype.setHeight=function(t){var e=t+1+"px";this.getGui().style.height=e,this.getGui().style.minHeight=e},o.prototype.addPreventHeaderScroll=function(){var t=this;this.addManagedListener(this.eHeaderViewport,"scroll",(function(){var e=t.eHeaderViewport.scrollLeft;0!==e&&(t.gridPanel.scrollHorizontally(e),t.eHeaderViewport.scrollLeft=0)}))},o.prototype.getHeaderContainers=function(){return this.headerContainers},o.prototype.setHeaderContainerWidth=function(t){this.eHeaderContainer.style.width=t+"px"},o.prototype.setLeftVisible=function(t){ke(this.ePinnedLeftHeader,t)},o.prototype.setRightVisible=function(t){ke(this.ePinnedRightHeader,t)},o.TEMPLATE='<div class="ag-header" role="presentation">\n <div class="ag-pinned-left-header" ref="ePinnedLeftHeader" role="presentation"></div>\n <div class="ag-header-viewport" ref="eHeaderViewport" role="presentation">\n <div class="ag-header-container" ref="eHeaderContainer" role="rowgroup"></div>\n </div>\n <div class="ag-pinned-right-header" ref="ePinnedRightHeader" role="presentation"></div>\n </div>',Da([Wn("ePinnedLeftHeader")],o.prototype,"ePinnedLeftHeader",void 0),Da([Wn("ePinnedRightHeader")],o.prototype,"ePinnedRightHeader",void 0),Da([Wn("eHeaderContainer")],o.prototype,"eHeaderContainer",void 0),Da([Wn("eHeaderViewport")],o.prototype,"eHeaderViewport",void 0),Da([it("columnController")],o.prototype,"columnController",void 0),Da([it("gridApi")],o.prototype,"gridApi",void 0),Da([it("autoWidthCalculator")],o.prototype,"autoWidthCalculator",void 0),Da([it("headerNavigationService")],o.prototype,"headerNavigationService",void 0)}(Zn),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Ta=function(){return(Ta=Object.assign||function(t){for(var e,o=1,n=arguments.length;o<n;o++)for(var i in e=arguments[o])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)},_a=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Fa=(function(t){function o(){var e=null!==t&&t.apply(this,arguments)||this;return e.allAdvancedFilters=new Map,e.activeAdvancedFilters=[],e.quickFilter=null,e.quickFilterParts=null,e.processingFilterChange=!1,e}var n;Aa(o,t),n=o,o.prototype.init=function(){this.addManagedListener(this.eventService,Wt.EVENT_ROW_DATA_CHANGED,this.onNewRowsLoaded.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_NEW_COLUMNS_LOADED,this.onNewColumnsLoaded.bind(this)),this.quickFilter=this.parseQuickFilter(this.gridOptionsWrapper.getQuickFilterText()),this.setQuickFilterParts(),this.allowShowChangeAfterFilter=this.gridOptionsWrapper.isAllowShowChangeAfterFilter(),this.checkExternalFilter()},o.prototype.setQuickFilterParts=function(){this.quickFilterParts=this.quickFilter?this.quickFilter.split(" "):null},o.prototype.setFilterModel=function(t){var e=this,o=[];if(t){var n=Rn(Object.keys(t));this.allAdvancedFilters.forEach((function(i,r){var s=t[r];o.push(e.setModelOnFilterWrapper(i.filterPromise,s)),n.delete(r)})),n.forEach((function(n){var i=e.columnController.getPrimaryColumn(n);if(i){var r=e.getOrCreateFilterWrapper(i,"NO_UI");o.push(e.setModelOnFilterWrapper(r.filterPromise,t[n]))}else console.warn("Warning ag-grid setFilterModel - no column found for colId "+n)}))}else this.allAdvancedFilters.forEach((function(t){o.push(e.setModelOnFilterWrapper(t.filterPromise,null))}));Tn.all(o).then((function(){return e.onFilterChanged()}))},o.prototype.setModelOnFilterWrapper=function(t,e){return new Tn((function(o){t.then((function(t){"function"!=typeof t.setModel&&(console.warn("Warning ag-grid - filter missing setModel method, which is needed for setFilterModel"),o()),(t.setModel(e)||Tn.resolve()).then((function(){return o()}))}))}))},o.prototype.getFilterModel=function(){var t={};return this.allAdvancedFilters.forEach((function(o,n){var i=o.filterPromise.resolveNow(null,(function(t){return t}));if(null==i)return null;if("function"==typeof i.getModel){var r=i.getModel();e(r)&&(t[n]=r)}else console.warn("Warning ag-grid - filter API missing getModel method, which is needed for getFilterModel")})),t},o.prototype.isAdvancedFilterPresent=function(){return this.activeAdvancedFilters.length>0},o.prototype.updateActiveFilters=function(){var t=this;this.activeAdvancedFilters.length=0,this.allAdvancedFilters.forEach((function(e){if(e.filterPromise.resolveNow(!1,(function(t){return t.isFilterActive()}))){var o=e.filterPromise.resolveNow(null,(function(t){return t}));t.activeAdvancedFilters.push(o)}}))},o.prototype.updateFilterFlagInColumns=function(t,e){this.allAdvancedFilters.forEach((function(o){var n=o.filterPromise.resolveNow(!1,(function(t){return t.isFilterActive()}));o.column.setFilterActive(n,t,e)}))},o.prototype.isAnyFilterPresent=function(){return this.isQuickFilterPresent()||this.isAdvancedFilterPresent()||this.externalFilterPresent},o.prototype.doAdvancedFiltersPass=function(t,e){for(var o=t.data,n=0;n<this.activeAdvancedFilters.length;n++){var i=this.activeAdvancedFilters[n];if(null!=i&&i!==e){if("function"!=typeof i.doesFilterPass)throw new Error("Filter is missing method doesFilterPass");if(!i.doesFilterPass({node:t,data:o}))return!1}}return!0},o.prototype.parseQuickFilter=function(t){return e(t)?this.gridOptionsWrapper.isRowModelDefault()?t.toUpperCase():(console.warn("ag-grid: quick filtering only works with the Client-Side Row Model"),null):null},o.prototype.setQuickFilter=function(t){var e=this.parseQuickFilter(t);this.quickFilter!==e&&(this.quickFilter=e,this.setQuickFilterParts(),this.onFilterChanged())},o.prototype.checkExternalFilter=function(){this.externalFilterPresent=this.gridOptionsWrapper.isExternalFilterPresent()},o.prototype.onFilterChanged=function(t,e){this.updateActiveFilters(),this.updateFilterFlagInColumns("filterChanged",e),this.checkExternalFilter(),this.allAdvancedFilters.forEach((function(e){e.filterPromise.then((function(e){e!==t&&e.onAnyFilterChanged&&e.onAnyFilterChanged()}))}));var o={type:Wt.EVENT_FILTER_CHANGED,api:this.gridApi,columnApi:this.columnApi};e&&G(o,e),this.processingFilterChange=!0,this.eventService.dispatchEvent(o),this.processingFilterChange=!1},o.prototype.isSuppressFlashingCellsBecauseFiltering=function(){return!this.allowShowChangeAfterFilter&&this.processingFilterChange},o.prototype.isQuickFilterPresent=function(){return null!==this.quickFilter},o.prototype.doesRowPassOtherFilters=function(t,e){return this.doesRowPassFilter({rowNode:e,filterInstanceToSkip:t})},o.prototype.doesRowPassQuickFilterNoCache=function(t,o){var n=this;return O(this.columnController.getAllColumnsForQuickFilter(),(function(i){var r=n.getQuickFilterTextForColumn(i,t);return e(r)&&r.indexOf(o)>=0}))},o.prototype.doesRowPassQuickFilterCache=function(t,e){return t.quickFilterAggregateText||this.aggregateRowForQuickFilter(t),t.quickFilterAggregateText.indexOf(e)>=0},o.prototype.doesRowPassQuickFilter=function(t){var e=this,o=this.gridOptionsWrapper.isCacheQuickFilter();return R(this.quickFilterParts,(function(n){return o?e.doesRowPassQuickFilterCache(t,n):e.doesRowPassQuickFilterNoCache(t,n)}))},o.prototype.doesRowPassFilter=function(t){return!(this.isQuickFilterPresent()&&!this.doesRowPassQuickFilter(t.rowNode))&&(!(this.externalFilterPresent&&!this.gridOptionsWrapper.doesExternalFilterPass(t.rowNode))&&!(this.isAdvancedFilterPresent()&&!this.doAdvancedFiltersPass(t.rowNode,t.filterInstanceToSkip)))},o.prototype.getQuickFilterTextForColumn=function(t,o){var n=this.valueService.getValue(t,o,!0),i=t.getColDef();if(i.getQuickFilterText){var r={value:n,node:o,data:o.data,column:t,colDef:i,context:this.gridOptionsWrapper.getContext()};n=i.getQuickFilterText(r)}return e(n)?n.toString().toUpperCase():null},o.prototype.aggregateRowForQuickFilter=function(t){var o=this,i=[];P(this.columnController.getAllColumnsForQuickFilter(),(function(n){var r=o.getQuickFilterTextForColumn(n,t);e(r)&&i.push(r)})),t.quickFilterAggregateText=i.join(n.QUICK_FILTER_SEPARATOR)},o.prototype.onNewRowsLoaded=function(t){this.allAdvancedFilters.forEach((function(t){t.filterPromise.then((function(t){t.onNewRowsLoaded&&t.onNewRowsLoaded()}))})),this.updateFilterFlagInColumns(t),this.updateActiveFilters()},o.prototype.createValueGetter=function(t){var e=this;return function(o){return e.valueService.getValue(t,o,!0)}},o.prototype.getFilterComponent=function(t,e,o){if(void 0===o&&(o=!0),o)return this.getOrCreateFilterWrapper(t,e).filterPromise;var n=this.cachedFilter(t);return n?n.filterPromise:null},o.prototype.isFilterActive=function(t){var e=this.cachedFilter(t);return!!e&&e.filterPromise.resolveNow(!1,(function(t){return t.isFilterActive()}))},o.prototype.getOrCreateFilterWrapper=function(t,e){var o=this.cachedFilter(t);return o?"NO_UI"!==e&&this.putIntoGui(o,e):(o=this.createFilterWrapper(t,e),this.allAdvancedFilters.set(t.getColId(),o)),o},o.prototype.cachedFilter=function(t){return this.allAdvancedFilters.get(t.getColId())},o.prototype.createFilterInstance=function(t,e){var o,n=this,i=ft.isRegistered(pt.SetFilterModule)?"agSetColumnFilter":"agTextColumnFilter",r=t.getColDef(),s=Ta(Ta({},this.createFilterParams(t,r,e)),{filterModifiedCallback:function(){var e={type:Wt.EVENT_FILTER_MODIFIED,api:n.gridApi,columnApi:n.columnApi,column:t,filterInstance:o};n.eventService.dispatchEvent(e)},filterChangedCallback:function(t){return n.onFilterChanged(o,t)},doesRowPassOtherFilter:function(t){return n.doesRowPassOtherFilters(o,t)}}),a=this.userComponentFactory.newFilterComponent(r,s,i);return a&&a.then((function(t){return o=t})),a},o.prototype.createFilterParams=function(t,e,o){void 0===o&&(o=null);var n={api:this.gridOptionsWrapper.getApi(),column:t,colDef:T(e),rowModel:this.rowModel,filterChangedCallback:function(){},filterModifiedCallback:function(){},valueGetter:this.createValueGetter(t),context:this.gridOptionsWrapper.getContext(),doesRowPassOtherFilter:function(){return!0}};return o&&(n.$scope=o),n},o.prototype.createFilterWrapper=function(t,e){var o={column:t,filterPromise:null,scope:null,compiledElement:null,guiPromise:Tn.resolve(null)};return o.scope=this.gridOptionsWrapper.isAngularCompileFilters()?this.$scope.$new():null,o.filterPromise=this.createFilterInstance(t,o.scope),o.filterPromise&&this.putIntoGui(o,e),o},o.prototype.putIntoGui=function(t,o){var n=this,i=document.createElement("div");i.className="ag-filter",t.guiPromise=new Tn((function(r){t.filterPromise.then((function(s){var a=s.getGui();if(e(a)||console.warn("getGui method from filter returned "+a+", it should be a DOM element or an HTML template string."),"string"==typeof a&&(a=oo(a)),i.appendChild(a),t.scope){var l=n.$compile(i)(t.scope);t.compiledElement=l,window.setTimeout((function(){return t.scope.$apply()}),0)}r(i),n.eventService.dispatchEvent({type:Wt.EVENT_FILTER_OPENED,column:t.column,source:o,eGui:i,api:n.gridApi,columnApi:n.columnApi})}))}))},o.prototype.onNewColumnsLoaded=function(){var t=this,e=!1;this.allAdvancedFilters.forEach((function(o){!t.columnController.getPrimaryColumn(o.column)&&(e=!0,t.disposeFilterWrapper(o,"filterDestroyed"))})),e&&this.onFilterChanged()},o.prototype.destroyFilter=function(t,e){void 0===e&&(e="api");var o=this.allAdvancedFilters.get(t.getColId());o&&(this.disposeFilterWrapper(o,e),this.onFilterChanged())},o.prototype.disposeFilterWrapper=function(t,e){var o=this;t.filterPromise.then((function(n){(n.setModel(null)||Tn.resolve()).then((function(){o.getContext().destroyBean(n),t.column.setFilterActive(!1,e),t.scope&&(t.compiledElement&&t.compiledElement.remove(),t.scope.$destroy()),o.allAdvancedFilters.delete(t.column.getColId())}))}))},o.prototype.destroy=function(){var e=this;t.prototype.destroy.call(this),this.allAdvancedFilters.forEach((function(t){return e.disposeFilterWrapper(t,"filterDestroyed")}))},o.QUICK_FILTER_SEPARATOR="\n",_a([it("$compile")],o.prototype,"$compile",void 0),_a([it("$scope")],o.prototype,"$scope",void 0),_a([it("valueService")],o.prototype,"valueService",void 0),_a([it("columnController")],o.prototype,"columnController",void 0),_a([it("rowModel")],o.prototype,"rowModel",void 0),_a([it("columnApi")],o.prototype,"columnApi",void 0),_a([it("gridApi")],o.prototype,"gridApi",void 0),_a([it("userComponentFactory")],o.prototype,"userComponentFactory",void 0),_a([et],o.prototype,"init",null),_a([ot],o.prototype,"destroy",null),o=n=_a([nt("filterManager")],o)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Na=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},La=(function(t){function n(){var e=null!==t&&t.apply(this,arguments)||this;return e.initialised=!1,e}Fa(n,t),n.prototype.init=function(){this.cellExpressions=this.gridOptionsWrapper.isEnableCellExpressions(),this.initialised=!0},n.prototype.getValue=function(t,e,o,n){if(void 0===o&&(o=!1),void 0===n&&(n=!1),this.initialised||this.init(),e){var i,r=t.getColDef(),s=r.field,a=t.getId(),l=e.data,p=e.groupData&&void 0!==e.groupData[a],u=!n&&e.aggData&&void 0!==e.aggData[a];if(o&&r.filterValueGetter?i=this.executeFilterValueGetter(r.filterValueGetter,l,t,e):this.gridOptionsWrapper.isTreeData()&&u?i=e.aggData[a]:this.gridOptionsWrapper.isTreeData()&&r.valueGetter?i=this.executeValueGetter(r.valueGetter,l,t,e):this.gridOptionsWrapper.isTreeData()&&s&&l?i=V(l,s,t.isFieldContainsDots()):p?i=e.groupData[a]:u?i=e.aggData[a]:r.valueGetter?i=this.executeValueGetter(r.valueGetter,l,t,e):s&&l&&(i=V(l,s,t.isFieldContainsDots())),this.cellExpressions&&"string"==typeof i&&0===i.indexOf("=")){var c=i.substring(1);i=this.executeValueGetter(c,l,t,e)}if(null==i){var d=this.getOpenedGroup(e,t);if(null!=d)return d}return i}},n.prototype.getOpenedGroup=function(t,e){if(this.gridOptionsWrapper.isShowOpenedGroup()&&e.getColDef().showRowGroup)for(var o=e.getColDef().showRowGroup,n=t.parent;null!=n;){if(n.rowGroupColumn&&(!0===o||o===n.rowGroupColumn.getId()))return n.key;n=n.parent}},n.prototype.setValue=function(t,n,i,r){var s=this.columnController.getPrimaryColumn(n);if(t&&s){o(t.data)&&(t.data={});var a=s.getColDef(),l=a.field,p=a.newValueHandler,u=a.valueSetter;if(o(l)&&o(p)&&o(u))console.warn("AG Grid: you need either field or valueSetter set on colDef for editing to work");else{var c,d={node:t,data:t.data,oldValue:this.getValue(s,t),newValue:i,colDef:s.getColDef(),column:s,api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi(),context:this.gridOptionsWrapper.getContext()};if(d.newValue=i,void 0===(c=p&&e(p)?p(d):e(u)?this.expressionService.evaluate(u,d):this.setValueUsingField(t.data,l,i,s.isFieldContainsDots()))&&(c=!0),c){t.resetQuickFilterAggregateText(),this.valueCache.onDataChanged(),d.newValue=this.getValue(s,t);var h=s.getColDef().onCellValueChanged;"function"==typeof h&&setTimeout((function(){return h(d)}),0);var f={type:Wt.EVENT_CELL_VALUE_CHANGED,event:null,rowIndex:t.rowIndex,rowPinned:t.rowPinned,column:d.column,api:d.api,columnApi:d.columnApi,colDef:d.colDef,context:d.context,data:t.data,node:t,oldValue:d.oldValue,newValue:d.newValue,value:d.newValue,source:r};this.eventService.dispatchEvent(f)}}}},n.prototype.setValueUsingField=function(t,e,o,n){if(!e)return!1;if(n)for(var i=e.split("."),r=t;i.length>0&&r;){var s=i.shift();0===i.length?r[s]=o:r=r[s]}else t[e]=o;return!0},n.prototype.executeFilterValueGetter=function(t,e,o,n){var i={data:e,node:n,column:o,colDef:o.getColDef(),api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi(),context:this.gridOptionsWrapper.getContext(),getValue:this.getValueCallback.bind(this,n)};return this.expressionService.evaluate(t,i)},n.prototype.executeValueGetter=function(t,e,o,n){var i=o.getId(),r=this.valueCache.getValue(n,i);if(void 0!==r)return r;var s={data:e,node:n,column:o,colDef:o.getColDef(),api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi(),context:this.gridOptionsWrapper.getContext(),getValue:this.getValueCallback.bind(this,n)},a=this.expressionService.evaluate(t,s);return this.valueCache.setValue(n,i,a),a},n.prototype.getValueCallback=function(t,e){var o=this.columnController.getPrimaryColumn(e);return o?this.getValue(o,t):null},n.prototype.getKeyForNode=function(t,e){var o=this.getValue(t,e),n=t.getColDef().keyCreator,i=n?n({value:o}):o;return"string"==typeof i||null==i||"[object Object]"===(i=String(i))&&z((function(){console.warn("AG Grid: a column you are grouping or pivoting by has objects as values. If you want to group by complex objects then either a) use a colDef.keyCreator (se AG Grid docs) or b) to toString() on the object to return a key")}),"getKeyForNode - warn about [object,object]"),i},Na([it("expressionService")],n.prototype,"expressionService",void 0),Na([it("columnController")],n.prototype,"columnController",void 0),Na([it("valueCache")],n.prototype,"valueCache",void 0),Na([et],n.prototype,"init",null),n=Na([nt("valueService")],n)}(Mt),function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s}),Ia=function(){function t(t){this.childCount=0,this.rowTemplatesToAdd=[],this.afterGuiAttachedCallbacks=[],this.lastMadeVisibleTime=0,this.eContainer=t.eContainer,this.eViewport=t.eViewport,t.eWrapper&&(this.eWrapper=t.eWrapper),this.hideWhenNoChildren=!!t.hideWhenNoChildren}return t.prototype.setVerticalScrollPosition=function(t){this.scrollTop=t},t.prototype.postConstruct=function(){this.checkDomOrder(),this.checkVisibility(),this.gridOptionsWrapper.addEventListener(zr.PROP_DOM_LAYOUT,this.checkDomOrder.bind(this))},t.prototype.checkDomOrder=function(){this.domOrder=this.gridOptionsWrapper.isEnsureDomOrder()},t.prototype.getRowElement=function(t){return this.eContainer.querySelector('[comp-id="'+t+'"]')},t.prototype.setHeight=function(t){null!=t?(this.eContainer.style.height=t+"px",this.eWrapper&&(this.eWrapper.style.height=t+"px")):this.eContainer.style.height=""},t.prototype.flushRowTemplates=function(){if(0!==this.rowTemplatesToAdd.length){var t=this.rowTemplatesToAdd.join("");no(this.eContainer,t),this.rowTemplatesToAdd.length=0}this.afterGuiAttachedCallbacks.forEach((function(t){return t()})),this.afterGuiAttachedCallbacks.length=0,this.lastPlacedElement=null},t.prototype.appendRowTemplate=function(t,e){this.domOrder?this.lastPlacedElement=lo(this.eContainer,t,this.lastPlacedElement):this.rowTemplatesToAdd.push(t),this.afterGuiAttachedCallbacks.push(e),this.childCount++,this.checkVisibility()},t.prototype.ensureDomOrder=function(t){this.domOrder&&(so(this.eContainer,t,this.lastPlacedElement),this.lastPlacedElement=t)},t.prototype.removeRowElement=function(t){this.eContainer.removeChild(t),this.childCount--,this.checkVisibility()},t.prototype.checkVisibility=function(){if(this.hideWhenNoChildren){var t=this.eViewport?this.eViewport:this.eContainer,e=this.childCount>0;this.visible!==e&&(this.visible=e,this.lastMadeVisibleTime=(new Date).getTime(),ke(t,e),e&&this.eViewport&&(this.eViewport.scrollTop=this.scrollTop))}},t.prototype.isMadeVisibleRecently=function(){return(new Date).getTime()-this.lastMadeVisibleTime<500},La([it("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),La([et],t.prototype,"postConstruct",null),t}(),Ga=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Ma=function(){return(Ma=Object.assign||function(t){for(var e,o=1,n=arguments.length;o<n;o++)for(var i in e=arguments[o])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)},xa=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Va=function(){for(var t=0,e=0,o=arguments.length;e<o;e++)t+=arguments[e].length;var n=Array(t),i=0;for(e=0;e<o;e++)for(var r=arguments[e],s=0,a=r.length;s<a;s++,i++)n[i]=r[s];return n},Ha=function(t){function o(e,o){var n=t.call(this)||this;return n.isMultiRowDrag=!1,n.isGridSorted=!1,n.isGridFiltered=!1,n.isRowGroupActive=!1,n.eContainer=e,n.gridPanel=o,n}return Ga(o,t),o.prototype.postConstruct=function(){this.gridOptionsWrapper.isRowModelDefault()&&(this.clientSideRowModel=this.rowModel),this.addManagedListener(this.eventService,Wt.EVENT_SORT_CHANGED,this.onSortChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_FILTER_CHANGED,this.onFilterChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_ROW_GROUP_CHANGED,this.onRowGroupChanged.bind(this)),this.onSortChanged(),this.onFilterChanged(),this.onRowGroupChanged()},o.prototype.onSortChanged=function(){this.isGridSorted=this.sortController.isSortActive()},o.prototype.onFilterChanged=function(){this.isGridFiltered=this.filterManager.isAnyFilterPresent()},o.prototype.onRowGroupChanged=function(){var t=this.columnController.getRowGroupColumns();this.isRowGroupActive=!n(t)},o.prototype.getContainer=function(){return this.eContainer},o.prototype.isInterestedIn=function(t){return t===$r.RowDrag},o.prototype.getIconName=function(){return this.gridOptionsWrapper.isRowDragManaged()&&this.shouldPreventRowMove()?ns.ICON_NOT_ALLOWED:ns.ICON_MOVE},o.prototype.shouldPreventRowMove=function(){return this.isGridSorted||this.isGridFiltered||this.isRowGroupActive},o.prototype.getRowNodes=function(t){if(!this.isFromThisGrid(t))return t.dragItem.rowNodes||[];var e=this.gridOptionsWrapper.isEnableMultiRowDragging(),o=this.selectionController.getSelectedNodes(),n=t.dragItem.rowNode;return e&&-1!==o.indexOf(n)?(this.isMultiRowDrag=!0,Va(o)):(this.isMultiRowDrag=!1,[n])},o.prototype.onDragEnter=function(t){this.dispatchGridEvent(Wt.EVENT_ROW_DRAG_ENTER,t),this.getRowNodes(t).forEach((function(t){t.setDragging(!0)})),this.onEnterOrDragging(t)},o.prototype.onDragging=function(t){this.onEnterOrDragging(t)},o.prototype.isFromThisGrid=function(t){return t.dragSource.dragSourceDomDataKey===this.gridOptionsWrapper.getDomDataKey()},o.prototype.isDropZoneWithinThisGrid=function(t){var e=this.gridPanel.getGui(),o=t.dropZoneTarget;return!e.contains(o)},o.prototype.onEnterOrDragging=function(t){this.dispatchGridEvent(Wt.EVENT_ROW_DRAG_MOVE,t),this.lastDraggingEvent=t;var e=this.mouseEventService.getNormalisedPosition(t).y;this.gridOptionsWrapper.isRowDragManaged()&&this.doManagedDrag(t,e),this.checkCenterForScrolling(e)},o.prototype.doManagedDrag=function(t,e){var o,n=this,i=this.isFromThisGrid(t);i?(o=[t.dragItem.rowNode],this.isMultiRowDrag&&(o=Va(this.selectionController.getSelectedNodes()).sort((function(t,e){return n.getRowIndexNumber(t)-n.getRowIndexNumber(e)}))),t.dragItem.rowNodes=o):o=t.dragItem.rowNodes,this.gridOptionsWrapper.isRowDragManaged()&&this.shouldPreventRowMove()||(this.gridOptionsWrapper.isSuppressMoveWhenRowDragging()||!i?this.isDropZoneWithinThisGrid(t)||this.clientSideRowModel.highlightRowAtPixel(o[0],e):this.moveRows(o,e))},o.prototype.getRowIndexNumber=function(t){return parseInt(d(t.getRowIndexString().split("-")),10)},o.prototype.moveRowAndClearHighlight=function(t){var e=this,o=this.clientSideRowModel.getLastHighlightedRowNode(),n=o&&"below"===o.highlighted,i=this.mouseEventService.getNormalisedPosition(t).y,r=t.dragItem.rowNodes,s=n?1:0;if(this.isFromThisGrid(t))r.forEach((function(t){t.rowTop<i&&(s-=1)})),this.moveRows(r,i,s);else{var a=this.gridOptionsWrapper.getRowNodeIdFunc(),l=this.clientSideRowModel.getRowIndexAtPixel(i)+1;"above"===this.clientSideRowModel.getHighlightPosition(i)&&l--,this.clientSideRowModel.updateRowData({add:r.map((function(t){return t.data})).filter((function(t){return!e.clientSideRowModel.getRowNode(a?a(t):t.id)})),addIndex:l})}this.clearRowHighlight()},o.prototype.clearRowHighlight=function(){this.clientSideRowModel.highlightRowAtPixel(null)},o.prototype.moveRows=function(t,e,o){void 0===o&&(o=0),this.clientSideRowModel.ensureRowsAtPixel(t,e,o)&&(this.focusController.clearFocusedCell(),this.rangeController&&this.rangeController.removeAllCellRanges())},o.prototype.checkCenterForScrolling=function(t){var e=this.gridPanel.getVScrollPosition();this.needToMoveUp=t<e.top+50,this.needToMoveDown=t>e.bottom-50,this.needToMoveUp||this.needToMoveDown?this.ensureIntervalStarted():this.ensureIntervalCleared()},o.prototype.ensureIntervalStarted=function(){this.movingIntervalId||(this.intervalCount=0,this.movingIntervalId=window.setInterval(this.moveInterval.bind(this),100))},o.prototype.ensureIntervalCleared=function(){e(this.movingIntervalId)&&(window.clearInterval(this.movingIntervalId),this.movingIntervalId=null)},o.prototype.moveInterval=function(){var t;this.intervalCount++,(t=10+5*this.intervalCount)>100&&(t=100);var e=null;this.needToMoveDown?e=this.gridPanel.scrollVertically(t):this.needToMoveUp&&(e=this.gridPanel.scrollVertically(-t)),0!==e&&this.onDragging(this.lastDraggingEvent)},o.prototype.addRowDropZone=function(t){var e=this;if(t.getContainer())if(this.dragAndDropService.findExternalZone(t))console.warn("AG Grid: addRowDropZone - target already exists in the list of DropZones. Use `removeRowDropZone` before adding it again.");else{var o={getContainer:t.getContainer};t.fromGrid?(t.fromGrid=void 0,o=t):(t.onDragEnter&&(o.onDragEnter=function(o){t.onDragEnter(e.draggingToRowDragEvent(Wt.EVENT_ROW_DRAG_ENTER,o))}),t.onDragLeave&&(o.onDragLeave=function(o){t.onDragLeave(e.draggingToRowDragEvent(Wt.EVENT_ROW_DRAG_LEAVE,o))}),t.onDragging&&(o.onDragging=function(o){t.onDragging(e.draggingToRowDragEvent(Wt.EVENT_ROW_DRAG_MOVE,o))}),t.onDragStop&&(o.onDragStop=function(o){t.onDragStop(e.draggingToRowDragEvent(Wt.EVENT_ROW_DRAG_END,o))})),this.dragAndDropService.addDropTarget(Ma({isInterestedIn:function(t){return t===$r.RowDrag},getIconName:function(){return ns.ICON_MOVE},external:!0},o))}else z((function(){return console.warn("AG Grid: addRowDropZone - A container target needs to be provided")}),"add-drop-zone-empty-target")},o.prototype.getRowDropZone=function(t){var e=this,o=this.getContainer.bind(this),n=this.onDragEnter.bind(this),i=this.onDragLeave.bind(this),r=this.onDragging.bind(this),s=this.onDragStop.bind(this);return t?{getContainer:o,onDragEnter:t.onDragEnter?function(o){n(o),t.onDragEnter(e.draggingToRowDragEvent(Wt.EVENT_ROW_DRAG_ENTER,o))}:n,onDragLeave:t.onDragLeave?function(o){i(o),t.onDragLeave(e.draggingToRowDragEvent(Wt.EVENT_ROW_DRAG_LEAVE,o))}:i,onDragging:t.onDragging?function(o){r(o),t.onDragging(e.draggingToRowDragEvent(Wt.EVENT_ROW_DRAG_MOVE,o))}:r,onDragStop:t.onDragStop?function(o){s(o),t.onDragStop(e.draggingToRowDragEvent(Wt.EVENT_ROW_DRAG_END,o))}:s,fromGrid:!0}:{getContainer:o,onDragEnter:n,onDragLeave:i,onDragging:r,onDragStop:s,fromGrid:!0}},o.prototype.draggingToRowDragEvent=function(t,e){var o,n=this.mouseEventService.getNormalisedPosition(e).y,i=-1,r=null;switch(n>this.paginationProxy.getCurrentPageHeight()||(i=this.rowModel.getRowIndexAtPixel(n),r=this.rowModel.getRow(i)),e.vDirection){case Zr.Down:o="down";break;case Zr.Up:o="up";break;default:o=null}return{type:t,api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi(),event:e.event,node:e.dragItem.rowNode,nodes:e.dragItem.rowNodes,overIndex:i,overNode:r,y:n,vDirection:o}},o.prototype.dispatchGridEvent=function(t,e){var o=this.draggingToRowDragEvent(t,e);this.eventService.dispatchEvent(o)},o.prototype.onDragLeave=function(t){this.dispatchGridEvent(Wt.EVENT_ROW_DRAG_LEAVE,t),this.stopDragging(t),this.gridOptionsWrapper.isRowDragManaged()&&this.clearRowHighlight(),this.isFromThisGrid(t)&&(this.isMultiRowDrag=!1)},o.prototype.onDragStop=function(t){this.dispatchGridEvent(Wt.EVENT_ROW_DRAG_END,t),this.stopDragging(t),!this.gridOptionsWrapper.isRowDragManaged()||!this.gridOptionsWrapper.isSuppressMoveWhenRowDragging()&&this.isFromThisGrid(t)||this.isDropZoneWithinThisGrid(t)||this.moveRowAndClearHighlight(t)},o.prototype.stopDragging=function(t){this.ensureIntervalCleared(),this.getRowNodes(t).forEach((function(t){t.setDragging(!1)}))},xa([it("dragAndDropService")],o.prototype,"dragAndDropService",void 0),xa([it("rowModel")],o.prototype,"rowModel",void 0),xa([it("paginationProxy")],o.prototype,"paginationProxy",void 0),xa([it("columnController")],o.prototype,"columnController",void 0),xa([it("focusController")],o.prototype,"focusController",void 0),xa([it("sortController")],o.prototype,"sortController",void 0),xa([it("filterManager")],o.prototype,"filterManager",void 0),xa([it("selectionController")],o.prototype,"selectionController",void 0),xa([rt("rangeController")],o.prototype,"rangeController",void 0),xa([it("mouseEventService")],o.prototype,"mouseEventService",void 0),xa([et],o.prototype,"postConstruct",null),o}(Mt),Wa=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),ka=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s};!function(t){function e(){var e=t.call(this,'<div class="ag-root ag-unselectable" role="grid" unselectable="on">\n <ag-header-root ref="headerRoot" unselectable="on"></ag-header-root>\n <div class="ag-floating-top" ref="eTop" role="presentation" unselectable="on">\n <div class="ag-pinned-left-floating-top" ref="eLeftTop" role="presentation" unselectable="on"></div>\n <div class="ag-floating-top-viewport" ref="eTopViewport" role="presentation" unselectable="on">\n <div class="ag-floating-top-container" ref="eTopContainer" role="presentation" unselectable="on"></div>\n </div>\n <div class="ag-pinned-right-floating-top" ref="eRightTop" role="presentation" unselectable="on"></div>\n <div class="ag-floating-top-full-width-container" ref="eTopFullWidthContainer" role="presentation" unselectable="on"></div>\n </div>\n <div class="ag-body-viewport" ref="eBodyViewport" role="presentation">\n <div class="ag-pinned-left-cols-container" ref="eLeftContainer" role="presentation" unselectable="on"></div>\n <div class="ag-center-cols-clipper" ref="eCenterColsClipper" role="presentation" unselectable="on">\n <div class="ag-center-cols-viewport" ref="eCenterViewport" role="presentation">\n <div class="ag-center-cols-container" ref="eCenterContainer" role="rowgroup" unselectable="on"></div>\n </div>\n </div>\n <div class="ag-pinned-right-cols-container" ref="eRightContainer" role="presentation" unselectable="on"></div>\n <div class="ag-full-width-container" ref="eFullWidthContainer" role="presentation" unselectable="on"></div>\n </div>\n <div class="ag-floating-bottom" ref="eBottom" role="presentation" unselectable="on">\n <div class="ag-pinned-left-floating-bottom" ref="eLeftBottom" role="presentation" unselectable="on"></div>\n <div class="ag-floating-bottom-viewport" ref="eBottomViewport" role="presentation" unselectable="on">\n <div class="ag-floating-bottom-container" ref="eBottomContainer" role="presentation" unselectable="on"></div>\n </div>\n <div class="ag-pinned-right-floating-bottom" ref="eRightBottom" role="presentation" unselectable="on"></div>\n <div class="ag-floating-bottom-full-width-container" ref="eBottomFullWidthContainer" role="presentation" unselectable="on"></div>\n </div>\n <div class="ag-body-horizontal-scroll" ref="eHorizontalScrollBody" aria-hidden="true">\n <div class="ag-horizontal-left-spacer" ref="eHorizontalLeftSpacer"></div>\n <div class="ag-body-horizontal-scroll-viewport" ref="eBodyHorizontalScrollViewport">\n <div class="ag-body-horizontal-scroll-container" ref="eBodyHorizontalScrollContainer"></div>\n </div>\n <div class="ag-horizontal-right-spacer" ref="eHorizontalRightSpacer"></div>\n </div>\n <ag-overlay-wrapper ref="overlayWrapper"></ag-overlay-wrapper>\n </div>')||this;return e.scrollLeft=-1,e.scrollTop=-1,e.nextScrollTop=-1,e.resetLastHorizontalScrollElementDebounced=$(e.resetLastHorizontalScrollElement.bind(e),500),e}Wa(e,t),e.prototype.getVScrollPosition=function(){return{top:this.eBodyViewport.scrollTop,bottom:this.eBodyViewport.scrollTop+this.eBodyViewport.offsetHeight}},e.prototype.getHScrollPosition=function(){return{left:this.eCenterViewport.scrollLeft,right:this.eCenterViewport.scrollLeft+this.eCenterViewport.offsetWidth}},e.prototype.onRowDataChanged=function(){this.showOrHideOverlay()},e.prototype.showOrHideOverlay=function(){var t=this.paginationProxy.isEmpty(),e=this.gridOptionsWrapper.isSuppressNoRowsOverlay();this[t&&!e?"showNoRowsOverlay":"hideOverlay"]()},e.prototype.onNewColumnsLoaded=function(){this.columnController.isReady()&&!this.paginationProxy.isEmpty()&&this.hideOverlay(),this.rowRenderer.forEachCellComp((function(t){return t.onNewColumnsLoaded()}))},e.prototype.init=function(){var t=this;this.enableRtl=this.gridOptionsWrapper.isEnableRtl(),this.printLayout=this.gridOptionsWrapper.getDomLayout()===ht.DOM_LAYOUT_PRINT,this.gridOptionsWrapper.addLayoutElement(this.getGui()),this.gridOptionsWrapper.addLayoutElement(this.eBodyViewport),this.suppressScrollOnFloatingRow(),this.setupRowAnimationCssClass(),this.buildRowContainerComponents(),this.addEventListeners(),this.addDragListeners(),this.addScrollListener(),this.gridOptionsWrapper.isRowModelDefault()&&!this.gridOptionsWrapper.getRowData()&&this.showLoadingOverlay(),this.setCellTextSelection(this.gridOptionsWrapper.isEnableCellTextSelect()),this.setPinnedContainerSize(),this.setHeaderAndFloatingHeights(),this.disableBrowserDragging(),this.addMouseListeners(),this.addPreventScrollWhileDragging(),this.addKeyboardEvents(),this.addBodyViewportListener(),this.addStopEditingWhenGridLosesFocus(),this.mockContextMenuForIPad(),this.addRowDragListener(),this.$scope&&this.addAngularApplyCheck(),this.onDisplayedColumnsWidthChanged(),this.gridApi.registerGridComp(this),this.alignedGridsService.registerGridComp(this),this.headerRootComp.registerGridComp(this),this.navigationService.registerGridComp(this),this.headerNavigationService.registerGridComp(this),this.heightScaler.registerGridComp(this),this.autoHeightCalculator.registerGridComp(this),this.columnAnimationService.registerGridComp(this),this.autoWidthCalculator.registerGridComp(this),this.paginationAutoPageSizeService.registerGridComp(this),this.mouseEventService.registerGridComp(this),this.beans.registerGridComp(this),this.rowRenderer.registerGridComp(this),this.animationFrameService.registerGridComp(this),this.contextMenuFactory&&this.contextMenuFactory.registerGridComp(this),this.menuFactory&&this.menuFactory.registerGridComp(this),(this.rangeController||this.gridOptionsWrapper.isRowSelectionMulti())&&(Bo(this.getGui(),!0),this.rangeController&&this.rangeController.registerGridComp(this)),[this.eCenterViewport,this.eBodyViewport].forEach((function(e){var o=t.resizeObserverService.observeResize(e,t.onCenterViewportResized.bind(t));t.addDestroyFunc((function(){return o()}))})),[this.eTop,this.eBodyViewport,this.eBottom].forEach((function(e){t.addManagedListener(e,"focusin",(function(){Me(e,"ag-has-focus")})),t.addManagedListener(e,"focusout",(function(t){e.contains(t.relatedTarget)||xe(e,"ag-has-focus")}))}))},e.prototype.onDomLayoutChanged=function(){var t=this.gridOptionsWrapper.getDomLayout()===ht.DOM_LAYOUT_PRINT;this.printLayout!==t&&(this.printLayout=t,this.setWidthsOfContainers(),this.setPinnedContainerSize())},e.prototype.onCenterViewportResized=function(){if(eo(this.eCenterViewport)){this.checkViewportAndScrolls();var t=this.getCenterWidth();t!==this.centerWidth&&(this.centerWidth=t,this.columnController.refreshFlexedColumns({viewportWidth:this.centerWidth,updateBodyWidths:!0,fireResizedEvent:!0}))}else this.bodyHeight=0},e.prototype.setColumnMovingCss=function(t){this.addOrRemoveCssClass("ag-column-moving",t)},e.prototype.setCellTextSelection=function(t){void 0===t&&(t=!1),[this.eTop,this.eBodyViewport,this.eBottom].forEach((function(e){return Ve(e,"ag-selectable",t)}))},e.prototype.addRowDragListener=function(){this.rowDragFeature=this.createManagedBean(new Ha(this.eBodyViewport,this)),this.dragAndDropService.addDropTarget(this.rowDragFeature)},e.prototype.getRowDragFeature=function(){return this.rowDragFeature},e.prototype.addStopEditingWhenGridLosesFocus=function(){var t=this;if(this.gridOptionsWrapper.isStopEditingWhenGridLosesFocus()){var e=[this.eBodyViewport,this.eBottom,this.eTop],o=function(o){var n=o.relatedTarget;if(null!==Te(n)){var i=e.some((function(t){return t.contains(n)}));if(!i){var r=t.popupService;i=r.getActivePopups().some((function(t){return t.contains(n)}))||r.isElementWithinCustomPopup(n)}i||t.rowRenderer.stopEditing()}else t.rowRenderer.stopEditing()};e.forEach((function(e){return t.addManagedListener(e,"focusout",o)}))}},e.prototype.addAngularApplyCheck=function(){var t=this,e=!1,o=function(){e||(e=!0,window.setTimeout((function(){e=!1,t.$scope.$apply()}),0))};this.addManagedListener(this.eventService,Wt.EVENT_DISPLAYED_COLUMNS_CHANGED,o),this.addManagedListener(this.eventService,Wt.EVENT_VIRTUAL_COLUMNS_CHANGED,o)},e.prototype.disableBrowserDragging=function(){this.addGuiEventListener("dragstart",(function(t){if(t.target instanceof HTMLImageElement)return t.preventDefault(),!1}))},e.prototype.addEventListeners=function(){this.addManagedListener(this.eventService,Wt.EVENT_DISPLAYED_COLUMNS_CHANGED,this.onDisplayedColumnsChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED,this.onDisplayedColumnsWidthChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_PINNED_ROW_DATA_CHANGED,this.setHeaderAndFloatingHeights.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_ROW_DATA_CHANGED,this.onRowDataChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_ROW_DATA_UPDATED,this.onRowDataChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_NEW_COLUMNS_LOADED,this.onNewColumnsLoaded.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_SCROLLBAR_WIDTH_CHANGED,this.onScrollbarWidthChanged.bind(this)),this.addManagedListener(this.gridOptionsWrapper,zr.PROP_HEADER_HEIGHT,this.setHeaderAndFloatingHeights.bind(this)),this.addManagedListener(this.gridOptionsWrapper,zr.PROP_PIVOT_HEADER_HEIGHT,this.setHeaderAndFloatingHeights.bind(this)),this.addManagedListener(this.gridOptionsWrapper,zr.PROP_GROUP_HEADER_HEIGHT,this.setHeaderAndFloatingHeights.bind(this)),this.addManagedListener(this.gridOptionsWrapper,zr.PROP_PIVOT_GROUP_HEADER_HEIGHT,this.setHeaderAndFloatingHeights.bind(this)),this.addManagedListener(this.gridOptionsWrapper,zr.PROP_FLOATING_FILTERS_HEIGHT,this.setHeaderAndFloatingHeights.bind(this)),this.addManagedListener(this.gridOptionsWrapper,zr.PROP_DOM_LAYOUT,this.onDomLayoutChanged.bind(this))},e.prototype.addDragListeners=function(){var t=this;this.gridOptionsWrapper.isEnableRangeSelection()&&!o(this.rangeController)&&[this.eLeftContainer,this.eRightContainer,this.eCenterContainer,this.eTop,this.eBottom].forEach((function(e){var o={eElement:e,onDragStart:t.rangeController.onDragStart.bind(t.rangeController),onDragStop:t.rangeController.onDragStop.bind(t.rangeController),onDragging:t.rangeController.onDragging.bind(t.rangeController)};t.dragService.addDragSource(o),t.addDestroyFunc((function(){return t.dragService.removeDragSource(o)}))}))},e.prototype.addMouseListeners=function(){var t=this;["dblclick","contextmenu","mouseover","mouseout","click","mousedown"].forEach((function(e){var o=t.processMouseEvent.bind(t,e);t.eAllCellContainers.forEach((function(n){return t.addManagedListener(n,e,o)}))}))},e.prototype.addPreventScrollWhileDragging=function(){var t=this,e=function(e){t.dragService.isDragging()&&e.cancelable&&e.preventDefault()};this.eAllCellContainers.forEach((function(t){t.addEventListener("touchmove",e,{passive:!1})})),this.addDestroyFunc((function(){t.eAllCellContainers.forEach((function(t){t.removeEventListener("touchmove",e)}))}))},e.prototype.addKeyboardEvents=function(){var t=this;["keydown","keypress"].forEach((function(e){var o=t.processKeyboardEvent.bind(t,e);t.eAllCellContainers.forEach((function(n){t.addManagedListener(n,e,o)}))}))},e.prototype.addBodyViewportListener=function(){var t=this;this.addManagedListener(this.eBodyViewport,"contextmenu",(function(e){var o=At(e);o!==t.eBodyViewport&&o!==t.eCenterViewport||(t.onContextMenu(e,null,null,null,null,t.getGui()),t.preventDefaultOnContextMenu(e))}))},e.prototype.getBodyClientRect=function(){if(this.eBodyViewport)return this.eBodyViewport.getBoundingClientRect()},e.prototype.getRowForEvent=function(t){for(var e=At(t);e;){var o=this.gridOptionsWrapper.getDomData(e,Es.DOM_DATA_KEY_RENDERED_ROW);if(o)return o;e=e.parentElement}return null},e.prototype.processKeyboardEvent=function(t,e){var o=Dt(this.gridOptionsWrapper,e,"cellComp"),n=Dt(this.gridOptionsWrapper,e,"renderedRow");e.defaultPrevented||(o?this.processCellKeyboardEvent(o,t,e):n&&n.isFullWidth()&&this.processFullWidthRowKeyboardEvent(n,t,e))},e.prototype.processCellKeyboardEvent=function(t,e,o){var n=t.getRenderedRow().getRowNode(),i=t.getColumn(),r=t.isEditing();if(!gn(this.gridOptionsWrapper,o,n,i,r))switch(e){case"keydown":!r&&this.navigationService.handlePageScrollingKey(o)||t.onKeyDown(o),this.doGridOperations(o,t);break;case"keypress":t.onKeyPress(o)}if("keydown"===e){var s=t.createEvent(o,Wt.EVENT_CELL_KEY_DOWN);this.eventService.dispatchEvent(s)}if("keypress"===e){var a=t.createEvent(o,Wt.EVENT_CELL_KEY_PRESS);this.eventService.dispatchEvent(a)}},e.prototype.processFullWidthRowKeyboardEvent=function(t,e,o){var n=t.getRowNode(),i=this.beans.focusController.getFocusedCell(),r=i&&i.column;if(!gn(this.gridOptionsWrapper,o,n,r,!1)){var s=o.key;if("keydown"===e)switch(s){case Sa.UP:case Sa.DOWN:t.onKeyboardNavigate(o);break;case Sa.TAB:t.onTabKeyDown(o)}}},e.prototype.doGridOperations=function(t,e){if((t.ctrlKey||t.metaKey)&&!e.isEditing()&&this.mouseEventService.isEventFromThisGrid(t))switch(t.which){case jn.A:return this.onCtrlAndA(t);case jn.C:return this.onCtrlAndC(t);case jn.V:return this.onCtrlAndV();case jn.D:return this.onCtrlAndD(t);case jn.Z:return t.shiftKey?this.undoRedoService.redo():this.undoRedoService.undo();case jn.Y:return this.undoRedoService.redo()}},e.prototype.scrollToTop=function(){this.eBodyViewport.scrollTop=0},e.prototype.processMouseEvent=function(t,e){if(this.mouseEventService.isEventFromThisGrid(e)&&!Pt(e)){var o=this.getRowForEvent(e),n=this.mouseEventService.getRenderedCellForEvent(e);"contextmenu"===t?(this.preventDefaultOnContextMenu(e),this.handleContextMenuMouseEvent(e,null,o,n)):(n&&n.onMouseEvent(t,e),o&&o.onMouseEvent(t,e))}},e.prototype.mockContextMenuForIPad=function(){var t=this;Ae()&&this.eAllCellContainers.forEach((function(e){var o=new ci(e);t.addManagedListener(o,ci.EVENT_LONG_TAP,(function(e){var o=t.getRowForEvent(e.touchEvent),n=t.mouseEventService.getRenderedCellForEvent(e.touchEvent);t.handleContextMenuMouseEvent(null,e.touchEvent,o,n)})),t.addDestroyFunc((function(){return o.destroy()}))}))},e.prototype.handleContextMenuMouseEvent=function(t,e,o,n){var i=o?o.getRowNode():null,r=n?n.getColumn():null,s=null;if(r){var a=t||e;n.dispatchCellContextMenuEvent(a),s=this.valueService.getValue(r,i)}var l=n?n.getGui():this.getGui();this.onContextMenu(t,e,i,r,s,l)},e.prototype.onContextMenu=function(t,e,o,n,i,r){if((this.gridOptionsWrapper.isAllowContextMenuWithControlKey()||!t||!t.ctrlKey&&!t.metaKey)&&this.contextMenuFactory&&!this.gridOptionsWrapper.isSuppressContextMenu()){var s=t||e.touches[0];if(this.contextMenuFactory.showMenu(o,n,i,s,r))(t||e).preventDefault()}},e.prototype.preventDefaultOnContextMenu=function(t){var e=this.gridOptionsWrapper,o=t.which;(e.isPreventDefaultOnContextMenu()||e.isSuppressMiddleClickScrolls()&&2===o)&&t.preventDefault()},e.prototype.onCtrlAndA=function(t){var e=this.pinnedRowModel,o=this.paginationProxy,i=this.rangeController,r=ht.PINNED_BOTTOM,s=ht.PINNED_TOP;if(i&&o.isRowsToRender()){var a=[e.isEmpty(s),e.isEmpty(r)],l=a[0]?null:s,p=void 0,u=void 0;a[1]?(p=null,u=this.paginationProxy.getRowCount()-1):(p=r,u=e.getPinnedBottomRowData().length-1);var c=this.columnController.getAllDisplayedColumns();if(n(c))return;i.setCellRange({rowStartIndex:0,rowStartPinned:l,rowEndIndex:u,rowEndPinned:p,columnStart:c[0],columnEnd:d(c)})}t.preventDefault()},e.prototype.onCtrlAndC=function(t){this.clipboardService&&!this.gridOptionsWrapper.isEnableCellTextSelection()&&(this.clipboardService.copyToClipboard(),t.preventDefault())},e.prototype.onCtrlAndV=function(){ft.isRegistered(pt.ClipboardModule)&&!this.gridOptionsWrapper.isSuppressClipboardPaste()&&this.clipboardService.pasteFromClipboard()},e.prototype.onCtrlAndD=function(t){ft.isRegistered(pt.ClipboardModule)&&!this.gridOptionsWrapper.isSuppressClipboardPaste()&&this.clipboardService.copyRangeDown(),t.preventDefault()},e.prototype.ensureIndexVisible=function(t,e){if(!this.printLayout){var o=this.paginationProxy.getRowCount();if("number"!=typeof t||t<0||t>=o)console.warn("invalid row index for ensureIndexVisible: "+t);else{this.gridOptionsWrapper.isPagination()&&!this.gridOptionsWrapper.isSuppressPaginationPanel()||this.paginationProxy.goToPageWithIndex(t);var n,i=this.paginationProxy.getRow(t);do{var r=i.rowTop,s=i.rowHeight,a=this.paginationProxy.getPixelOffset(),l=i.rowTop-a,p=l+i.rowHeight,u=this.getVScrollPosition(),c=this.heightScaler.getOffset(),d=u.top+c,h=u.bottom+c,f=h-d,g=this.heightScaler.getScrollPositionForPixel(l),y=this.heightScaler.getScrollPositionForPixel(p-f),v=Math.min((g+y)/2,l),m=null;"top"===e?m=g:"bottom"===e?m=y:"middle"===e?m=v:d>l?m=g:h<p&&(m=y),null!==m&&(this.eBodyViewport.scrollTop=m,this.rowRenderer.redrawAfterScroll()),n=r!==i.rowTop||s!==i.rowHeight}while(n);this.animationFrameService.flushAllFrames()}}},e.prototype.getCenterWidth=function(){return Ye(this.eCenterViewport)},e.prototype.isHorizontalScrollShowing=function(){return this.gridOptionsWrapper.isAlwaysShowHorizontalScroll()||uo(this.eCenterViewport)},e.prototype.isVerticalScrollShowing=function(){var t=this.gridOptionsWrapper.isAlwaysShowVerticalScroll();return Ve(this.eBodyViewport,"ag-force-vertical-scroll",t),t||co(this.eBodyViewport)},e.prototype.onScrollbarWidthChanged=function(){this.checkViewportAndScrolls()},e.prototype.checkViewportAndScrolls=function(){this.updateScrollVisibleService(),this.checkBodyHeight(),this.onHorizontalViewportChanged(),this.setPinnedContainerSize(),this.scrollLeft!==this.getCenterViewportScrollLeft()&&this.onBodyHorizontalScroll(this.eCenterViewport)},e.prototype.updateScrollVisibleService=function(){this.updateScrollVisibleServiceImpl(),setTimeout(this.updateScrollVisibleServiceImpl.bind(this),500)},e.prototype.updateScrollVisibleServiceImpl=function(){var t={horizontalScrollShowing:!1,verticalScrollShowing:!1};t.verticalScrollShowing=this.isVerticalScrollShowing(),t.horizontalScrollShowing=this.isHorizontalScrollShowing(),this.scrollVisibleService.setScrollsVisible(t),this.setHorizontalScrollVisible(t.horizontalScrollShowing),this.setVerticalScrollPaddingVisible(t.verticalScrollShowing)},e.prototype.setHorizontalScrollVisible=function(t){var e=this.gridOptionsWrapper.isSuppressHorizontalScroll(),o=t&&this.gridOptionsWrapper.getScrollbarWidth()||0,n=e?0:o,i=Oe()&&t;this.eCenterViewport.style.height="calc(100% + "+o+"px)",go(this.eHorizontalScrollBody,n),go(this.eBodyHorizontalScrollViewport,n+(i?1:0)),go(this.eBodyHorizontalScrollContainer,n)},e.prototype.setVerticalScrollPaddingVisible=function(t){var e=t?"scroll":"hidden";this.eTop.style.overflowY=this.eBottom.style.overflowY=e,this.setFakeHScrollSpacerWidths()},e.prototype.updateRowCount=function(){var t=this.headerNavigationService.getHeaderRowCount(),e=this.paginationProxy.getType(),o=-1;e===ht.ROW_MODEL_TYPE_CLIENT_SIDE&&(o=0,this.paginationProxy.forEachNode((function(t){t.group||o++})));var n=-1===o?-1:t+o;jo(this.getGui(),n)},e.prototype.updateColumnCount=function(){var t=this.columnController.getAllGridColumns();zo(this.getGui(),t.length)},e.prototype.ensureColumnVisible=function(t){var e=this.columnController.getGridColumn(t);if(e)if(e.isPinned())console.warn("calling ensureIndexVisible on a "+e.getPinned()+" pinned column doesn't make sense for column "+e.getColId());else if(this.columnController.isColumnDisplayed(e)){var o,n,i=e.getLeft(),r=i+e.getActualWidth(),s=this.getCenterWidth(),a=this.getCenterViewportScrollLeft(),l=this.columnController.getBodyContainerWidth();this.enableRtl?(o=l-a-s,n=l-a):(o=a,n=s+a);var p=o>i,u=n<r,c=s<e.getActualWidth(),d=p||c;if(d||u){var h=void 0;h=this.enableRtl?d?l-s-i:l-r:d?i:r-s,this.setCenterViewportScrollLeft(h)}this.onHorizontalViewportChanged(),this.animationFrameService.flushAllFrames()}else console.warn("column is not currently visible")},e.prototype.showLoadingOverlay=function(){this.gridOptionsWrapper.isSuppressLoadingOverlay()||this.overlayWrapper.showLoadingOverlay()},e.prototype.showNoRowsOverlay=function(){this.gridOptionsWrapper.isSuppressNoRowsOverlay()||this.overlayWrapper.showNoRowsOverlay()},e.prototype.hideOverlay=function(){this.overlayWrapper.hideOverlay()},e.prototype.sizeColumnsToFit=function(t){var e=this,o=0;this.isVerticalScrollShowing()&&(o=this.gridOptionsWrapper.getScrollbarWidth());var n=Ye(this.eBodyViewport)-o;n>0?this.columnController.sizeColumnsToFit(n,"sizeColumnsToFit"):void 0===t?window.setTimeout((function(){e.sizeColumnsToFit(100)}),0):100===t?window.setTimeout((function(){e.sizeColumnsToFit(500)}),100):500===t?window.setTimeout((function(){e.sizeColumnsToFit(-1)}),500):console.warn("AG Grid: tried to call sizeColumnsToFit() but the grid is coming back with zero width, maybe the grid is not visible yet on the screen?")},e.prototype.getCenterContainer=function(){return this.eCenterContainer},e.prototype.getDropTargetBodyContainers=function(){return[this.eBodyViewport,this.eTopViewport,this.eBottomViewport]},e.prototype.getDropTargetLeftContainers=function(){return[this.eLeftContainer,this.eLeftBottom,this.eLeftTop]},e.prototype.getDropTargetRightContainers=function(){return[this.eRightContainer,this.eRightBottom,this.eRightTop]},e.prototype.buildRowContainerComponents=function(){var t=this;this.eAllCellContainers=[this.eLeftContainer,this.eRightContainer,this.eCenterContainer,this.eTop,this.eBottom,this.eFullWidthContainer],this.rowContainerComponents={body:new Ia({eContainer:this.eCenterContainer,eWrapper:this.eCenterColsClipper,eViewport:this.eBodyViewport}),fullWidth:new Ia({eContainer:this.eFullWidthContainer}),pinnedLeft:new Ia({eContainer:this.eLeftContainer}),pinnedRight:new Ia({eContainer:this.eRightContainer}),floatingTop:new Ia({eContainer:this.eTopContainer}),floatingTopPinnedLeft:new Ia({eContainer:this.eLeftTop}),floatingTopPinnedRight:new Ia({eContainer:this.eRightTop}),floatingTopFullWidth:new Ia({eContainer:this.eTopFullWidthContainer,hideWhenNoChildren:!0}),floatingBottom:new Ia({eContainer:this.eBottomContainer}),floatingBottomPinnedLeft:new Ia({eContainer:this.eLeftBottom}),floatingBottomPinnedRight:new Ia({eContainer:this.eRightBottom}),floatingBottomFullWidth:new Ia({eContainer:this.eBottomFullWidthContainer,hideWhenNoChildren:!0})},A(this.rowContainerComponents,(function(e,o){o&&t.getContext().createBean(o)}))},e.prototype.setupRowAnimationCssClass=function(){var t=this,e=function(){var e=t.gridOptionsWrapper.isAnimateRows()&&!t.heightScaler.isScaling();Ve(t.eBodyViewport,"ag-row-animation",e),Ve(t.eBodyViewport,"ag-row-no-animation",!e)};e(),this.addManagedListener(this.eventService,Wt.EVENT_HEIGHT_SCALE_CHANGED,e)},e.prototype.suppressScrollOnFloatingRow=function(){var t=this;this.addManagedListener(this.eTopViewport,"scroll",(function(){return t.eTopViewport.scrollLeft=0})),this.addManagedListener(this.eBottomViewport,"scroll",(function(){return t.eTopViewport.scrollLeft=0}))},e.prototype.getRowContainers=function(){return this.rowContainerComponents},e.prototype.getFloatingTopBottom=function(){return[this.eTop,this.eBottom]},e.prototype.onDisplayedColumnsChanged=function(){this.setPinnedContainerSize(),this.setHeaderAndFloatingHeights(),this.onHorizontalViewportChanged(),this.updateScrollVisibleService(),this.updateColumnCount()},e.prototype.onDisplayedColumnsWidthChanged=function(){this.setWidthsOfContainers(),this.onHorizontalViewportChanged(),this.updateScrollVisibleService(),this.enableRtl&&this.horizontallyScrollHeaderCenterAndFloatingCenter()},e.prototype.setWidthsOfContainers=function(){this.setCenterWidth(),this.setPinnedContainerSize()},e.prototype.setCenterWidth=function(){var t=this.headerRootComp,e=this.columnController,o=e.getBodyContainerWidth();this.printLayout&&(o+=e.getDisplayedColumnsLeftWidth()+e.getDisplayedColumnsRightWidth());t.setHeaderContainerWidth(o);var n=o+"px";this.eCenterContainer.style.width=n,this.eBottomContainer.style.width=n,this.eTopContainer.style.width=n,this.printLayout||(this.eBodyHorizontalScrollContainer.style.width=n)},e.prototype.setPinnedLeftWidth=function(){var t=this,e=this.pinningLeft,o=this.columnController.getDisplayedColumnsLeftWidth(),n=this.pinningLeft=!this.printLayout&&o>0,i=[this.eLeftContainer,this.eLeftTop,this.eLeftBottom];e!==n&&this.headerRootComp.setLeftVisible(n),i.forEach((function(e){return ke(e,t.pinningLeft)})),n&&i.forEach((function(t){return fo(t,o)}))},e.prototype.setPinnedRightWidth=function(){var t=this.pinningRight,e=this.columnController.getDisplayedColumnsRightWidth(),o=this.pinningRight=!this.printLayout&&e>0,n=[this.eRightContainer,this.eRightTop,this.eRightBottom];t!==o&&this.headerRootComp.setRightVisible(o),n.forEach((function(t){return ke(t,o)})),o&&n.forEach((function(t){return fo(t,e)}))},e.prototype.setPinnedContainerSize=function(){this.setPinnedLeftWidth(),this.setPinnedRightWidth(),this.setFakeHScrollSpacerWidths()},e.prototype.setFakeHScrollSpacerWidths=function(){var t=this.columnController.getDisplayedColumnsRightWidth(),e=!this.enableRtl&&this.isVerticalScrollShowing(),o=this.gridOptionsWrapper.getScrollbarWidth();e&&(t+=o),fo(this.eHorizontalRightSpacer,t),Ve(this.eHorizontalRightSpacer,"ag-scroller-corner",t<=o);var n=this.columnController.getDisplayedColumnsLeftWidth();this.enableRtl&&this.isVerticalScrollShowing()&&(n+=o),fo(this.eHorizontalLeftSpacer,n),Ve(this.eHorizontalLeftSpacer,"ag-scroller-corner",n<=o)},e.prototype.checkBodyHeight=function(){var t=Ke(this.eBodyViewport);if(this.bodyHeight!==t){this.bodyHeight=t;var e={type:Wt.EVENT_BODY_HEIGHT_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(e)}},e.prototype.setHeaderAndFloatingHeights=function(){var t,e,o,n=this,i=n.columnController,r=n.gridOptionsWrapper,s=n.pinnedRowModel,a=n.eTop,l=n.eBottom,p=0,u=i.getHeaderRowCount();i.isPivotMode()?(e=r.getPivotGroupHeaderHeight(),o=r.getPivotHeaderHeight()):(i.hasFloatingFilters()&&(u++,p=1),e=r.getGroupHeaderHeight(),o=r.getHeaderHeight());var c=u-(1+p);t=p*r.getFloatingFiltersHeight(),t+=c*e,t+=o,this.headerRootComp.setHeight(t);var d=s.getPinnedTopTotalHeight();d&&(d+=1);var h=s.getPinnedBottomTotalHeight();h&&(h+=1);var f=d+"px",g=h+"px";a.style.minHeight=f,a.style.height=f,a.style.display=d?"inherit":"none",l.style.minHeight=g,l.style.height=g,l.style.display=h?"inherit":"none",this.checkBodyHeight()},e.prototype.getBodyHeight=function(){return this.bodyHeight},e.prototype.setHorizontalScrollPosition=function(t){var e=this.eCenterViewport.scrollWidth-this.getCenterWidth();this.shouldBlockScrollUpdate("horizontal",t)&&(t=Math.min(Math.max(t,0),e)),this.eCenterViewport.scrollLeft=t,this.doHorizontalScroll(t)},e.prototype.setVerticalScrollPosition=function(t){this.eBodyViewport.scrollTop=t},e.prototype.scrollHorizontally=function(t){var e=this.eCenterViewport.scrollLeft;return this.setHorizontalScrollPosition(e+t),this.eCenterViewport.scrollLeft-e},e.prototype.scrollVertically=function(t){var e=this.eBodyViewport.scrollTop;return this.setVerticalScrollPosition(e+t),this.eBodyViewport.scrollTop-e},e.prototype.addScrollListener=function(){this.addManagedListener(this.eCenterViewport,"scroll",this.onCenterViewportScroll.bind(this)),this.addManagedListener(this.eBodyHorizontalScrollViewport,"scroll",this.onFakeHorizontalScroll.bind(this));var t=this.gridOptionsWrapper.isDebounceVerticalScrollbar()?$(this.onVerticalScroll.bind(this),100):this.onVerticalScroll.bind(this);this.addManagedListener(this.eBodyViewport,"scroll",t)},e.prototype.onVerticalScroll=function(){var t=this.eBodyViewport.scrollTop;this.shouldBlockScrollUpdate("vertical",t,!0)||(this.animationFrameService.setScrollTop(t),this.nextScrollTop=t,this.gridOptionsWrapper.isSuppressAnimationFrame()?(this.scrollTop=this.nextScrollTop,this.redrawRowsAfterScroll()):this.animationFrameService.schedule())},e.prototype.executeAnimationFrameScroll=function(){var t=this.scrollTop!=this.nextScrollTop;return t&&(this.scrollTop=this.nextScrollTop,this.redrawRowsAfterScroll()),t},e.prototype.shouldBlockScrollUpdate=function(t,e,o){if(void 0===o&&(o=!1),o&&!Ae())return!1;if("vertical"===t){var n=Ke(this.eBodyViewport),i=this.eBodyViewport.scrollHeight;if(e<0||e+n>i)return!0}if("horizontal"===t){var r=this.getCenterWidth(),s=this.eCenterViewport.scrollWidth;if(this.enableRtl&&Qe()){if(e>0)return!0}else if(e<0)return!0;if(Math.abs(e)+r>s)return!0}return!1},e.prototype.isControllingScroll=function(t){return this.lastHorizontalScrollElement?t===this.lastHorizontalScrollElement:(this.lastHorizontalScrollElement=t,!0)},e.prototype.onFakeHorizontalScroll=function(){this.isControllingScroll(this.eBodyHorizontalScrollViewport)&&this.onBodyHorizontalScroll(this.eBodyHorizontalScrollViewport)},e.prototype.onCenterViewportScroll=function(){this.isControllingScroll(this.eCenterViewport)&&this.onBodyHorizontalScroll(this.eCenterViewport)},e.prototype.onBodyHorizontalScroll=function(t){var e=this.eCenterViewport.scrollLeft;this.shouldBlockScrollUpdate("horizontal",e,!0)||(this.doHorizontalScroll(Math.floor($e(t,this.enableRtl))),this.resetLastHorizontalScrollElementDebounced())},e.prototype.resetLastHorizontalScrollElement=function(){this.lastHorizontalScrollElement=null},e.prototype.doHorizontalScroll=function(t){this.scrollLeft=t;var e={type:Wt.EVENT_BODY_SCROLL,api:this.gridApi,columnApi:this.columnApi,direction:"horizontal",left:this.scrollLeft,top:this.scrollTop};this.eventService.dispatchEvent(e),this.horizontallyScrollHeaderCenterAndFloatingCenter(t),this.onHorizontalViewportChanged()},e.prototype.redrawRowsAfterScroll=function(){var t={type:Wt.EVENT_BODY_SCROLL,direction:"vertical",api:this.gridApi,columnApi:this.columnApi,left:this.scrollLeft,top:this.scrollTop};this.eventService.dispatchEvent(t)},e.prototype.onHorizontalViewportChanged=function(){var t=this.getCenterWidth(),e=this.getCenterViewportScrollLeft();this.columnController.setViewportPosition(t,e)},e.prototype.getCenterViewportScrollLeft=function(){return $e(this.eCenterViewport,this.enableRtl)},e.prototype.setCenterViewportScrollLeft=function(t){Ze(this.eCenterViewport,t,this.enableRtl)},e.prototype.horizontallyScrollHeaderCenterAndFloatingCenter=function(t){void 0===t&&(t=this.getCenterViewportScrollLeft());var e=this.enableRtl?t:-t;this.headerRootComp.setHorizontalScroll(e),this.eBottomContainer.style.transform="translateX("+e+"px)",this.eTopContainer.style.transform="translateX("+e+"px)",Ze(this.lastHorizontalScrollElement===this.eCenterViewport?this.eBodyHorizontalScrollViewport:this.eCenterViewport,t,this.enableRtl)},e.prototype.addScrollEventListener=function(t){this.eBodyViewport.addEventListener("scroll",t)},e.prototype.removeScrollEventListener=function(t){this.eBodyViewport.removeEventListener("scroll",t)},ka([it("alignedGridsService")],e.prototype,"alignedGridsService",void 0),ka([it("rowRenderer")],e.prototype,"rowRenderer",void 0),ka([it("pinnedRowModel")],e.prototype,"pinnedRowModel",void 0),ka([it("animationFrameService")],e.prototype,"animationFrameService",void 0),ka([it("navigationService")],e.prototype,"navigationService",void 0),ka([it("autoHeightCalculator")],e.prototype,"autoHeightCalculator",void 0),ka([it("columnAnimationService")],e.prototype,"columnAnimationService",void 0),ka([it("autoWidthCalculator")],e.prototype,"autoWidthCalculator",void 0),ka([it("paginationAutoPageSizeService")],e.prototype,"paginationAutoPageSizeService",void 0),ka([it("beans")],e.prototype,"beans",void 0),ka([it("paginationProxy")],e.prototype,"paginationProxy",void 0),ka([it("columnApi")],e.prototype,"columnApi",void 0),ka([it("gridApi")],e.prototype,"gridApi",void 0),ka([it("dragService")],e.prototype,"dragService",void 0),ka([it("mouseEventService")],e.prototype,"mouseEventService",void 0),ka([it("$scope")],e.prototype,"$scope",void 0),ka([it("scrollVisibleService")],e.prototype,"scrollVisibleService",void 0),ka([it("valueService")],e.prototype,"valueService",void 0),ka([it("dragAndDropService")],e.prototype,"dragAndDropService",void 0),ka([it("maxDivHeightScaler")],e.prototype,"heightScaler",void 0),ka([it("resizeObserverService")],e.prototype,"resizeObserverService",void 0),ka([it("undoRedoService")],e.prototype,"undoRedoService",void 0),ka([it("columnController")],e.prototype,"columnController",void 0),ka([it("headerNavigationService")],e.prototype,"headerNavigationService",void 0),ka([it("popupService")],e.prototype,"popupService",void 0),ka([rt("rangeController")],e.prototype,"rangeController",void 0),ka([rt("contextMenuFactory")],e.prototype,"contextMenuFactory",void 0),ka([rt("menuFactory")],e.prototype,"menuFactory",void 0),ka([rt("clipboardService")],e.prototype,"clipboardService",void 0),ka([Wn("eBodyViewport")],e.prototype,"eBodyViewport",void 0),ka([Wn("eCenterContainer")],e.prototype,"eCenterContainer",void 0),ka([Wn("eCenterViewport")],e.prototype,"eCenterViewport",void 0),ka([Wn("eLeftContainer")],e.prototype,"eLeftContainer",void 0),ka([Wn("eRightContainer")],e.prototype,"eRightContainer",void 0),ka([Wn("eCenterColsClipper")],e.prototype,"eCenterColsClipper",void 0),ka([Wn("eHorizontalScrollBody")],e.prototype,"eHorizontalScrollBody",void 0),ka([Wn("eHorizontalLeftSpacer")],e.prototype,"eHorizontalLeftSpacer",void 0),ka([Wn("eHorizontalRightSpacer")],e.prototype,"eHorizontalRightSpacer",void 0),ka([Wn("eBodyHorizontalScrollViewport")],e.prototype,"eBodyHorizontalScrollViewport",void 0),ka([Wn("eBodyHorizontalScrollContainer")],e.prototype,"eBodyHorizontalScrollContainer",void 0),ka([Wn("eFullWidthContainer")],e.prototype,"eFullWidthContainer",void 0),ka([Wn("eTop")],e.prototype,"eTop",void 0),ka([Wn("eLeftTop")],e.prototype,"eLeftTop",void 0),ka([Wn("eRightTop")],e.prototype,"eRightTop",void 0),ka([Wn("eTopContainer")],e.prototype,"eTopContainer",void 0),ka([Wn("eTopViewport")],e.prototype,"eTopViewport",void 0),ka([Wn("eTopFullWidthContainer")],e.prototype,"eTopFullWidthContainer",void 0),ka([Wn("eBottom")],e.prototype,"eBottom",void 0),ka([Wn("eLeftBottom")],e.prototype,"eLeftBottom",void 0),ka([Wn("eRightBottom")],e.prototype,"eRightBottom",void 0),ka([Wn("eBottomContainer")],e.prototype,"eBottomContainer",void 0),ka([Wn("eBottomViewport")],e.prototype,"eBottomViewport",void 0),ka([Wn("eBottomFullWidthContainer")],e.prototype,"eBottomFullWidthContainer",void 0),ka([Wn("headerRoot")],e.prototype,"headerRootComp",void 0),ka([Wn("overlayWrapper")],e.prototype,"overlayWrapper",void 0),ka([et],e.prototype,"init",null)}(xn);!function(t){t.EVERYTHING="group",t.FILTER="filter",t.SORT="sort",t.MAP="map",t.AGGREGATE="aggregate",t.PIVOT="pivot",t.NOTHING="nothing"}(Pa||(Pa={}));
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
var Ba,ja=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Ua=(function(){function t(){this.detailGridInfoMap={},this.destroyCalled=!1}t.prototype.registerGridComp=function(t){this.gridPanel=t},t.prototype.registerGridCore=function(t){this.gridCore=t},t.prototype.registerHeaderRootComp=function(t){this.headerRootComp=t},t.prototype.init=function(){switch(this.rowModel.getType()){case ht.ROW_MODEL_TYPE_CLIENT_SIDE:this.clientSideRowModel=this.rowModel;break;case ht.ROW_MODEL_TYPE_INFINITE:this.infiniteRowModel=this.rowModel;break;case ht.ROW_MODEL_TYPE_SERVER_SIDE:this.serverSideRowModel=this.rowModel}},t.prototype.__getAlignedGridService=function(){return this.alignedGridsService},t.prototype.addDetailGridInfo=function(t,e){this.detailGridInfoMap[t]=e},t.prototype.removeDetailGridInfo=function(t){this.detailGridInfoMap[t]=void 0},t.prototype.getDetailGridInfo=function(t){return this.detailGridInfoMap[t]},t.prototype.forEachDetailGridInfo=function(t){var o=0;A(this.detailGridInfoMap,(function(n,i){e(i)&&(t(i,o),o++)}))},t.prototype.getDataAsCsv=function(t){if(ft.assertRegistered(pt.CsvExportModule,"api.getDataAsCsv"))return this.csvCreator.getDataAsCsv(t)},t.prototype.exportDataAsCsv=function(t){ft.assertRegistered(pt.CsvExportModule,"api.exportDataAsCSv")&&this.csvCreator.exportDataAsCsv(t)},t.prototype.getDataAsExcel=function(t){if(ft.assertRegistered(pt.ExcelExportModule,"api.getDataAsExcel"))return this.excelCreator.getDataAsExcel(t)},t.prototype.exportDataAsExcel=function(t){ft.assertRegistered(pt.ExcelExportModule,"api.exportDataAsExcel")&&this.excelCreator.exportDataAsExcel(t)},t.prototype.setEnterpriseDatasource=function(t){console.warn("ag-grid: since version 18.x, api.setEnterpriseDatasource() should be replaced with api.setServerSideDatasource()"),this.setServerSideDatasource(t)},t.prototype.setGridAriaProperty=function(t,e){if(t){var o=this.gridPanel.getGui(),n="aria-"+t;null===e?o.removeAttribute(n):o.setAttribute(n,e)}},t.prototype.setServerSideDatasource=function(t){this.serverSideRowModel?this.serverSideRowModel.setDatasource(t):console.warn("AG Grid: you can only use an enterprise datasource when gridOptions.rowModelType is '"+ht.ROW_MODEL_TYPE_SERVER_SIDE+"'")},t.prototype.setDatasource=function(t){this.gridOptionsWrapper.isRowModelInfinite()?this.rowModel.setDatasource(t):console.warn("AG Grid: you can only use a datasource when gridOptions.rowModelType is '"+ht.ROW_MODEL_TYPE_INFINITE+"'")},t.prototype.setViewportDatasource=function(t){this.gridOptionsWrapper.isRowModelViewport()?this.rowModel.setViewportDatasource(t):console.warn("AG Grid: you can only use a viewport datasource when gridOptions.rowModelType is '"+ht.ROW_MODEL_TYPE_VIEWPORT+"'")},t.prototype.setRowData=function(t){if(this.gridOptionsWrapper.isRowModelDefault())if(this.gridOptionsWrapper.isImmutableData()){var e=this.immutableService.createTransactionForRowData(t);if(!e)return;var o=e[0],n=e[1],i=this.clientSideRowModel.updateRowData(o,n);i&&this.rowRenderer.refreshFullWidthRows(i.update)}else this.selectionController.reset(),this.clientSideRowModel.setRowData(t);else console.warn("cannot call setRowData unless using normal row model")},t.prototype.setFloatingTopRowData=function(t){console.warn("AG Grid: since v12, api.setFloatingTopRowData() is now api.setPinnedTopRowData()"),this.setPinnedTopRowData(t)},t.prototype.setFloatingBottomRowData=function(t){console.warn("AG Grid: since v12, api.setFloatingBottomRowData() is now api.setPinnedBottomRowData()"),this.setPinnedBottomRowData(t)},t.prototype.getFloatingTopRowCount=function(){return console.warn("AG Grid: since v12, api.getFloatingTopRowCount() is now api.getPinnedTopRowCount()"),this.getPinnedTopRowCount()},t.prototype.getFloatingBottomRowCount=function(){return console.warn("AG Grid: since v12, api.getFloatingBottomRowCount() is now api.getPinnedBottomRowCount()"),this.getPinnedBottomRowCount()},t.prototype.getFloatingTopRow=function(t){return console.warn("AG Grid: since v12, api.getFloatingTopRow() is now api.getPinnedTopRow()"),this.getPinnedTopRow(t)},t.prototype.getFloatingBottomRow=function(t){return console.warn("AG Grid: since v12, api.getFloatingBottomRow() is now api.getPinnedBottomRow()"),this.getPinnedBottomRow(t)},t.prototype.setPinnedTopRowData=function(t){this.pinnedRowModel.setPinnedTopRowData(t)},t.prototype.setPinnedBottomRowData=function(t){this.pinnedRowModel.setPinnedBottomRowData(t)},t.prototype.getPinnedTopRowCount=function(){return this.pinnedRowModel.getPinnedTopRowCount()},t.prototype.getPinnedBottomRowCount=function(){return this.pinnedRowModel.getPinnedBottomRowCount()},t.prototype.getPinnedTopRow=function(t){return this.pinnedRowModel.getPinnedTopRow(t)},t.prototype.getPinnedBottomRow=function(t){return this.pinnedRowModel.getPinnedBottomRow(t)},t.prototype.setColumnDefs=function(t,e){void 0===e&&(e="api"),this.columnController.setColumnDefs(t,e)},t.prototype.setAutoGroupColumnDef=function(t,e){this.gridOptionsWrapper.setProperty("autoGroupColumnDef",t,!0)},t.prototype.expireValueCache=function(){this.valueCache.expire()},t.prototype.getVerticalPixelRange=function(){return this.gridPanel.getVScrollPosition()},t.prototype.getHorizontalPixelRange=function(){return this.gridPanel.getHScrollPosition()},t.prototype.setAlwaysShowHorizontalScroll=function(t){this.gridOptionsWrapper.setProperty("alwaysShowHorizontalScroll",t)},t.prototype.setAlwaysShowVerticalScroll=function(t){this.gridOptionsWrapper.setProperty("alwaysShowVerticalScroll",t)},t.prototype.refreshToolPanel=function(){this.gridCore.refreshSideBar()},t.prototype.refreshCells=function(t){void 0===t&&(t={}),Array.isArray(t)?console.warn("since AG Grid v11.1, refreshCells() now takes parameters, please see the documentation."):this.rowRenderer.refreshCells(t)},t.prototype.flashCells=function(t){void 0===t&&(t={}),this.rowRenderer.flashCells(t)},t.prototype.redrawRows=function(t){void 0===t&&(t={}),t&&t.rowNodes?this.rowRenderer.redrawRows(t.rowNodes):this.rowRenderer.redrawAfterModelUpdate()},t.prototype.timeFullRedraw=function(t){void 0===t&&(t=1);var e=0,o=0,n=0,i=this;!function r(){var s=(new Date).getTime();i.rowRenderer.redrawAfterModelUpdate();var a=(new Date).getTime();window.setTimeout((function(){var i=(new Date).getTime(),l=a-s,p=i-a;console.log("duration: processing = "+l+"ms, reflow = "+p+"ms"),e++,o+=l,n+=p,e<t?window.setTimeout(r,1e3):(console.log("tests complete. iteration count = "+e),console.log("average processing = "+o/e+"ms"),console.log("average reflow = "+n/e+"ms"))}),0)}()},t.prototype.refreshView=function(){console.warn("AG Grid: since v11.1, refreshView() is deprecated, please call refreshCells() or redrawRows() instead"),this.redrawRows()},t.prototype.refreshRows=function(t){console.warn("since AG Grid v11.1, refreshRows() is deprecated, please use refreshCells({rowNodes: rows}) or redrawRows({rowNodes: rows}) instead"),this.refreshCells({rowNodes:t})},t.prototype.rowDataChanged=function(t){console.warn("AG Grid: rowDataChanged is deprecated, either call refreshView() to refresh everything, or call rowNode.setRowData(newData) to set value on a particular node"),this.redrawRows()},t.prototype.softRefreshView=function(){console.error("AG Grid: since v16, softRefreshView() is no longer supported. Please check the documentation on how to refresh.")},t.prototype.refreshGroupRows=function(){console.warn("AG Grid: since v11.1, refreshGroupRows() is no longer supported, call refreshCells() instead. Because refreshCells() now does dirty checking, it will only refresh cells that have changed, so it should not be necessary to only refresh the group rows."),this.refreshCells()},t.prototype.setFunctionsReadOnly=function(t){this.gridOptionsWrapper.setProperty("functionsReadOnly",t)},t.prototype.refreshHeader=function(){this.headerRootComp.refreshHeader(),this.gridPanel.setHeaderAndFloatingHeights()},t.prototype.isAnyFilterPresent=function(){return this.filterManager.isAnyFilterPresent()},t.prototype.isAdvancedFilterPresent=function(){return console.warn("AG Grid: isAdvancedFilterPresent() is deprecated, please use isColumnFilterPresent()"),this.isColumnFilterPresent()},t.prototype.isColumnFilterPresent=function(){return this.filterManager.isAdvancedFilterPresent()},t.prototype.isQuickFilterPresent=function(){return this.filterManager.isQuickFilterPresent()},t.prototype.getModel=function(){return this.rowModel},t.prototype.setRowNodeExpanded=function(t,e){t&&t.setExpanded(e)},t.prototype.onGroupExpandedOrCollapsed=function(t){o(this.clientSideRowModel)&&console.warn("AG Grid: cannot call onGroupExpandedOrCollapsed unless using normal row model"),e(t)&&console.warn("AG Grid: api.onGroupExpandedOrCollapsed - refreshFromIndex parameter is no longer used, the grid will refresh all rows"),this.clientSideRowModel.refreshModel({step:Pa.MAP})},t.prototype.refreshInMemoryRowModel=function(t){console.warn("ag-grid: since version 18.x, api.refreshInMemoryRowModel() should be replaced with api.refreshClientSideRowModel()"),this.refreshClientSideRowModel(t)},t.prototype.refreshClientSideRowModel=function(t){o(this.clientSideRowModel)&&console.warn("cannot call refreshClientSideRowModel unless using normal row model");var n=Pa.EVERYTHING,i={group:Pa.EVERYTHING,filter:Pa.FILTER,map:Pa.MAP,aggregate:Pa.AGGREGATE,sort:Pa.SORT,pivot:Pa.PIVOT};if(e(t)&&(n=i[t]),o(n))console.error("AG Grid: invalid step "+t+", available steps are "+Object.keys(i).join(", "));else{var r={step:n,keepRenderedRows:!0,animate:!0,keepEditingRows:!0};this.clientSideRowModel.refreshModel(r)}},t.prototype.isAnimationFrameQueueEmpty=function(){return this.animationFrameService.isQueueEmpty()},t.prototype.getRowNode=function(t){return this.rowModel.getRowNode(t)},t.prototype.getSizesForCurrentTheme=function(){return{rowHeight:this.gridOptionsWrapper.getRowHeightAsNumber(),headerHeight:this.gridOptionsWrapper.getHeaderHeight()}},t.prototype.expandAll=function(){this.clientSideRowModel?this.clientSideRowModel.expandOrCollapseAll(!0):this.serverSideRowModel?this.serverSideRowModel.expandAll(!0):console.warn("AG Grid: expandAll only works with Client Side Row Model and Server Side Row Model")},t.prototype.collapseAll=function(){this.clientSideRowModel?this.clientSideRowModel.expandOrCollapseAll(!1):this.serverSideRowModel?this.serverSideRowModel.expandAll(!1):console.warn("AG Grid: collapseAll only works with Client Side Row Model and Server Side Row Model")},t.prototype.getToolPanelInstance=function(t){return this.gridCore.getToolPanelInstance(t)},t.prototype.addVirtualRowListener=function(t,e,o){"string"!=typeof t&&console.warn("AG Grid: addVirtualRowListener is deprecated, please use addRenderedRowListener."),this.addRenderedRowListener(t,e,o)},t.prototype.addRenderedRowListener=function(t,e,o){"virtualRowSelected"===t&&console.warn("AG Grid: event virtualRowSelected is deprecated, to register for individual row\n selection events, add a listener directly to the row node."),this.rowRenderer.addRenderedRowListener(t,e,o)},t.prototype.setQuickFilter=function(t){this.filterManager.setQuickFilter(t)},t.prototype.selectIndex=function(t,e,o){console.warn("AG Grid: do not use api for selection, call node.setSelected(value) instead"),o&&console.warn("AG Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it"),this.selectionController.selectIndex(t,e)},t.prototype.deselectIndex=function(t,e){void 0===e&&(e=!1),console.warn("AG Grid: do not use api for selection, call node.setSelected(value) instead"),e&&console.warn("AG Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it"),this.selectionController.deselectIndex(t)},t.prototype.selectNode=function(t,e,o){void 0===e&&(e=!1),void 0===o&&(o=!1),console.warn("AG Grid: API for selection is deprecated, call node.setSelected(value) instead"),o&&console.warn("AG Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it"),t.setSelectedParams({newValue:!0,clearSelection:!e})},t.prototype.deselectNode=function(t,e){void 0===e&&(e=!1),console.warn("AG Grid: API for selection is deprecated, call node.setSelected(value) instead"),e&&console.warn("AG Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it"),t.setSelectedParams({newValue:!1})},t.prototype.selectAll=function(){this.selectionController.selectAllRowNodes()},t.prototype.deselectAll=function(){this.selectionController.deselectAllRowNodes()},t.prototype.selectAllFiltered=function(){this.selectionController.selectAllRowNodes(!0)},t.prototype.deselectAllFiltered=function(){this.selectionController.deselectAllRowNodes(!0)},t.prototype.recomputeAggregates=function(){o(this.clientSideRowModel)&&console.warn("cannot call recomputeAggregates unless using normal row model"),console.warn("recomputeAggregates is deprecated, please call api.refreshClientSideRowModel('aggregate') instead"),this.clientSideRowModel.refreshModel({step:Pa.AGGREGATE})},t.prototype.sizeColumnsToFit=function(){this.gridPanel.sizeColumnsToFit()},t.prototype.showLoadingOverlay=function(){this.gridPanel.showLoadingOverlay()},t.prototype.showNoRowsOverlay=function(){this.gridPanel.showNoRowsOverlay()},t.prototype.hideOverlay=function(){this.gridPanel.hideOverlay()},t.prototype.isNodeSelected=function(t){return console.warn("AG Grid: no need to call api.isNodeSelected(), just call node.isSelected() instead"),t.isSelected()},t.prototype.getSelectedNodesById=function(){return console.error("AG Grid: since version 3.4, getSelectedNodesById no longer exists, use getSelectedNodes() instead"),null},t.prototype.getSelectedNodes=function(){return this.selectionController.getSelectedNodes()},t.prototype.getSelectedRows=function(){return this.selectionController.getSelectedRows()},t.prototype.getBestCostNodeSelection=function(){return this.selectionController.getBestCostNodeSelection()},t.prototype.getRenderedNodes=function(){return this.rowRenderer.getRenderedNodes()},t.prototype.ensureColIndexVisible=function(t){console.warn("AG Grid: ensureColIndexVisible(index) no longer supported, use ensureColumnVisible(colKey) instead.")},t.prototype.ensureColumnVisible=function(t){this.gridPanel.ensureColumnVisible(t)},t.prototype.ensureIndexVisible=function(t,e){this.gridPanel.ensureIndexVisible(t,e)},t.prototype.ensureNodeVisible=function(t,e){this.gridCore.ensureNodeVisible(t,e)},t.prototype.forEachLeafNode=function(t){o(this.clientSideRowModel)&&console.warn("cannot call forEachNode unless using normal row model"),this.clientSideRowModel.forEachLeafNode(t)},t.prototype.forEachNode=function(t){this.rowModel.forEachNode(t)},t.prototype.forEachNodeAfterFilter=function(t){o(this.clientSideRowModel)&&console.warn("cannot call forEachNodeAfterFilter unless using normal row model"),this.clientSideRowModel.forEachNodeAfterFilter(t)},t.prototype.forEachNodeAfterFilterAndSort=function(t){o(this.clientSideRowModel)&&console.warn("cannot call forEachNodeAfterFilterAndSort unless using normal row model"),this.clientSideRowModel.forEachNodeAfterFilterAndSort(t)},t.prototype.getFilterApiForColDef=function(t){return console.warn("ag-grid API method getFilterApiForColDef deprecated, use getFilterInstance instead"),this.getFilterInstance(t)},t.prototype.getFilterInstance=function(t,e){var o=this.columnController.getPrimaryColumn(t);if(o){var n=this.filterManager.getFilterComponent(o,"NO_UI"),i=n&&n.resolveNow(null,(function(t){return t}));return e&&(i?setTimeout(e,0,i):n&&n.then(e)),i}},t.prototype.getFilterApi=function(t){return console.warn("AG Grid: getFilterApi is deprecated, use getFilterInstance instead"),this.getFilterInstance(t)},t.prototype.destroyFilter=function(t){var e=this.columnController.getPrimaryColumn(t);if(e)return this.filterManager.destroyFilter(e,"filterDestroyed")},t.prototype.getStatusPanel=function(t){if(this.statusBarService)return this.statusBarService.getStatusPanel(t)},t.prototype.getColumnDef=function(t){var e=this.columnController.getPrimaryColumn(t);return e?e.getColDef():null},t.prototype.getColumnDefs=function(){return this.columnController.getColumnDefs()},t.prototype.onFilterChanged=function(){this.filterManager.onFilterChanged()},t.prototype.onSortChanged=function(){this.sortController.onSortChanged()},t.prototype.setSortModel=function(t,e){console.warn("AG Grid: as of version 24.0.0, setSortModel() is deprecated, sort information is now part of Column State. Please use columnApi.applyColumnState() instead.");var o=[];t&&t.forEach((function(t,e){o.push({colId:t.colId,sort:t.sort,sortIndex:e})})),this.columnController.applyColumnState({state:o,defaultState:{sort:null}})},t.prototype.getSortModel=function(){console.warn("AG Grid: as of version 24.0.0, getSortModel() is deprecated, sort information is now part of Column State. Please use columnApi.getColumnState() instead.");var t=this.columnController.getColumnState().filter((function(t){return null!=t.sort})),e={};t.forEach((function(t){var o=t.colId,n=t.sortIndex;e[o]=n}));var o=t.map((function(t){return{colId:t.colId,sort:t.sort}}));return o.sort((function(t,o){return e[t.colId]-e[o.colId]})),o},t.prototype.setFilterModel=function(t){this.filterManager.setFilterModel(t)},t.prototype.getFilterModel=function(){return this.filterManager.getFilterModel()},t.prototype.getFocusedCell=function(){return this.focusController.getFocusedCell()},t.prototype.clearFocusedCell=function(){return this.focusController.clearFocusedCell()},t.prototype.setFocusedCell=function(t,e,o){this.focusController.setFocusedCell(t,e,o,!0)},t.prototype.setSuppressRowDrag=function(t){this.gridOptionsWrapper.setProperty(zr.PROP_SUPPRESS_ROW_DRAG,t)},t.prototype.setSuppressMoveWhenRowDragging=function(t){this.gridOptionsWrapper.setProperty(zr.PROP_SUPPRESS_MOVE_WHEN_ROW_DRAG,t)},t.prototype.setSuppressRowClickSelection=function(t){this.gridOptionsWrapper.setProperty(zr.PROP_SUPPRESS_ROW_CLICK_SELECTION,t)},t.prototype.addRowDropZone=function(t){this.gridPanel.getRowDragFeature().addRowDropZone(t)},t.prototype.removeRowDropZone=function(t){var e=this.dragAndDropService.findExternalZone(t);e&&this.dragAndDropService.removeDropTarget(e)},t.prototype.getRowDropZoneParams=function(t){return this.gridPanel.getRowDragFeature().getRowDropZone(t)},t.prototype.setHeaderHeight=function(t){this.gridOptionsWrapper.setProperty(zr.PROP_HEADER_HEIGHT,t),this.doLayout()},t.prototype.setDomLayout=function(t){this.gridOptionsWrapper.setProperty(zr.PROP_DOM_LAYOUT,t)},t.prototype.setEnableCellTextSelection=function(t){this.gridPanel.setCellTextSelection(t)},t.prototype.setFillHandleDirection=function(t){this.gridOptionsWrapper.setProperty(zr.PROP_FILL_HANDLE_DIRECTION,t)},t.prototype.setGroupHeaderHeight=function(t){this.gridOptionsWrapper.setProperty(zr.PROP_GROUP_HEADER_HEIGHT,t),this.doLayout()},t.prototype.setFloatingFiltersHeight=function(t){this.gridOptionsWrapper.setProperty(zr.PROP_FLOATING_FILTERS_HEIGHT,t),this.doLayout()},t.prototype.setPivotGroupHeaderHeight=function(t){this.gridOptionsWrapper.setProperty(zr.PROP_PIVOT_GROUP_HEADER_HEIGHT,t),this.doLayout()},t.prototype.setPivotHeaderHeight=function(t){this.gridOptionsWrapper.setProperty(zr.PROP_PIVOT_HEADER_HEIGHT,t),this.doLayout()},t.prototype.isSideBarVisible=function(){return this.gridCore.isSideBarVisible()},t.prototype.setSideBarVisible=function(t){this.gridCore.setSideBarVisible(t)},t.prototype.setSideBarPosition=function(t){this.gridCore.setSideBarPosition(t)},t.prototype.openToolPanel=function(t){this.gridCore.openToolPanel(t)},t.prototype.closeToolPanel=function(){this.gridCore.closeToolPanel()},t.prototype.getOpenedToolPanel=function(){return this.gridCore.getOpenedToolPanel()},t.prototype.getSideBar=function(){return this.gridCore.getSideBar()},t.prototype.setSideBar=function(t){return this.gridCore.setSideBar(t)},t.prototype.setSuppressClipboardPaste=function(t){this.gridOptionsWrapper.setProperty(zr.PROP_SUPPRESS_CLIPBOARD_PASTE,t)},t.prototype.isToolPanelShowing=function(){return this.gridCore.isToolPanelShowing()},t.prototype.doLayout=function(){this.gridPanel.checkViewportAndScrolls()},t.prototype.resetRowHeights=function(){e(this.clientSideRowModel)&&this.clientSideRowModel.resetRowHeights()},t.prototype.setGroupRemoveSingleChildren=function(t){this.gridOptionsWrapper.setProperty(zr.PROP_GROUP_REMOVE_SINGLE_CHILDREN,t)},t.prototype.setGroupRemoveLowestSingleChildren=function(t){this.gridOptionsWrapper.setProperty(zr.PROP_GROUP_REMOVE_LOWEST_SINGLE_CHILDREN,t)},t.prototype.onRowHeightChanged=function(){this.clientSideRowModel?this.clientSideRowModel.onRowHeightChanged():this.serverSideRowModel&&this.serverSideRowModel.onRowHeightChanged()},t.prototype.getValue=function(t,e){var n=this.columnController.getPrimaryColumn(t);return o(n)&&(n=this.columnController.getGridColumn(t)),o(n)?null:this.valueService.getValue(n,e)},t.prototype.addEventListener=function(t,e){var o=this.gridOptionsWrapper.useAsyncEvents();this.eventService.addEventListener(t,e,o)},t.prototype.addGlobalListener=function(t){var e=this.gridOptionsWrapper.useAsyncEvents();this.eventService.addGlobalListener(t,e)},t.prototype.removeEventListener=function(t,e){var o=this.gridOptionsWrapper.useAsyncEvents();this.eventService.removeEventListener(t,e,o)},t.prototype.removeGlobalListener=function(t){var e=this.gridOptionsWrapper.useAsyncEvents();this.eventService.removeGlobalListener(t,e)},t.prototype.dispatchEvent=function(t){this.eventService.dispatchEvent(t)},t.prototype.destroy=function(){this.destroyCalled||(this.destroyCalled=!0,this.context.destroyBean(this.gridCore),this.context.destroy())},t.prototype.cleanDownReferencesToAvoidMemoryLeakInCaseApplicationIsKeepingReferenceToDestroyedGrid=function(){setTimeout(H.bind(window,this,"Grid API"),100)},t.prototype.warnIfDestroyed=function(t){return this.destroyCalled&&console.warn("AG Grid: Grid API method "+t+" was called on a grid that was destroyed."),this.destroyCalled},t.prototype.resetQuickFilter=function(){this.warnIfDestroyed("resetQuickFilter")||this.rowModel.forEachNode((function(t){return t.quickFilterAggregateText=null}))},t.prototype.getRangeSelections=function(){return console.warn("AG Grid: in v20.1.x, api.getRangeSelections() is gone, please use getCellRanges() instead.\n We had to change how cell selections works a small bit to allow charting to integrate. The return type of\n getCellRanges() is a bit different, please check the AG Grid documentation."),null},t.prototype.getCellRanges=function(){return this.rangeController?this.rangeController.getCellRanges():(console.warn("AG Grid: cell range selection is only available in AG Grid Enterprise"),null)},t.prototype.camelCaseToHumanReadable=function(t){return Yt(t)},t.prototype.addRangeSelection=function(t){console.warn("AG Grid: As of version 21.x, range selection changed slightly to allow charting integration. Please call api.addCellRange() instead of api.addRangeSelection()")},t.prototype.addCellRange=function(t){this.rangeController||console.warn("AG Grid: cell range selection is only available in AG Grid Enterprise"),this.rangeController.addCellRange(t)},t.prototype.clearRangeSelection=function(){this.rangeController||console.warn("AG Grid: cell range selection is only available in AG Grid Enterprise"),this.rangeController.removeAllCellRanges()},t.prototype.undoCellEditing=function(){this.undoRedoService.undo()},t.prototype.redoCellEditing=function(){this.undoRedoService.redo()},t.prototype.getCurrentUndoSize=function(){return this.undoRedoService.getCurrentUndoStackSize()},t.prototype.getCurrentRedoSize=function(){return this.undoRedoService.getCurrentRedoStackSize()},t.prototype.getChartModels=function(){if(ft.assertRegistered(pt.RangeSelectionModule,"api.getChartModels")&&ft.assertRegistered(pt.GridChartsModule,"api.getChartModels"))return this.chartService.getChartModels()},t.prototype.createRangeChart=function(t){if(ft.assertRegistered(pt.RangeSelectionModule,"api.createRangeChart")&&ft.assertRegistered(pt.GridChartsModule,"api.createRangeChart"))return this.chartService.createRangeChart(t)},t.prototype.createCrossFilterChart=function(t){if(ft.assertRegistered(pt.RangeSelectionModule,"api.createCrossFilterChart")&&ft.assertRegistered(pt.GridChartsModule,"api.createCrossFilterChart"))return this.chartService.createCrossFilterChart(t)},t.prototype.restoreChart=function(t,e){if(ft.assertRegistered(pt.RangeSelectionModule,"api.restoreChart")&&ft.assertRegistered(pt.GridChartsModule,"api.restoreChart"))return this.chartService.restoreChart(t,e)},t.prototype.createPivotChart=function(t){if(ft.assertRegistered(pt.RangeSelectionModule,"api.createPivotChart")&&ft.assertRegistered(pt.GridChartsModule,"api.createPivotChart"))return this.chartService.createPivotChart(t)},t.prototype.copySelectedRowsToClipboard=function(t,e){this.clipboardService||console.warn("AG Grid: clipboard is only available in AG Grid Enterprise"),this.clipboardService.copySelectedRowsToClipboard(t,e)},t.prototype.copySelectedRangeToClipboard=function(t){this.clipboardService||console.warn("AG Grid: clipboard is only available in AG Grid Enterprise"),this.clipboardService.copySelectedRangeToClipboard(t)},t.prototype.copySelectedRangeDown=function(){this.clipboardService||console.warn("AG Grid: clipboard is only available in AG Grid Enterprise"),this.clipboardService.copyRangeDown()},t.prototype.showColumnMenuAfterButtonClick=function(t,e){var o=this.columnController.getGridColumn(t);this.menuFactory.showMenuAfterButtonClick(o,e)},t.prototype.showColumnMenuAfterMouseClick=function(t,e){var o=this.columnController.getGridColumn(t);o||(o=this.columnController.getPrimaryColumn(t)),o?this.menuFactory.showMenuAfterMouseEvent(o,e):console.error("AG Grid: column '"+t+"' not found")},t.prototype.hidePopupMenu=function(){this.contextMenuFactory&&this.contextMenuFactory.hideActiveMenu(),this.menuFactory.hideActiveMenu()},t.prototype.setPopupParent=function(t){this.gridOptionsWrapper.setProperty(zr.PROP_POPUP_PARENT,t)},t.prototype.tabToNextCell=function(){return this.rowRenderer.tabToNextCell(!1)},t.prototype.tabToPreviousCell=function(){return this.rowRenderer.tabToNextCell(!0)},t.prototype.getCellRendererInstances=function(t){return void 0===t&&(t={}),this.rowRenderer.getCellRendererInstances(t)},t.prototype.getCellEditorInstances=function(t){return void 0===t&&(t={}),this.rowRenderer.getCellEditorInstances(t)},t.prototype.getEditingCells=function(){return this.rowRenderer.getEditingCells()},t.prototype.stopEditing=function(t){void 0===t&&(t=!1),this.rowRenderer.stopEditing(t)},t.prototype.startEditingCell=function(t){var e=this.columnController.getGridColumn(t.colKey);if(e){var n={rowIndex:t.rowIndex,rowPinned:t.rowPinned,column:e};o(t.rowPinned)&&this.gridPanel.ensureIndexVisible(t.rowIndex),this.rowRenderer.startEditingCell(n,t.keyPress,t.charPress)}else console.warn("AG Grid: no column found for "+t.colKey)},t.prototype.addAggFunc=function(t,e){this.aggFuncService&&this.aggFuncService.addAggFunc(t,e)},t.prototype.addAggFuncs=function(t){this.aggFuncService&&this.aggFuncService.addAggFuncs(t)},t.prototype.clearAggFuncs=function(){this.aggFuncService&&this.aggFuncService.clear()},t.prototype.applyServerSideTransaction=function(t){if(this.serverSideTransactionManager)return this.serverSideTransactionManager.applyTransaction(t);console.warn("AG Grid: Cannot apply Server Side Transaction if not using the Server Side Row Model.")},t.prototype.applyServerSideTransactionAsync=function(t,e){if(this.serverSideTransactionManager)return this.serverSideTransactionManager.applyTransactionAsync(t,e);console.warn("AG Grid: Cannot apply Server Side Transaction if not using the Server Side Row Model.")},t.prototype.retryServerSideLoads=function(){this.serverSideRowModel?this.serverSideRowModel.retryLoads():console.warn("AG Grid: API retryServerSideLoads() can only be used when using Server-Side Row Model.")},t.prototype.flushServerSideAsyncTransactions=function(){if(this.serverSideTransactionManager)return this.serverSideTransactionManager.flushAsyncTransactions();console.warn("AG Grid: Cannot flush Server Side Transaction if not using the Server Side Row Model.")},t.prototype.applyTransaction=function(t){if(this.clientSideRowModel){var e=this.clientSideRowModel.updateRowData(t);return this.rowRenderer.refreshFullWidthRows(e.update),this.gridOptionsWrapper.isSuppressChangeDetection()||this.rowRenderer.refreshCells(),e}console.error("AG Grid: updateRowData() only works with ClientSideRowModel. Working with InfiniteRowModel was deprecated in v23.1 and removed in v24.1")},t.prototype.updateRowData=function(t){return z((function(){return console.warn("AG Grid: as of v23.1, grid API updateRowData(transaction) is now called applyTransaction(transaction). updateRowData is deprecated and will be removed in a future major release.")}),"updateRowData deprecated"),this.applyTransaction(t)},t.prototype.applyTransactionAsync=function(t,e){this.clientSideRowModel?this.clientSideRowModel.batchUpdateRowData(t,e):console.error("AG Grid: api.applyTransactionAsync() only works with ClientSideRowModel.")},t.prototype.flushAsyncTransactions=function(){this.clientSideRowModel?this.clientSideRowModel.flushAsyncTransactions():console.error("AG Grid: api.applyTransactionAsync() only works with ClientSideRowModel.")},t.prototype.batchUpdateRowData=function(t,e){z((function(){return console.warn("AG Grid: as of v23.1, grid API batchUpdateRowData(transaction, callback) is now called applyTransactionAsync(transaction, callback). batchUpdateRowData is deprecated and will be removed in a future major release.")}),"batchUpdateRowData deprecated"),this.applyTransactionAsync(t,e)},t.prototype.insertItemsAtIndex=function(t,e,o){console.warn("AG Grid: insertItemsAtIndex() is deprecated, use updateRowData(transaction) instead."),this.updateRowData({add:e,addIndex:t,update:null,remove:null})},t.prototype.removeItems=function(t,e){console.warn("AG Grid: removeItems() is deprecated, use updateRowData(transaction) instead.");var o=t.map((function(t){return t.data}));this.updateRowData({add:null,addIndex:null,update:null,remove:o})},t.prototype.addItems=function(t,e){console.warn("AG Grid: addItems() is deprecated, use updateRowData(transaction) instead."),this.updateRowData({add:t,addIndex:null,update:null,remove:null})},t.prototype.refreshVirtualPageCache=function(){console.warn("AG Grid: refreshVirtualPageCache() is now called refreshInfiniteCache(), please call refreshInfiniteCache() instead"),this.refreshInfiniteCache()},t.prototype.refreshInfinitePageCache=function(){console.warn("AG Grid: refreshInfinitePageCache() is now called refreshInfiniteCache(), please call refreshInfiniteCache() instead"),this.refreshInfiniteCache()},t.prototype.refreshInfiniteCache=function(){this.infiniteRowModel?this.infiniteRowModel.refreshCache():console.warn("AG Grid: api.refreshInfiniteCache is only available when rowModelType='infinite'.")},t.prototype.purgeVirtualPageCache=function(){console.warn("AG Grid: purgeVirtualPageCache() is now called purgeInfiniteCache(), please call purgeInfiniteCache() instead"),this.purgeInfinitePageCache()},t.prototype.purgeInfinitePageCache=function(){console.warn("AG Grid: purgeInfinitePageCache() is now called purgeInfiniteCache(), please call purgeInfiniteCache() instead"),this.purgeInfiniteCache()},t.prototype.purgeInfiniteCache=function(){this.infiniteRowModel?this.infiniteRowModel.purgeCache():console.warn("AG Grid: api.purgeInfiniteCache is only available when rowModelType='infinite'.")},t.prototype.purgeEnterpriseCache=function(t){console.warn("ag-grid: since version 18.x, api.purgeEnterpriseCache() should be replaced with api.purgeServerSideCache()"),this.purgeServerSideCache(t)},t.prototype.purgeServerSideCache=function(t){void 0===t&&(t=[]),this.serverSideRowModel?(console.warn("AG Grid: since v25.0, api.purgeServerSideCache is deprecated. Please use api.refreshServerSideStore({purge: true}) instead."),this.refreshServerSideStore({route:t,purge:!0})):console.warn("AG Grid: api.purgeServerSideCache is only available when rowModelType='serverSide'.")},t.prototype.refreshServerSideStore=function(t){this.serverSideRowModel?this.serverSideRowModel.refreshStore(t):console.warn("AG Grid: api.refreshServerSideStore is only available when rowModelType='serverSide'.")},t.prototype.getServerSideStoreState=function(){return this.serverSideRowModel?this.serverSideRowModel.getStoreState():(console.warn("AG Grid: api.getServerSideStoreState is only available when rowModelType='serverSide'."),[])},t.prototype.getVirtualRowCount=function(){return console.warn("AG Grid: getVirtualRowCount() is now called getInfiniteRowCount(), please call getInfiniteRowCount() instead"),this.getInfiniteRowCount()},t.prototype.getInfiniteRowCount=function(){if(this.infiniteRowModel)return this.infiniteRowModel.getRowCount();console.warn("AG Grid: api.getVirtualRowCount is only available when rowModelType='virtual'.")},t.prototype.isMaxRowFound=function(){return console.warn("AG Grid: api.isLastRowIndexKnown is deprecated, please use api.isLastRowIndexKnown()"),this.isLastRowIndexKnown()},t.prototype.isLastRowIndexKnown=function(){if(this.infiniteRowModel)return this.infiniteRowModel.isLastRowIndexKnown();console.warn("AG Grid: api.isMaxRowFound is only available when rowModelType='virtual'.")},t.prototype.setVirtualRowCount=function(t,e){console.warn("AG Grid: setVirtualRowCount() is now called setInfiniteRowCount(), please call setInfiniteRowCount() instead"),this.setRowCount(t,e)},t.prototype.setInfiniteRowCount=function(t,e){console.warn("AG Grid: setInfiniteRowCount() is now called setRowCount(), please call setRowCount() instead"),this.setRowCount(t,e)},t.prototype.setRowCount=function(t,e){this.infiniteRowModel?this.infiniteRowModel.setRowCount(t,e):console.warn("AG Grid: api.setRowCount is only available for Infinite Row Model.")},t.prototype.getVirtualPageState=function(){return console.warn("AG Grid: getVirtualPageState() is now called getCacheBlockState(), please call getCacheBlockState() instead"),this.getCacheBlockState()},t.prototype.getInfinitePageState=function(){return console.warn("AG Grid: getInfinitePageState() is now called getCacheBlockState(), please call getCacheBlockState() instead"),this.getCacheBlockState()},t.prototype.getCacheBlockState=function(){return this.rowNodeBlockLoader.getBlockState()},t.prototype.checkGridSize=function(){this.gridPanel.setHeaderAndFloatingHeights()},t.prototype.getFirstRenderedRow=function(){return console.warn("in AG Grid v12, getFirstRenderedRow() was renamed to getFirstDisplayedRow()"),this.getFirstDisplayedRow()},t.prototype.getFirstDisplayedRow=function(){return this.rowRenderer.getFirstVirtualRenderedRow()},t.prototype.getLastRenderedRow=function(){return console.warn("in AG Grid v12, getLastRenderedRow() was renamed to getLastDisplayedRow()"),this.getLastDisplayedRow()},t.prototype.getLastDisplayedRow=function(){return this.rowRenderer.getLastVirtualRenderedRow()},t.prototype.getDisplayedRowAtIndex=function(t){return this.rowModel.getRow(t)},t.prototype.getDisplayedRowCount=function(){return this.rowModel.getRowCount()},t.prototype.paginationIsLastPageFound=function(){return this.paginationProxy.isLastPageFound()},t.prototype.paginationGetPageSize=function(){return this.paginationProxy.getPageSize()},t.prototype.paginationSetPageSize=function(t){this.gridOptionsWrapper.setProperty("paginationPageSize",t)},t.prototype.paginationGetCurrentPage=function(){return this.paginationProxy.getCurrentPage()},t.prototype.paginationGetTotalPages=function(){return this.paginationProxy.getTotalPages()},t.prototype.paginationGetRowCount=function(){return this.paginationProxy.getMasterRowCount()},t.prototype.paginationGoToNextPage=function(){this.paginationProxy.goToNextPage()},t.prototype.paginationGoToPreviousPage=function(){this.paginationProxy.goToPreviousPage()},t.prototype.paginationGoToFirstPage=function(){this.paginationProxy.goToFirstPage()},t.prototype.paginationGoToLastPage=function(){this.paginationProxy.goToLastPage()},t.prototype.paginationGoToPage=function(t){this.paginationProxy.goToPage(t)},ja([rt("immutableService")],t.prototype,"immutableService",void 0),ja([rt("csvCreator")],t.prototype,"csvCreator",void 0),ja([rt("excelCreator")],t.prototype,"excelCreator",void 0),ja([it("rowRenderer")],t.prototype,"rowRenderer",void 0),ja([it("filterManager")],t.prototype,"filterManager",void 0),ja([it("columnController")],t.prototype,"columnController",void 0),ja([it("selectionController")],t.prototype,"selectionController",void 0),ja([it("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),ja([it("valueService")],t.prototype,"valueService",void 0),ja([it("alignedGridsService")],t.prototype,"alignedGridsService",void 0),ja([it("eventService")],t.prototype,"eventService",void 0),ja([it("pinnedRowModel")],t.prototype,"pinnedRowModel",void 0),ja([it("context")],t.prototype,"context",void 0),ja([it("rowModel")],t.prototype,"rowModel",void 0),ja([it("sortController")],t.prototype,"sortController",void 0),ja([it("paginationProxy")],t.prototype,"paginationProxy",void 0),ja([it("focusController")],t.prototype,"focusController",void 0),ja([it("dragAndDropService")],t.prototype,"dragAndDropService",void 0),ja([rt("rangeController")],t.prototype,"rangeController",void 0),ja([rt("clipboardService")],t.prototype,"clipboardService",void 0),ja([rt("aggFuncService")],t.prototype,"aggFuncService",void 0),ja([it("menuFactory")],t.prototype,"menuFactory",void 0),ja([rt("contextMenuFactory")],t.prototype,"contextMenuFactory",void 0),ja([it("valueCache")],t.prototype,"valueCache",void 0),ja([it("animationFrameService")],t.prototype,"animationFrameService",void 0),ja([rt("statusBarService")],t.prototype,"statusBarService",void 0),ja([rt("chartService")],t.prototype,"chartService",void 0),ja([rt("undoRedoService")],t.prototype,"undoRedoService",void 0),ja([rt("rowNodeBlockLoader")],t.prototype,"rowNodeBlockLoader",void 0),ja([rt("ssrmTransactionManager")],t.prototype,"serverSideTransactionManager",void 0),ja([et],t.prototype,"init",null),ja([ot],t.prototype,"cleanDownReferencesToAvoidMemoryLeakInCaseApplicationIsKeepingReferenceToDestroyedGrid",null),t=ja([nt("gridApi")],t)}(),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),za=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Ka=function(t,e){return function(o,n){e(o,n,t)}},Ya=(function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.expressionToFunctionCache={},e}Ua(e,t),e.prototype.setBeans=function(t){this.logger=t.create("ExpressionService")},e.prototype.evaluate=function(t,e){if("function"==typeof t)return t(e);if("string"==typeof t){var o=t;return this.evaluateExpression(o,e)}console.error("AG Grid: value should be either a string or a function",t)},e.prototype.evaluateExpression=function(t,e){try{return this.createExpressionFunction(t)(e.value,e.context,e.oldValue,e.newValue,e.value,e.node,e.data,e.colDef,e.rowIndex,e.api,e.columnApi,e.getValue,e.column,e.columnGroup)}catch(o){return console.log("Processing of the expression failed"),console.log("Expression = "+t),console.log("Params =",e),console.log("Exception = "+o),null}},e.prototype.createExpressionFunction=function(t){if(this.expressionToFunctionCache[t])return this.expressionToFunctionCache[t];var e=this.createFunctionBody(t),o=new Function("x, ctx, oldValue, newValue, value, node, data, colDef, rowIndex, api, columnApi, getValue, column, columnGroup",e);return this.expressionToFunctionCache[t]=o,o},e.prototype.createFunctionBody=function(t){return t.indexOf("return")>=0?t:"return "+t+";"},za([Ka(0,at("loggerFactory"))],e.prototype,"setBeans",null),e=za([nt("expressionService")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),qa=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Xa=(function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.templateCache={},e.waitingCallbacks={},e}Ya(e,t),e.prototype.getTemplate=function(t,e){var o=this.templateCache[t];if(o)return o;var n=this.waitingCallbacks[t],i=this;if(!n){n=[],this.waitingCallbacks[t]=n;var r=new XMLHttpRequest;r.onload=function(){i.handleHttpResult(this,t)},r.open("GET",t),r.send()}return e&&n.push(e),null},e.prototype.handleHttpResult=function(t,e){if(200===t.status&&null!==t.response){this.templateCache[e]=t.response||t.responseText;for(var o=this.waitingCallbacks[e],n=0;n<o.length;n++){(0,o[n])()}if(this.$scope){var i=this;window.setTimeout((function(){i.$scope.$apply()}),0)}}else console.warn("Unable to get template error "+t.status+" - "+e)},qa([it("$scope")],e.prototype,"$scope",void 0),e=qa([nt("templateService")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Qa=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},$a=function(){for(var t=0,e=0,o=arguments.length;e<o;e++)t+=arguments[e].length;var n=Array(t),i=0;for(e=0;e<o;e++)for(var r=arguments[e],s=0,a=r.length;s<a;s++,i++)n[i]=r[s];return n},Za=function(e){function o(){return null!==e&&e.apply(this,arguments)||this}var n;return Xa(o,e),n=o,o.addKeyboardModeEvents=function(t,e){var o=n.instancesMonitored.get(t);o&&o.length>0?-1===o.indexOf(e)&&o.push(e):(n.instancesMonitored.set(t,[e]),t.addEventListener("keydown",n.toggleKeyboardMode),t.addEventListener("mousedown",n.toggleKeyboardMode))},o.removeKeyboardModeEvents=function(t,e){var o=n.instancesMonitored.get(t),i=[];o&&o.length&&(i=$a(o).filter((function(t){return t!==e})),n.instancesMonitored.set(t,i)),0===i.length&&(t.removeEventListener("keydown",n.toggleKeyboardMode),t.removeEventListener("mousedown",n.toggleKeyboardMode))},o.toggleKeyboardMode=function(t){var e=n.keyboardModeActive,o="keydown"===t.type;if(!(o&&(t.ctrlKey||t.metaKey||t.altKey)||e&&o||!e&&!o)){n.keyboardModeActive=o;var i=t.target.ownerDocument;if(i){var r=n.instancesMonitored.get(i);r&&r.forEach((function(t){t.dispatchEvent({type:o?Wt.EVENT_KEYBOARD_FOCUS:Wt.EVENT_MOUSE_FOCUS})}))}}},o.prototype.init=function(){var t=this.clearFocusedCell.bind(this);this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_PIVOT_MODE_CHANGED,t),this.addManagedListener(this.eventService,Wt.EVENT_NEW_COLUMNS_LOADED,this.onColumnEverythingChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_GROUP_OPENED,t),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_ROW_GROUP_CHANGED,t)},o.prototype.registerGridCore=function(t){var e=this;this.gridCore=t;var o=this.gridOptionsWrapper.getDocument();n.addKeyboardModeEvents(o,t),this.addDestroyFunc((function(){return e.unregisterGridCore(t)}))},o.prototype.unregisterGridCore=function(t){var e=this.gridOptionsWrapper.getDocument();n.removeKeyboardModeEvents(e,t)},o.prototype.onColumnEverythingChanged=function(){if(this.focusedCellPosition){var t=this.focusedCellPosition.column,e=this.columnController.getGridColumn(t.getId());t!==e&&this.clearFocusedCell()}},o.prototype.isKeyboardMode=function(){return n.keyboardModeActive},o.prototype.getFocusCellToUseAfterRefresh=function(){return this.gridOptionsWrapper.isSuppressFocusAfterRefresh()||!this.focusedCellPosition?null:this.getGridCellForDomElement(document.activeElement)?this.focusedCellPosition:null},o.prototype.getGridCellForDomElement=function(t){for(var e=t;e;){var o=this.gridOptionsWrapper.getDomData(e,vs.DOM_DATA_KEY_CELL_COMP);if(o)return o.getCellPosition();e=e.parentNode}return null},o.prototype.clearFocusedCell=function(){this.focusedCellPosition=null,this.onCellFocused(!1)},o.prototype.getFocusedCell=function(){return this.focusedCellPosition},o.prototype.setFocusedCell=function(e,o,n,i){void 0===i&&(i=!1);var r=this.columnController.getGridColumn(o);r?(this.focusedCellPosition=r?{rowIndex:e,rowPinned:t(n),column:r}:null,this.onCellFocused(i)):this.focusedCellPosition=null},o.prototype.isCellFocused=function(t){return null!=this.focusedCellPosition&&(this.focusedCellPosition.column===t.column&&this.isRowFocused(t.rowIndex,t.rowPinned))},o.prototype.isRowNodeFocused=function(t){return this.isRowFocused(t.rowIndex,t.rowPinned)},o.prototype.isHeaderWrapperFocused=function(t){if(null==this.focusedHeaderPosition)return!1;var e=t.getColumn(),o=t.getParentComponent().getRowIndex(),n=t.getPinned(),i=this.focusedHeaderPosition,r=i.column,s=i.headerRowIndex;return e===r&&o===s&&n==r.getPinned()},o.prototype.clearFocusedHeader=function(){this.focusedHeaderPosition=null},o.prototype.getFocusedHeader=function(){return this.focusedHeaderPosition},o.prototype.setFocusedHeader=function(t,e){this.focusedHeaderPosition={headerRowIndex:t,column:e}},o.prototype.focusHeaderPosition=function(t,e,o,n,i){if(void 0===e&&(e=null),void 0===o&&(o=!1),void 0===n&&(n=!1),n){var r,s=this.gridOptionsWrapper,a=this.getFocusedHeader(),l=this.headerNavigationService.getHeaderRowCount();if(o){if(r=s.getTabToNextHeaderFunc())t=r({backwards:"Before"===e,previousHeaderPosition:a,nextHeaderPosition:t,headerRowCount:l})}else if((r=s.getNavigateToNextHeaderFunc())&&i)t=r({key:i.key,previousHeaderPosition:a,nextHeaderPosition:t,headerRowCount:l,event:i})}if(!t)return!1;if(-1===t.headerRowIndex)return this.focusGridView(t.column);this.headerNavigationService.scrollToColumn(t.column,e);var p=this.headerNavigationService.getHeaderContainer(t.column.getPinned()).getRowComps()[t.headerRowIndex].getHeaderComps()[t.column.getUniqueId()];return!!p&&(p.getFocusableElement().focus(),!0)},o.prototype.isAnyCellFocused=function(){return!!this.focusedCellPosition},o.prototype.isRowFocused=function(e,o){return null!=this.focusedCellPosition&&(this.focusedCellPosition.rowIndex===e&&this.focusedCellPosition.rowPinned===t(o))},o.prototype.findFocusableElements=function(t,e,o){void 0===o&&(o=!1);var n=ht.FOCUSABLE_SELECTOR,i=ht.FOCUSABLE_EXCLUDE;e&&(i+=", "+e),o&&(i+=', [tabindex="-1"]');var r=Array.prototype.slice.apply(t.querySelectorAll(n)),s=Array.prototype.slice.apply(t.querySelectorAll(i));if(!s.length)return r;var a;return a=s,r.filter((function(t){return-1===a.indexOf(t)}))},o.prototype.focusInto=function(t,e,o){void 0===e&&(e=!1),void 0===o&&(o=!1);var n=this.findFocusableElements(t,null,o),i=e?d(n):n[0];return!!i&&(i.focus(),!0)},o.prototype.findNextFocusableElement=function(t,e,o){var n=this.findFocusableElements(t,e?':not([tabindex="-1"])':null),i=(e?E(n,(function(t){return t.contains(document.activeElement)})):n.indexOf(document.activeElement))+(o?-1:1);return i<0||i>=n.length?null:n[i]},o.prototype.isFocusUnderManagedComponent=function(t){var e=t.querySelectorAll("."+Zn.FOCUS_MANAGED_CLASS);if(!e.length)return!1;for(var o=0;o<e.length;o++)if(e[o].contains(document.activeElement))return!0;return!1},o.prototype.findTabbableParent=function(t,e){void 0===e&&(e=5);for(var o=0;t&&null===Te(t)&&++o<=e;)t=t.parentElement;return null===Te(t)?null:t},o.prototype.onCellFocused=function(t){var e={type:Wt.EVENT_CELL_FOCUSED,forceBrowserFocus:t,rowIndex:null,column:null,floating:null,api:this.gridApi,columnApi:this.columnApi,rowPinned:null};this.focusedCellPosition&&(e.rowIndex=this.focusedCellPosition.rowIndex,e.column=this.focusedCellPosition.column,e.rowPinned=this.focusedCellPosition.rowPinned),this.eventService.dispatchEvent(e)},o.prototype.focusGridView=function(e,o){var n=o?this.rowPositionUtils.getLastRow():this.rowPositionUtils.getFirstRow();if(!n)return!1;var i=n.rowIndex,r=n.rowPinned,s=this.getFocusedHeader();if(!e&&s&&(e=s.column),null==i||!e)return!1;if(this.rowRenderer.ensureCellVisible({rowIndex:i,column:e,rowPinned:r}),this.setFocusedCell(i,e,t(r),!0),this.rangeController){var a={rowIndex:i,rowPinned:r,column:e};this.rangeController.setRangeToCell(a)}return!0},o.prototype.focusNextGridCoreContainer=function(t){return!!this.gridCore.focusNextInnerContainer(t)||(t||this.gridCore.forceFocusOutOfContainer(),!1)},o.AG_KEYBOARD_FOCUS="ag-keyboard-focus",o.keyboardModeActive=!1,o.instancesMonitored=new Map,Qa([it("columnController")],o.prototype,"columnController",void 0),Qa([it("headerNavigationService")],o.prototype,"headerNavigationService",void 0),Qa([it("columnApi")],o.prototype,"columnApi",void 0),Qa([it("gridApi")],o.prototype,"gridApi",void 0),Qa([it("rowRenderer")],o.prototype,"rowRenderer",void 0),Qa([it("rowPositionUtils")],o.prototype,"rowPositionUtils",void 0),Qa([rt("rangeController")],o.prototype,"rangeController",void 0),Qa([et],o.prototype,"init",null),o=n=Qa([nt("focusController")],o)}(Mt),Ja=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),tl=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},el=(function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.popupList=[],e}Ja(e,t),e.prototype.registerGridCore=function(t){var e=this;this.gridCore=t,this.addManagedListener(this.gridCore,Wt.EVENT_KEYBOARD_FOCUS,(function(){P(e.popupList,(function(t){return Me(t.element,Za.AG_KEYBOARD_FOCUS)}))})),this.addManagedListener(this.gridCore,Wt.EVENT_MOUSE_FOCUS,(function(){P(e.popupList,(function(t){return xe(t.element,Za.AG_KEYBOARD_FOCUS)}))}))},e.prototype.getPopupParent=function(){var t=this.gridOptionsWrapper.getPopupParent();return t||this.gridCore.getRootGui()},e.prototype.positionPopupForMenu=function(t){var e=t.eventSource.getBoundingClientRect(),o=this.getParentRect(),n=this.keepYWithinBounds(t,e.top-o.top),i=t.ePopup.clientWidth>0?t.ePopup.clientWidth:200;t.ePopup.style.minWidth=i+"px";var r,s=o.right-o.left-i;function a(){return e.right-o.left-2}function l(){return e.left-o.left-i}this.gridOptionsWrapper.isEnableRtl()?((r=l())<0&&(r=a()),r>s&&(r=0)):((r=a())>s&&(r=l()),r<0&&(r=0)),t.ePopup.style.left=r+"px",t.ePopup.style.top=n+"px"},e.prototype.positionPopupUnderMouseEvent=function(t){var e=this.calculatePointerAlign(t.mouseEvent),o=e.x,n=e.y,i=t.ePopup,r=t.nudgeX,s=t.nudgeY;this.positionPopup({ePopup:i,x:o,y:n,nudgeX:r,nudgeY:s,keepWithinBounds:!0}),this.callPostProcessPopup(t.type,t.ePopup,null,t.mouseEvent,t.column,t.rowNode)},e.prototype.calculatePointerAlign=function(t){var e=this.getParentRect();return{x:t.clientX-e.left,y:t.clientY-e.top}},e.prototype.positionPopupUnderComponent=function(t){var e=t.eventSource.getBoundingClientRect(),o=t.alignSide||"left",n=this.getParentRect(),i=e.left-n.left;"right"===o&&(i-=t.ePopup.offsetWidth-e.width),this.positionPopup({ePopup:t.ePopup,minWidth:t.minWidth,minHeight:t.minHeight,nudgeX:t.nudgeX,nudgeY:t.nudgeY,x:i,y:e.top-n.top+e.height,keepWithinBounds:t.keepWithinBounds}),this.callPostProcessPopup(t.type,t.ePopup,t.eventSource,null,t.column,t.rowNode)},e.prototype.positionPopupOverComponent=function(t){var e=t.eventSource.getBoundingClientRect(),o=this.getParentRect();this.positionPopup({ePopup:t.ePopup,minWidth:t.minWidth,nudgeX:t.nudgeX,nudgeY:t.nudgeY,x:e.left-o.left,y:e.top-o.top,keepWithinBounds:t.keepWithinBounds}),this.callPostProcessPopup(t.type,t.ePopup,t.eventSource,null,t.column,t.rowNode)},e.prototype.callPostProcessPopup=function(t,e,o,n,i,r){var s=this.gridOptionsWrapper.getPostProcessPopupFunc();s&&s({column:i,rowNode:r,ePopup:e,type:t,eventSource:o,mouseEvent:n})},e.prototype.positionPopup=function(t){var e=t.x,o=t.y;t.nudgeX&&(e+=t.nudgeX),t.nudgeY&&(o+=t.nudgeY),t.keepWithinBounds&&(e=this.keepXWithinBounds(t,e),o=this.keepYWithinBounds(t,o)),t.ePopup.style.left=e+"px",t.ePopup.style.top=o+"px"},e.prototype.getActivePopups=function(){return this.popupList.map((function(t){return t.element}))},e.prototype.getParentRect=function(){var t=this.getPopupParent(),e=this.gridOptionsWrapper.getDocument();t===e.body&&(t=e.documentElement);var o=getComputedStyle(t),n=t.getBoundingClientRect();return{top:n.top+parseFloat(o.borderTopWidth)||0,left:n.left+parseFloat(o.borderLeftWidth)||0,right:n.right+parseFloat(o.borderRightWidth)||0,bottom:n.bottom+parseFloat(o.borderBottomWidth)||0}},e.prototype.keepYWithinBounds=function(t,e){var o=this.gridOptionsWrapper.getDocument(),n=o.documentElement,i=this.getPopupParent(),r=i.getBoundingClientRect(),s=o.documentElement.getBoundingClientRect(),a=i===o.body,l=Math.min(200,r.height),p=0;t.minHeight&&t.minHeight<l?l=t.minHeight:t.ePopup.offsetHeight>0&&(l=t.ePopup.clientHeight,p=qe(t.ePopup)-l);var u=a?qe(n)+n.scrollTop:r.height;a&&(u-=Math.abs(s.top-r.top));var c=u-l-p;return Math.min(Math.max(e,0),Math.abs(c))},e.prototype.keepXWithinBounds=function(t,e){var o=this.gridOptionsWrapper.getDocument(),n=o.documentElement,i=this.getPopupParent(),r=i.getBoundingClientRect(),s=o.documentElement.getBoundingClientRect(),a=i===o.body,l=t.ePopup,p=Math.min(200,r.width),u=0;t.minWidth&&t.minWidth<p?p=t.minWidth:l.offsetWidth>0&&(p=l.offsetWidth,l.style.minWidth=p+"px",u=Xe(l)-p);var c=a?Xe(n)+n.scrollLeft:r.width;a&&(c-=Math.abs(s.left-r.left));var d=c-p-u;return Math.min(Math.max(e,0),Math.abs(d))},e.prototype.keepPopupPositionedRelativeTo=function(t){var e=this.getPopupParent(),o=e.getBoundingClientRect(),n=t.element.getBoundingClientRect(),i=o.top-n.top,r=o.left-n.left,s=i,a=r,l=t.ePopup.style.top,p=parseInt(l.substring(0,l.length-1),10),u=t.ePopup.style.left,c=parseInt(u.substring(0,u.length-1),10),d=window.setInterval((function(){var o=e.getBoundingClientRect(),n=t.element.getBoundingClientRect();if(0==n.top&&0==n.left&&0==n.height&&0==n.width)t.hidePopup();else{var l=o.top-n.top;if(l!=s){var u=p+i-l;t.ePopup.style.top=u+"px"}s=l;var d=o.left-n.left;if(d!=a){var h=c+r-d;t.ePopup.style.left=h+"px"}a=d}}),200);return function(){null!=d&&window.clearInterval(d),d=void 0}},e.prototype.addPopup=function(t){var e=this,o=t.modal,n=t.eChild,i=t.closeOnEsc,r=t.closedCallback,s=t.click,a=t.alwaysOnTop,l=t.afterGuiAttached,p=t.positionCallback,u=t.anchorToElement,c=this.gridOptionsWrapper.getDocument();if(c){var d=E(this.popupList,(function(t){return t.element===n}));if(-1!==d){var h=this.popupList[d];return{hideFunc:h.hideFunc,stopAnchoringFunc:h.stopAnchoringFunc}}var f=this.getPopupParent();f.appendChild(n),null==n.style.top&&(n.style.top="0px"),null==n.style.left&&(n.style.left="0px");var g=document.createElement("div"),y=this.environment.getTheme().theme;y&&Me(g,y),Me(g,"ag-popup"),Me(n,this.gridOptionsWrapper.isEnableRtl()?"ag-rtl":"ag-ltr"),Me(n,"ag-popup-child"),this.focusController.isKeyboardMode()&&Me(n,Za.AG_KEYBOARD_FOCUS),g.appendChild(n),f.appendChild(g),a?this.setAlwaysOnTop(g,!0):this.bringPopupToFront(g);var v,m=!1,C=function(t){g.contains(document.activeElement)&&((t.which||t.keyCode)===jn.ESCAPE&&O({keyboardEvent:t}))},w=function(t){return O({mouseEvent:t})},R=function(t){return O({touchEvent:t})},O=function(t){void 0===t&&(t={});var o=t.mouseEvent,i=t.touchEvent,a=t.keyboardEvent;e.isEventFromCurrentPopup({mouseEvent:o,touchEvent:i},n)||e.isEventSameChainAsOriginalEvent({originalMouseEvent:s,mouseEvent:o,touchEvent:i})||m||(m=!0,f.removeChild(g),c.removeEventListener("keydown",C),c.removeEventListener("mousedown",w),c.removeEventListener("touchstart",R),c.removeEventListener("contextmenu",w),e.eventService.removeEventListener(Wt.EVENT_DRAG_STARTED,w),r&&r(o||i||a),e.popupList=e.popupList.filter((function(t){return t.element!==n})),v&&v())};return l&&l({hidePopup:O}),window.setTimeout((function(){i&&c.addEventListener("keydown",C),o&&(c.addEventListener("mousedown",w),e.eventService.addEventListener(Wt.EVENT_DRAG_STARTED,w),c.addEventListener("touchstart",R),c.addEventListener("contextmenu",w))}),0),p&&p(),u&&(v=this.keepPopupPositionedRelativeTo({element:u,ePopup:n,hidePopup:O})),this.popupList.push({element:n,hideFunc:O,stopAnchoringFunc:v}),{hideFunc:O,stopAnchoringFunc:v}}console.warn("ag-grid: could not find the document, document is empty")},e.prototype.isEventFromCurrentPopup=function(t,e){var o=t.mouseEvent,n=t.touchEvent,i=o||n;if(!i)return!1;var r=E(this.popupList,(function(t){return t.element===e}));if(-1===r)return!1;for(var s=r;s<this.popupList.length;s++){if(Tt(this.popupList[s].element,i))return!0}return this.isElementWithinCustomPopup(i.target)},e.prototype.isElementWithinCustomPopup=function(t){if(!this.popupList.length)return!1;for(;t&&t!==document.body;){if(t.classList.contains("ag-custom-component-popup")||null===t.parentElement)return!0;t=t.parentElement}return!1},e.prototype.isEventSameChainAsOriginalEvent=function(t){var e=t.originalMouseEvent,o=t.mouseEvent,n=t.touchEvent,i=null;if(o?i=o:n&&(i=n.touches[0]),i&&e){var r=o?o.screenX:0,s=o?o.screenY:0,a=Math.abs(e.screenX-r)<5,l=Math.abs(e.screenY-s)<5;if(a&&l)return!0}return!1},e.prototype.getWrapper=function(t){for(;!He(t,"ag-popup")&&t.parentElement;)t=t.parentElement;return He(t,"ag-popup")?t:null},e.prototype.setAlwaysOnTop=function(t,e){var o=this.getWrapper(t);o&&(Ve(o,"ag-always-on-top",!!e),e&&this.bringPopupToFront(o))},e.prototype.bringPopupToFront=function(t){var e=this.getPopupParent(),o=Array.prototype.slice.call(e.querySelectorAll(".ag-popup")),n=o.length,i=Array.prototype.slice.call(e.querySelectorAll(".ag-popup.ag-always-on-top")),r=i.length,s=this.getWrapper(t);if(s&&!(n<=1)&&e.contains(t)){var a=o.indexOf(s);if(r)He(s,"ag-always-on-top")?a!==n-1&&d(i).insertAdjacentElement("afterend",s):a!==n-r-1&&i[0].insertAdjacentElement("beforebegin",s);else a!==n-1&&d(o).insertAdjacentElement("afterend",s);var l={type:"popupToFront",api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi(),eWrapper:s};this.eventService.dispatchEvent(l)}},tl([it("environment")],e.prototype,"environment",void 0),tl([it("focusController")],e.prototype,"focusController",void 0),e=tl([nt("popupService")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),ol=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},nl=function(t,e){return function(o,n){e(o,n,t)}},il=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}el(e,t),e.prototype.setBeans=function(t){this.logging=t.isDebug()},e.prototype.create=function(t){return new il(t,this.isLogging.bind(this))},e.prototype.isLogging=function(){return this.logging},ol([nl(0,at("gridOptionsWrapper"))],e.prototype,"setBeans",null),e=ol([nt("loggerFactory")],e)}(Mt),function(){function t(t,e){this.name=t,this.isLoggingFunc=e}return t.prototype.isLogging=function(){return this.isLoggingFunc()},t.prototype.log=function(t){this.isLoggingFunc()&&console.log("AG Grid."+this.name+": "+t)},t}()),rl=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),sl=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},al=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}rl(e,t),e.prototype.registerGridComp=function(t){this.gridPanel=t},e.prototype.registerHeaderRootComp=function(t){this.headerRootComp=t},e.prototype.getPreferredWidthForColumn=function(t,e){var o=this.getHeaderCellForColumn(t);if(!o)return-1;var n=document.createElement("span");n.style.position="fixed";var i=this.gridPanel.getCenterContainer();i.appendChild(n),this.putRowCellsIntoDummyContainer(t,n),e||this.cloneItemIntoDummy(o,n);var r=n.offsetWidth;return i.removeChild(n),r+this.gridOptionsWrapper.getAutoSizePadding()},e.prototype.getHeaderCellForColumn=function(t){var e=null;return this.headerRootComp.forEachHeaderElement((function(o){if(o instanceof Qs){var n=o;n.getColumn()===t&&(e=n)}})),e?e.getGui():null},e.prototype.putRowCellsIntoDummyContainer=function(t,e){var o=this;this.rowRenderer.getAllCellsForColumn(t).forEach((function(t){return o.cloneItemIntoDummy(t,e)}))},e.prototype.cloneItemIntoDummy=function(t,e){var o=t.cloneNode(!0);o.style.width="",o.style.position="static",o.style.left="";var n=document.createElement("div");He(o,"ag-header-cell")?(Me(n,"ag-header"),Me(n,"ag-header-row"),n.style.position="static"):Me(n,"ag-row"),n.style.display="table-row",n.appendChild(o),e.appendChild(n)},sl([it("rowRenderer")],e.prototype,"rowRenderer",void 0),e=sl([nt("autoWidthCalculator")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),ll=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},pl=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}al(e,t),e.prototype.addResizeBar=function(t){var e=this,o={dragStartPixels:t.dragStartPixels||0,eElement:t.eResizeBar,onDragStart:this.onDragStart.bind(this,t),onDragStop:this.onDragStop.bind(this,t),onDragging:this.onDragging.bind(this,t)};this.dragService.addDragSource(o,!0);return function(){return e.dragService.removeDragSource(o)}},e.prototype.onDragStart=function(t,e){this.dragStartX=e.clientX,this.setResizeIcons();var o=e instanceof MouseEvent&&!0===e.shiftKey;t.onResizeStart(o)},e.prototype.setResizeIcons=function(){this.oldBodyCursor=this.eGridDiv.style.cursor,this.oldUserSelect=this.eGridDiv.style.userSelect,this.oldWebkitUserSelect=this.eGridDiv.style.webkitUserSelect,this.eGridDiv.style.cursor="ew-resize",this.eGridDiv.style.userSelect="none",this.eGridDiv.style.webkitUserSelect="none"},e.prototype.onDragStop=function(t,e){t.onResizeEnd(this.resizeAmount),this.resetIcons()},e.prototype.resetIcons=function(){this.eGridDiv.style.cursor=this.oldBodyCursor,this.eGridDiv.style.userSelect=this.oldUserSelect,this.eGridDiv.style.webkitUserSelect=this.oldWebkitUserSelect},e.prototype.onDragging=function(t,e){this.resizeAmount=e.clientX-this.dragStartX,t.onResizing(this.resizeAmount)},ll([it("dragService")],e.prototype,"dragService",void 0),ll([it("eGridDiv")],e.prototype,"eGridDiv",void 0),e=ll([nt("horizontalResizeService")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),ul=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},cl=(function(t){function e(){return t.call(this,void 0,!0)||this}pl(e,t),e.prototype.postConstruct=function(){var e=this;this.logger=this.loggerFactory.create("GridCore");var o=this.createTemplate();if(this.setTemplate(o),[this.gridApi,this.rowRenderer,this.popupService,this.focusController].forEach((function(t){return t.registerGridCore(e)})),ft.isRegistered(pt.ClipboardModule)&&this.clipboardService.registerGridCore(this),this.gridOptionsWrapper.addLayoutElement(this.getGui()),this.eGridDiv.appendChild(this.getGui()),this.addDestroyFunc((function(){e.eGridDiv.removeChild(e.getGui())})),this.$scope){var n=this.$scope.$watch(this.quickFilterOnScope,(function(t){return e.filterManager.setQuickFilter(t)}));this.addDestroyFunc(n)}this.addRtlSupport(),this.logger.log("ready"),this.gridOptionsWrapper.addLayoutElement(this.eRootWrapperBody);var i=this.resizeObserverService.observeResize(this.eGridDiv,this.onGridSizeChanged.bind(this));this.addDestroyFunc((function(){return i()}));var r=this.getGui();this.addManagedListener(this,Wt.EVENT_KEYBOARD_FOCUS,(function(){Me(r,Za.AG_KEYBOARD_FOCUS)})),this.addManagedListener(this,Wt.EVENT_MOUSE_FOCUS,(function(){xe(r,Za.AG_KEYBOARD_FOCUS)})),t.prototype.postConstruct.call(this)},e.prototype.getFocusableElement=function(){return this.eRootWrapperBody},e.prototype.createTemplate=function(){var t=ft.isRegistered(pt.SideBarModule),e=ft.isRegistered(pt.StatusBarModule);return'<div ref="eRootWrapper" class="ag-root-wrapper">\n '+(ft.isRegistered(pt.RowGroupingModule)?"<ag-grid-header-drop-zones></ag-grid-header-drop-zones>":"")+'\n <div class="ag-root-wrapper-body" ref="rootWrapperBody">\n <ag-grid-comp ref="gridPanel"></ag-grid-comp>\n '+(t?'<ag-side-bar ref="sideBar"></ag-side-bar>':"")+"\n </div>\n "+(e?'<ag-status-bar ref="statusBar"></ag-status-bar>':"")+"\n <ag-pagination></ag-pagination>\n "+(ft.isRegistered(pt.EnterpriseCoreModule)?"<ag-watermark></ag-watermark>":"")+"\n </div>"},e.prototype.getFocusableContainers=function(){var t=[this.gridPanel.getGui()];return this.sideBarComp&&t.push(this.sideBarComp.getGui()),t.filter((function(t){return eo(t)}))},e.prototype.focusNextInnerContainer=function(t){var e=this.getFocusableContainers(),o=E(e,(function(t){return t.contains(document.activeElement)}))+(t?-1:1);return!(o<0||o>=e.length)&&(0===o?this.focusGridHeader():this.focusController.focusInto(e[o]))},e.prototype.focusInnerElement=function(t){var e=this.getFocusableContainers();if(t){if(e.length>1)return this.focusController.focusInto(d(e));var o=d(this.columnController.getAllDisplayedColumns());if(this.focusController.focusGridView(o,!0))return!0}return this.focusGridHeader()},e.prototype.focusGridHeader=function(){var t=this.columnController.getAllDisplayedColumns()[0];return!!t&&(t.getParent()&&(t=this.columnController.getColumnGroupAtLevel(t,0)),this.focusController.focusHeaderPosition({headerRowIndex:0,column:t}),!0)},e.prototype.onGridSizeChanged=function(){var t={type:Wt.EVENT_GRID_SIZE_CHANGED,api:this.gridApi,columnApi:this.columnApi,clientWidth:this.eGridDiv.clientWidth,clientHeight:this.eGridDiv.clientHeight};this.eventService.dispatchEvent(t)},e.prototype.addRtlSupport=function(){var t=this.gridOptionsWrapper.isEnableRtl()?"ag-rtl":"ag-ltr";Me(this.getGui(),t)},e.prototype.getRootGui=function(){return this.getGui()},e.prototype.isSideBarVisible=function(){return!!this.sideBarComp&&this.sideBarComp.isDisplayed()},e.prototype.setSideBarVisible=function(t){this.sideBarComp?this.sideBarComp.setDisplayed(t):t&&console.warn("AG Grid: sideBar is not loaded")},e.prototype.setSideBarPosition=function(t){this.sideBarComp?this.sideBarComp.setSideBarPosition(t):console.warn("AG Grid: sideBar is not loaded")},e.prototype.closeToolPanel=function(){this.sideBarComp?this.sideBarComp.close():console.warn("AG Grid: toolPanel is only available in AG Grid Enterprise")},e.prototype.getSideBar=function(){return this.gridOptions.sideBar},e.prototype.getToolPanelInstance=function(t){if(this.sideBarComp)return this.sideBarComp.getToolPanelInstance(t);console.warn("AG Grid: toolPanel is only available in AG Grid Enterprise")},e.prototype.refreshSideBar=function(){this.sideBarComp&&this.sideBarComp.refresh()},e.prototype.setSideBar=function(t){this.sideBarComp&&(this.eRootWrapperBody.removeChild(this.sideBarComp.getGui()),this.gridOptions.sideBar=xr.parse(t),this.sideBarComp.reset(),this.eRootWrapperBody.appendChild(this.sideBarComp.getGui()))},e.prototype.getOpenedToolPanel=function(){return this.sideBarComp?this.sideBarComp.openedItem():null},e.prototype.openToolPanel=function(t){this.sideBarComp?this.sideBarComp.openToolPanel(t):console.warn("AG Grid: toolPanel is only available in AG Grid Enterprise")},e.prototype.isToolPanelShowing=function(){return this.sideBarComp.isToolPanelShowing()},e.prototype.destroy=function(){this.logger.log("Grid DOM removed"),t.prototype.destroy.call(this)},e.prototype.ensureNodeVisible=function(t,e){if(void 0===e&&(e=null),this.doingVirtualPaging)throw new Error("Cannot use ensureNodeVisible when doing virtual paging, as we cannot check rows that are not in memory");for(var o=this.rowModel.getRowCount(),n="function"==typeof t,i=-1,r=0;r<o;r++){var s=this.rowModel.getRow(r);if(n){if(t(s)){i=r;break}}else if(t===s||t===s.data){i=r;break}}i>=0&&this.gridPanel.ensureIndexVisible(i,e)},e.prototype.onTabKeyDown=function(){},ul([it("gridOptions")],e.prototype,"gridOptions",void 0),ul([it("rowModel")],e.prototype,"rowModel",void 0),ul([it("resizeObserverService")],e.prototype,"resizeObserverService",void 0),ul([it("rowRenderer")],e.prototype,"rowRenderer",void 0),ul([it("filterManager")],e.prototype,"filterManager",void 0),ul([it("eGridDiv")],e.prototype,"eGridDiv",void 0),ul([it("$scope")],e.prototype,"$scope",void 0),ul([it("quickFilterOnScope")],e.prototype,"quickFilterOnScope",void 0),ul([it("popupService")],e.prototype,"popupService",void 0),ul([it("columnController")],e.prototype,"columnController",void 0),ul([it("loggerFactory")],e.prototype,"loggerFactory",void 0),ul([it("columnApi")],e.prototype,"columnApi",void 0),ul([it("gridApi")],e.prototype,"gridApi",void 0),ul([rt("clipboardService")],e.prototype,"clipboardService",void 0),ul([Wn("gridPanel")],e.prototype,"gridPanel",void 0),ul([Wn("sideBar")],e.prototype,"sideBarComp",void 0),ul([Wn("rootWrapperBody")],e.prototype,"eRootWrapperBody",void 0)}(Zn),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),dl=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},hl=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}cl(e,t),e.prototype.registerGridComp=function(t){this.gridPanel=t},e.prototype.hideActiveMenu=function(){this.hidePopup&&this.hidePopup()},e.prototype.showMenuAfterMouseEvent=function(t,e){var o=this;this.showPopup(t,(function(n){o.popupService.positionPopupUnderMouseEvent({column:t,type:"columnMenu",mouseEvent:e,ePopup:n})}),e.target)},e.prototype.showMenuAfterButtonClick=function(t,e){var o=this;this.showPopup(t,(function(n){o.popupService.positionPopupUnderComponent({type:"columnMenu",eventSource:e,ePopup:n,keepWithinBounds:!0,column:t})}),e)},e.prototype.showPopup=function(t,e,o){var n,i=this,r=this.filterManager.getOrCreateFilterWrapper(t,"COLUMN_MENU"),s=document.createElement("div");s.setAttribute("role","presentation"),Me(s,"ag-menu"),this.tabListener=this.addManagedListener(s,"keydown",(function(t){return i.trapFocusWithin(t,s)})),r.guiPromise.then((function(t){return s.appendChild(t)}));var a=o||this.gridPanel.getGui(),l=this.popupService.addPopup({modal:!0,eChild:s,closeOnEsc:!0,closedCallback:function(e){t.setMenuVisible(!1,"contextMenu");var n=e instanceof KeyboardEvent;if(i.tabListener&&(i.tabListener=i.tabListener()),n&&o&&eo(o)){var r=i.focusController.findTabbableParent(o);r&&r.focus()}},positionCallback:function(){return e(s)},anchorToElement:a});l&&(this.hidePopup=n=l.hideFunc),r.filterPromise.then((function(t){e(s),t.afterGuiAttached&&t.afterGuiAttached({container:"columnMenu",hidePopup:n})})),t.setMenuVisible(!0,"contextMenu")},e.prototype.trapFocusWithin=function(t,e){t.keyCode!==jn.TAB||t.defaultPrevented||this.focusController.findNextFocusableElement(e,!1,t.shiftKey)||(t.preventDefault(),this.focusController.focusInto(e,t.shiftKey))},e.prototype.isMenuEnabled=function(t){return t.isFilterAllowed()},dl([it("filterManager")],e.prototype,"filterManager",void 0),dl([it("popupService")],e.prototype,"popupService",void 0),dl([it("focusController")],e.prototype,"focusController",void 0),e=dl([nt("menuFactory")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),fl=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},gl=(function(t){function o(){var e=null!==t&&t.apply(this,arguments)||this;return e.dragEndFunctions=[],e.dragSources=[],e}hl(o,t),o.prototype.init=function(){this.logger=this.loggerFactory.create("DragService")},o.prototype.removeAllListeners=function(){this.dragSources.forEach(this.removeListener.bind(this)),this.dragSources.length=0},o.prototype.removeListener=function(t){var e=t.dragSource.eElement,o=t.mouseDownListener;if(e.removeEventListener("mousedown",o),t.touchEnabled){var n=t.touchStartListener;e.removeEventListener("touchstart",n,{passive:!0})}},o.prototype.removeDragSource=function(t){var e=a(this.dragSources,(function(e){return e.dragSource===t}));e&&(this.removeListener(e),g(this.dragSources,e))},o.prototype.setNoSelectToBody=function(t){var o=this.gridOptionsWrapper.getDocument().querySelector("body");e(o)&&Ve(o,"ag-unselectable",t)},o.prototype.isDragging=function(){return this.dragging},o.prototype.addDragSource=function(t,e){void 0===e&&(e=!1);var o=this.onMouseDown.bind(this,t);t.eElement.addEventListener("mousedown",o);var n=null,i=this.gridOptionsWrapper.isSuppressTouch();e&&!i&&(n=this.onTouchStart.bind(this,t),t.eElement.addEventListener("touchstart",n,{passive:!0})),this.dragSources.push({dragSource:t,mouseDownListener:o,touchStartListener:n,touchEnabled:e})},o.prototype.onTouchStart=function(t,e){var o=this;this.currentDragParams=t,this.dragging=!1;var n=e.touches[0];this.touchLastTime=n,this.touchStart=n;var i=function(e){return o.onTouchUp(e,t.eElement)},r=t.eElement,s=[{target:document,type:"touchmove",listener:function(t){t.cancelable&&t.preventDefault()},options:{passive:!1}},{target:r,type:"touchmove",listener:function(e){return o.onTouchMove(e,t.eElement)},options:{passive:!0}},{target:r,type:"touchend",listener:i,options:{passive:!0}},{target:r,type:"touchcancel",listener:i,options:{passive:!0}}];this.addTemporaryEvents(s),0===t.dragStartPixels&&this.onCommonMove(n,this.touchStart,t.eElement)},o.prototype.onMouseDown=function(t,e){var o=this,n=e;if(!(t.skipMouseEvent&&t.skipMouseEvent(e)||n._alreadyProcessedByDragService||(n._alreadyProcessedByDragService=!0,0!==e.button))){this.currentDragParams=t,this.dragging=!1,this.mouseStartEvent=e;var i=this.gridOptionsWrapper.getDocument();this.setNoSelectToBody(!0);var r=[{target:i,type:"mousemove",listener:function(e){return o.onMouseMove(e,t.eElement)}},{target:i,type:"mouseup",listener:function(e){return o.onMouseUp(e,t.eElement)}},{target:i,type:"contextmenu",listener:function(t){return t.preventDefault()}}];this.addTemporaryEvents(r),0===t.dragStartPixels&&this.onMouseMove(e,t.eElement)}},o.prototype.addTemporaryEvents=function(t){t.forEach((function(t){var e=t.target,o=t.type,n=t.listener,i=t.options;e.addEventListener(o,n,i)})),this.dragEndFunctions.push((function(){t.forEach((function(t){var e=t.target,o=t.type,n=t.listener,i=t.options;e.removeEventListener(o,n,i)}))}))},o.prototype.isEventNearStartEvent=function(t,o){var n=this.currentDragParams.dragStartPixels;return Cn(t,o,e(n)?n:4)},o.prototype.getFirstActiveTouch=function(t){for(var e=0;e<t.length;e++)if(t[e].identifier===this.touchStart.identifier)return t[e];return null},o.prototype.onCommonMove=function(t,e,o){if(!this.dragging){if(!this.dragging&&this.isEventNearStartEvent(t,e))return;this.dragging=!0;var n={type:Wt.EVENT_DRAG_STARTED,api:this.gridApi,columnApi:this.columnApi,target:o};this.eventService.dispatchEvent(n),this.currentDragParams.onDragStart(e),this.currentDragParams.onDragging(e)}this.currentDragParams.onDragging(t)},o.prototype.onTouchMove=function(t,e){var o=this.getFirstActiveTouch(t.touches);o&&this.onCommonMove(o,this.touchStart,e)},o.prototype.onMouseMove=function(t,e){this.onCommonMove(t,this.mouseStartEvent,e)},o.prototype.onTouchUp=function(t,e){var o=this.getFirstActiveTouch(t.changedTouches);o||(o=this.touchLastTime),this.onUpCommon(o,e)},o.prototype.onMouseUp=function(t,e){this.onUpCommon(t,e)},o.prototype.onUpCommon=function(t,e){if(this.dragging){this.dragging=!1,this.currentDragParams.onDragStop(t);var o={type:Wt.EVENT_DRAG_STOPPED,api:this.gridApi,columnApi:this.columnApi,target:e};this.eventService.dispatchEvent(o)}this.setNoSelectToBody(!1),this.mouseStartEvent=null,this.touchStart=null,this.touchLastTime=null,this.currentDragParams=null,this.dragEndFunctions.forEach((function(t){return t()})),this.dragEndFunctions.length=0},fl([it("loggerFactory")],o.prototype,"loggerFactory",void 0),fl([it("columnApi")],o.prototype,"columnApi",void 0),fl([it("gridApi")],o.prototype,"gridApi",void 0),fl([et],o.prototype,"init",null),fl([ot],o.prototype,"removeAllListeners",null),o=fl([nt("dragService")],o)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),yl=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},vl=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}var o;gl(e,t),o=e,e.prototype.progressSort=function(t,e,o){void 0===o&&(o="api");var n=this.getNextSortDirection(t);this.setSortForColumn(t,n,e,o)},e.prototype.setSortForColumn=function(t,e,o,n){void 0===n&&(n="api"),e!==ht.SORT_ASC&&e!==ht.SORT_DESC&&(e=null),t.setSort(e,n),o&&!this.gridOptionsWrapper.isSuppressMultiSort()||this.clearSortBarThisColumn(t,n),this.updateSortIndex(t),this.dispatchSortChangedEvents()},e.prototype.updateSortIndex=function(t){var e=this.getColumnsWithSortingOrdered(),o=0;e.forEach((function(e){e!==t&&(e.setSortIndex(o),o++)})),t.getSort()&&t.setSortIndex(o),this.columnController.getPrimaryAndSecondaryAndAutoColumns().filter((function(t){return null==t.getSort()})).forEach((function(t){return t.setSortIndex()}))},e.prototype.onSortChanged=function(){this.dispatchSortChangedEvents()},e.prototype.isSortActive=function(){var t=this.columnController.getPrimaryAndSecondaryAndAutoColumns().filter((function(t){return!!t.getSort()}));return t&&t.length>0},e.prototype.dispatchSortChangedEvents=function(){var t={type:Wt.EVENT_SORT_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(t)},e.prototype.clearSortBarThisColumn=function(t,e){this.columnController.getPrimaryAndSecondaryAndAutoColumns().forEach((function(o){o!==t&&o.setSort(void 0,e)}))},e.prototype.getNextSortDirection=function(t){var e;if(e=t.getColDef().sortingOrder?t.getColDef().sortingOrder:this.gridOptionsWrapper.getSortingOrder()?this.gridOptionsWrapper.getSortingOrder():o.DEFAULT_SORTING_ORDER,!Array.isArray(e)||e.length<=0)return console.warn("ag-grid: sortingOrder must be an array with at least one element, currently it's "+e),null;var n,i=e.indexOf(t.getSort()),r=i<0,s=i==e.length-1;return n=r||s?e[0]:e[i+1],o.DEFAULT_SORTING_ORDER.indexOf(n)<0?(console.warn("ag-grid: invalid sort type "+n),null):n},e.prototype.getColumnsWithSortingOrdered=function(){var t=this.columnController.getPrimaryAndSecondaryAndAutoColumns(),e=t.filter((function(t){return!!t.getSort()})),o={};return t.forEach((function(t,e){return o[t.getId()]=e})),e.sort((function(t,e){var n=t.getSortIndex(),i=e.getSortIndex();return null!=n&&null!=i?n-i:null==n&&null==i?o[t.getId()]>o[e.getId()]?1:-1:null==i?-1:1})),e},e.prototype.getSortModel=function(){return this.getColumnsWithSortingOrdered().map((function(t){return{sort:t.getSort(),colId:t.getId()}}))},e.prototype.getSortOptions=function(){return this.getColumnsWithSortingOrdered().map((function(t){return{sort:t.getSort(),column:t}}))},e.DEFAULT_SORTING_ORDER=[ht.SORT_ASC,ht.SORT_DESC,null],yl([it("columnController")],e.prototype,"columnController",void 0),yl([it("columnApi")],e.prototype,"columnApi",void 0),yl([it("gridApi")],e.prototype,"gridApi",void 0),e=o=yl([nt("sortController")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),ml=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Cl=(function(t){function o(){var e=null!==t&&t.apply(this,arguments)||this;return e.gridInstanceId=n.gridInstanceSequence.next(),e}var n;vl(o,t),n=o,o.prototype.init=function(){this.stampDomElementWithGridInstance()},o.prototype.registerGridComp=function(t){this.gridPanel=t},o.prototype.stampDomElementWithGridInstance=function(){this.eGridDiv[n.GRID_DOM_KEY]=this.gridInstanceId},o.prototype.getRenderedCellForEvent=function(t){return Dt(this.gridOptionsWrapper,t,"cellComp")},o.prototype.isEventFromThisGrid=function(t){for(var o=Ft(t),i=0;i<o.length;i++){var r=o[i][n.GRID_DOM_KEY];if(e(r))return r===this.gridInstanceId}return!1},o.prototype.getCellPositionForEvent=function(t){var e=this.getRenderedCellForEvent(t);return e?e.getCellPosition():null},o.prototype.getNormalisedPosition=function(t){var e,o,n=this.gridOptionsWrapper.getDomLayout()===ht.DOM_LAYOUT_NORMAL,i=t;if(null!=i.clientX||null!=i.clientY?(e=i.clientX,o=i.clientY):(e=i.x,o=i.y),n){var r=this.gridPanel.getVScrollPosition();e+=this.gridPanel.getHScrollPosition().left,o+=r.top}return{x:e,y:o}},o.gridInstanceSequence=new Dn,o.GRID_DOM_KEY="__ag_grid_instance",ml([it("eGridDiv")],o.prototype,"eGridDiv",void 0),ml([et],o.prototype,"init",null),o=n=ml([nt("mouseEventService")],o)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),wl=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},El=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}Cl(e,t),e.prototype.getNextCellToFocus=function(t,e){for(var o=e,n=!1;!n;){switch(t){case jn.UP:o=this.getCellAbove(o);break;case jn.DOWN:o=this.getCellBelow(o);break;case jn.RIGHT:o=this.gridOptionsWrapper.isEnableRtl()?this.getCellToLeft(o):this.getCellToRight(o);break;case jn.LEFT:o=this.gridOptionsWrapper.isEnableRtl()?this.getCellToRight(o):this.getCellToLeft(o);break;default:o=null,console.warn("AG Grid: unknown key for navigation "+t)}n=!o||this.isCellGoodToFocusOn(o)}return o},e.prototype.isCellGoodToFocusOn=function(t){var e,o=t.column;switch(t.rowPinned){case ht.PINNED_TOP:e=this.pinnedRowModel.getPinnedTopRow(t.rowIndex);break;case ht.PINNED_BOTTOM:e=this.pinnedRowModel.getPinnedBottomRow(t.rowIndex);break;default:e=this.rowModel.getRow(t.rowIndex)}return!!e&&!o.isSuppressNavigable(e)},e.prototype.getCellToLeft=function(t){if(!t)return null;var e=this.columnController.getDisplayedColBefore(t.column);return e?{rowIndex:t.rowIndex,column:e,rowPinned:t.rowPinned}:null},e.prototype.getCellToRight=function(t){if(!t)return null;var e=this.columnController.getDisplayedColAfter(t.column);return e?{rowIndex:t.rowIndex,column:e,rowPinned:t.rowPinned}:null},e.prototype.getRowBelow=function(t){var e=t.rowIndex,o=t.rowPinned;if(this.isLastRowInContainer(t))switch(o){case ht.PINNED_BOTTOM:return null;case ht.PINNED_TOP:return this.rowModel.isRowsToRender()?{rowIndex:this.paginationProxy.getPageFirstRow(),rowPinned:null}:this.pinnedRowModel.isRowsToRender(ht.PINNED_BOTTOM)?{rowIndex:0,rowPinned:ht.PINNED_BOTTOM}:null;default:return this.pinnedRowModel.isRowsToRender(ht.PINNED_BOTTOM)?{rowIndex:0,rowPinned:ht.PINNED_BOTTOM}:null}return{rowIndex:e+1,rowPinned:o}},e.prototype.getCellBelow=function(t){if(!t)return null;var e=this.getRowBelow(t);return e?{rowIndex:e.rowIndex,column:t.column,rowPinned:e.rowPinned}:null},e.prototype.isLastRowInContainer=function(t){var e=t.rowPinned,o=t.rowIndex;return e===ht.PINNED_TOP?this.pinnedRowModel.getPinnedTopRowData().length-1<=o:e===ht.PINNED_BOTTOM?this.pinnedRowModel.getPinnedBottomRowData().length-1<=o:this.paginationProxy.getPageLastRow()<=o},e.prototype.getRowAbove=function(t){var e=t.rowIndex,o=t.rowPinned;return(o?0===e:e===this.paginationProxy.getPageFirstRow())?o===ht.PINNED_TOP?null:o&&this.rowModel.isRowsToRender()?this.getLastBodyCell():this.pinnedRowModel.isRowsToRender(ht.PINNED_TOP)?this.getLastFloatingTopRow():null:{rowIndex:e-1,rowPinned:o}},e.prototype.getCellAbove=function(t){if(!t)return null;var e=this.getRowAbove({rowIndex:t.rowIndex,rowPinned:t.rowPinned});return e?{rowIndex:e.rowIndex,column:t.column,rowPinned:e.rowPinned}:null},e.prototype.getLastBodyCell=function(){return{rowIndex:this.paginationProxy.getPageLastRow(),rowPinned:null}},e.prototype.getLastFloatingTopRow=function(){return{rowIndex:this.pinnedRowModel.getPinnedTopRowData().length-1,rowPinned:ht.PINNED_TOP}},e.prototype.getNextTabbedCell=function(t,e){return e?this.getNextTabbedCellBackwards(t):this.getNextTabbedCellForwards(t)},e.prototype.getNextTabbedCellForwards=function(t){var e=this.columnController.getAllDisplayedColumns(),n=t.rowIndex,i=t.rowPinned,r=this.columnController.getDisplayedColAfter(t.column);if(!r){r=e[0];var s=this.getRowBelow(t);if(o(s))return null;if(!s.rowPinned&&!this.paginationProxy.isRowInPage(s))return null;n=s?s.rowIndex:null,i=s?s.rowPinned:null}return{rowIndex:n,column:r,rowPinned:i}},e.prototype.getNextTabbedCellBackwards=function(t){var e=this.columnController.getAllDisplayedColumns(),n=t.rowIndex,i=t.rowPinned,r=this.columnController.getDisplayedColBefore(t.column);if(!r){r=d(e);var s=this.getRowAbove({rowIndex:t.rowIndex,rowPinned:t.rowPinned});if(o(s))return null;if(!s.rowPinned&&!this.paginationProxy.isRowInPage(s))return null;n=s?s.rowIndex:null,i=s?s.rowPinned:null}return{rowIndex:n,column:r,rowPinned:i}},wl([it("columnController")],e.prototype,"columnController",void 0),wl([it("rowModel")],e.prototype,"rowModel",void 0),wl([it("pinnedRowModel")],e.prototype,"pinnedRowModel",void 0),wl([it("paginationProxy")],e.prototype,"paginationProxy",void 0),e=wl([nt("cellNavigationService")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Rl=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Ol=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}El(e,t),e.prototype.formatValue=function(t,e,o,n,i,r){void 0===r&&(r=!0);var s,a=null,l=t.getColDef();if(i?s=i:r&&(s=e&&e.rowPinned&&l.pinnedRowValueFormatter?l.pinnedRowValueFormatter:l.valueFormatter),s){var p={value:n,node:e,data:e?e.data:null,colDef:l,column:t,api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi(),context:this.gridOptionsWrapper.getContext()};p.$scope=o,a=this.expressionService.evaluate(s,p)}else if(l.refData)return l.refData[n]||"";return null==a&&Array.isArray(n)&&(a=n.join(", ")),a},Rl([it("expressionService")],e.prototype,"expressionService",void 0),e=Rl([nt("valueFormatterService")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Pl=(function(t){function e(e){return t.call(this,e,"ag-radio-button","radio")||this}Ol(e,t),e.prototype.isSelected=function(){return this.eInput.checked},e.prototype.toggle=function(){this.isSelected()||this.setValue(!0)},e.prototype.addInputListeners=function(){t.prototype.addInputListeners.call(this),this.addManagedListener(this.eventService,Wt.EVENT_CHECKBOX_CHANGED,this.onChange.bind(this))},e.prototype.onChange=function(t){t.selected&&t.name&&this.eInput.name&&this.eInput.name===t.name&&t.id&&this.eInput.id!==t.id&&this.setValue(!1,!0)}}(Bs),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Sl=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},bl=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}Pl(e,t),e.prototype.setScrollsVisible=function(t){if(this.horizontalScrollShowing!==t.horizontalScrollShowing||this.verticalScrollShowing!==t.verticalScrollShowing){this.horizontalScrollShowing=t.horizontalScrollShowing,this.verticalScrollShowing=t.verticalScrollShowing;var e={type:Wt.EVENT_SCROLL_VISIBILITY_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(e)}},e.prototype.isHorizontalScrollShowing=function(){return this.horizontalScrollShowing},e.prototype.isVerticalScrollShowing=function(){return this.verticalScrollShowing},Sl([it("columnApi")],e.prototype,"columnApi",void 0),Sl([it("gridApi")],e.prototype,"gridApi",void 0),e=Sl([nt("scrollVisibleService")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Dl=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Al=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}bl(e,t),e.prototype.processAllCellClasses=function(t,e,o,n){this.processClassRules(t.cellClassRules,e,o,n),this.processStaticCellClasses(t,e,o)},e.prototype.processClassRules=function(t,e,o,n){if(W(t))for(var i=Object.keys(t),r=0;r<i.length;r++){var s=i[r],a=t[s],l=void 0;"string"==typeof a?l=this.expressionService.evaluate(a,e):"function"==typeof a&&(l=a(e)),l?o(s):n&&n(s)}},e.prototype.processStaticCellClasses=function(t,e,o){if(t.cellClass){var n=void 0;if("function"==typeof t.cellClass)n=(0,t.cellClass)(e);else n=t.cellClass;"string"==typeof n?o(n):Array.isArray(n)&&n.forEach((function(t){o(t)}))}},Dl([it("expressionService")],e.prototype,"expressionService",void 0),e=Dl([nt("stylingService")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Tl=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},_l=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}Al(e,t),e.prototype.setMouseOver=function(t){this.selectedColumns=t;var e={type:Wt.EVENT_COLUMN_HOVER_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(e)},e.prototype.clearMouseOver=function(){this.selectedColumns=null;var t={type:Wt.EVENT_COLUMN_HOVER_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(t)},e.prototype.isHovered=function(t){return!!this.selectedColumns&&this.selectedColumns.indexOf(t)>=0},Tl([it("columnApi")],e.prototype,"columnApi",void 0),Tl([it("gridApi")],e.prototype,"gridApi",void 0),e=Tl([nt("columnHoverService")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Fl=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Nl=(function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.executeNextFuncs=[],e.executeLaterFuncs=[],e.active=!1,e.animationThreadCount=0,e}_l(e,t),e.prototype.registerGridComp=function(t){this.gridPanel=t},e.prototype.isActive=function(){return this.active},e.prototype.start=function(){this.active||this.gridOptionsWrapper.isSuppressColumnMoveAnimation()||this.gridOptionsWrapper.isEnableRtl()||(this.ensureAnimationCssClassPresent(),this.active=!0)},e.prototype.finish=function(){this.active&&(this.flush(),this.active=!1)},e.prototype.executeNextVMTurn=function(t){this.active?this.executeNextFuncs.push(t):t()},e.prototype.executeLaterVMTurn=function(t){this.active?this.executeLaterFuncs.push(t):t()},e.prototype.ensureAnimationCssClassPresent=function(){var t=this;this.animationThreadCount++;var e=this.animationThreadCount;this.gridPanel.setColumnMovingCss(!0),this.executeLaterFuncs.push((function(){t.animationThreadCount===e&&t.gridPanel.setColumnMovingCss(!1)}))},e.prototype.flush=function(){var t=this.executeNextFuncs;this.executeNextFuncs=[];var e=this.executeLaterFuncs;this.executeLaterFuncs=[],0===t.length&&0===e.length||(window.setTimeout((function(){return t.forEach((function(t){return t()}))}),0),window.setTimeout((function(){return e.forEach((function(t){return t()}))}),300))},e=Fl([nt("columnAnimationService")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Ll=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Il=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}var n;Nl(e,t),n=e,e.prototype.createAutoGroupColumns=function(t){var e=this,o=[],n=this.gridOptionsWrapper.isTreeData(),i=this.gridOptionsWrapper.isGroupMultiAutoColumn();return n&&i&&(console.warn("AG Grid: you cannot mix groupMultiAutoColumn with treeData, only one column can be used to display groups when doing tree data"),i=!1),i?t.forEach((function(t,n){o.push(e.createOneAutoGroupColumn(t,n))})):o.push(this.createOneAutoGroupColumn()),o},e.prototype.createOneAutoGroupColumn=function(t,e){var i,r=this.generateDefaultColDef(t);(i=t?ht.GROUP_AUTO_COLUMN_ID+"-"+t.getId():n.GROUP_AUTO_COLUMN_BUNDLE_ID,G(r,this.gridOptionsWrapper.getAutoGroupColumnDef()),(r=this.columnFactory.mergeColDefs(r)).colId=i,this.gridOptionsWrapper.isTreeData())||o(r.field)&&o(r.valueGetter)&&o(r.filterValueGetter)&&(r.filter=!1);e&&e>0&&(r.headerCheckboxSelection=!1);var s=new yt(r,null,i,!0);return this.context.createBean(s),s},e.prototype.generateDefaultColDef=function(t){var e=this.gridOptionsWrapper.getAutoGroupColumnDef(),o={headerName:this.gridOptionsWrapper.getLocaleTextFunc()("group","Group")};if(e&&(e.cellRenderer||e.cellRendererFramework)||(o.cellRenderer="agGroupCellRenderer"),t){var n=t.getColDef();M(o,{headerName:this.columnController.getDisplayNameForColumn(t,"header"),headerValueGetter:n.headerValueGetter}),n.cellRenderer&&M(o,{cellRendererParams:{innerRenderer:n.cellRenderer,innerRendererParams:n.cellRendererParams}}),o.showRowGroup=t.getColId()}else o.showRowGroup=!0;return o},e.GROUP_AUTO_COLUMN_BUNDLE_ID=ht.GROUP_AUTO_COLUMN_ID,Ll([it("columnController")],e.prototype,"columnController",void 0),Ll([it("columnFactory")],e.prototype,"columnFactory",void 0),e=n=Ll([nt("autoGroupColService")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Gl=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Ml=(function(t){function n(){var e=null!==t&&t.apply(this,arguments)||this;return e.currentPage=0,e.topDisplayedRowIndex=0,e.bottomDisplayedRowIndex=0,e.pixelOffset=0,e.masterRowCount=0,e}Il(n,t),n.prototype.postConstruct=function(){this.active=this.gridOptionsWrapper.isPagination(),this.paginateChildRows=this.gridOptionsWrapper.isPaginateChildRows(),this.addManagedListener(this.eventService,Wt.EVENT_MODEL_UPDATED,this.onModelUpdated.bind(this)),this.addManagedListener(this.gridOptionsWrapper,"paginationPageSize",this.onPaginationPageSizeChanged.bind(this)),this.onModelUpdated()},n.prototype.ensureRowHeightsValid=function(t,e,o,n){var i=this.rowModel.ensureRowHeightsValid(t,e,this.getPageFirstRow(),this.getPageLastRow());return i&&this.calculatePages(),i},n.prototype.onModelUpdated=function(t){this.calculatePages();var e={type:Wt.EVENT_PAGINATION_CHANGED,animate:!!t&&t.animate,newData:!!t&&t.newData,newPage:!!t&&t.newPage,keepRenderedRows:!!t&&t.keepRenderedRows,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(e)},n.prototype.onPaginationPageSizeChanged=function(){this.calculatePages();var t={type:Wt.EVENT_PAGINATION_CHANGED,animate:!1,newData:!1,newPage:!1,keepRenderedRows:!0,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(t)},n.prototype.goToPage=function(t){if(this.active&&this.currentPage!==t){this.currentPage=t;var e={type:Wt.EVENT_MODEL_UPDATED,animate:!1,keepRenderedRows:!1,newData:!1,newPage:!0,api:this.gridApi,columnApi:this.columnApi};this.onModelUpdated(e)}},n.prototype.getPixelOffset=function(){return this.pixelOffset},n.prototype.getRow=function(t){return this.rowModel.getRow(t)},n.prototype.getRowNode=function(t){return this.rowModel.getRowNode(t)},n.prototype.getRowIndexAtPixel=function(t){return this.rowModel.getRowIndexAtPixel(t)},n.prototype.getCurrentPageHeight=function(){return o(this.topRowBounds)||o(this.bottomRowBounds)?0:Math.max(this.bottomRowBounds.rowTop+this.bottomRowBounds.rowHeight-this.topRowBounds.rowTop,0)},n.prototype.getCurrentPagePixelRange=function(){return{pageFirstPixel:this.topRowBounds?this.topRowBounds.rowTop:0,pageLastPixel:this.bottomRowBounds?this.bottomRowBounds.rowTop+this.bottomRowBounds.rowHeight:0}},n.prototype.isRowPresent=function(t){return!!this.rowModel.isRowPresent(t)&&(t.rowIndex>=this.topDisplayedRowIndex&&t.rowIndex<=this.bottomDisplayedRowIndex)},n.prototype.isEmpty=function(){return this.rowModel.isEmpty()},n.prototype.isRowsToRender=function(){return this.rowModel.isRowsToRender()},n.prototype.getNodesInRangeForSelection=function(t,e){return this.rowModel.getNodesInRangeForSelection(t,e)},n.prototype.forEachNode=function(t){return this.rowModel.forEachNode(t)},n.prototype.getType=function(){return this.rowModel.getType()},n.prototype.getRowBounds=function(t){var e=this.rowModel.getRowBounds(t);return e.rowIndex=t,e},n.prototype.getPageFirstRow=function(){return this.topRowBounds?this.topRowBounds.rowIndex:-1},n.prototype.getPageLastRow=function(){return this.bottomRowBounds?this.bottomRowBounds.rowIndex:-1},n.prototype.getRowCount=function(){return this.rowModel.getRowCount()},n.prototype.getPageForIndex=function(t){return Math.floor(t/this.pageSize)},n.prototype.goToPageWithIndex=function(t){if(this.active){var e=this.getPageForIndex(t);this.goToPage(e)}},n.prototype.isRowInPage=function(t){return!this.active||this.getPageForIndex(t.rowIndex)===this.currentPage},n.prototype.isLastPageFound=function(){return this.rowModel.isLastRowIndexKnown()},n.prototype.getCurrentPage=function(){return this.currentPage},n.prototype.goToNextPage=function(){this.goToPage(this.currentPage+1)},n.prototype.goToPreviousPage=function(){this.goToPage(this.currentPage-1)},n.prototype.goToFirstPage=function(){this.goToPage(0)},n.prototype.goToLastPage=function(){var t=this.rowModel.getRowCount(),e=Math.floor(t/this.pageSize);this.goToPage(e)},n.prototype.getPageSize=function(){return this.pageSize},n.prototype.getTotalPages=function(){return this.totalPages},n.prototype.setPageSize=function(){this.pageSize=this.gridOptionsWrapper.getPaginationPageSize(),(null==this.pageSize||this.pageSize<1)&&(this.pageSize=100)},n.prototype.calculatePages=function(){this.active?(this.setPageSize(),this.paginateChildRows?this.calculatePagesAllRows():this.calculatePagesMasterRowsOnly()):this.calculatedPagesNotActive(),this.topRowBounds=this.rowModel.getRowBounds(this.topDisplayedRowIndex),this.topRowBounds&&(this.topRowBounds.rowIndex=this.topDisplayedRowIndex),this.bottomRowBounds=this.rowModel.getRowBounds(this.bottomDisplayedRowIndex),this.bottomRowBounds&&(this.bottomRowBounds.rowIndex=this.bottomDisplayedRowIndex),this.setPixelOffset(e(this.topRowBounds)?this.topRowBounds.rowTop:0)},n.prototype.setPixelOffset=function(t){this.pixelOffset!==t&&(this.pixelOffset=t,this.eventService.dispatchEvent({type:Wt.EVENT_PAGINATION_PIXEL_OFFSET_CHANGED}))},n.prototype.setZeroRows=function(){this.masterRowCount=0,this.topDisplayedRowIndex=0,this.bottomDisplayedRowIndex=-1,this.currentPage=0,this.totalPages=0},n.prototype.calculatePagesMasterRowsOnly=function(){if(this.masterRowCount=this.rowModel.getTopLevelRowCount(),this.masterRowCount<=0)this.setZeroRows();else{var t=this.masterRowCount-1;this.totalPages=Math.floor(t/this.pageSize)+1,this.currentPage>=this.totalPages&&(this.currentPage=this.totalPages-1),(!ee(this.currentPage)||this.currentPage<0)&&(this.currentPage=0);var e=this.pageSize*this.currentPage,o=this.pageSize*(this.currentPage+1)-1;if(o>t&&(o=t),this.topDisplayedRowIndex=this.rowModel.getTopLevelRowDisplayedIndex(e),o===t)this.bottomDisplayedRowIndex=this.rowModel.getRowCount()-1;else{var n=this.rowModel.getTopLevelRowDisplayedIndex(o+1);this.bottomDisplayedRowIndex=n-1}}},n.prototype.getMasterRowCount=function(){return this.masterRowCount},n.prototype.calculatePagesAllRows=function(){if(this.masterRowCount=this.rowModel.getRowCount(),0!==this.masterRowCount){var t=this.masterRowCount-1;this.totalPages=Math.floor(t/this.pageSize)+1,this.currentPage>=this.totalPages&&(this.currentPage=this.totalPages-1),(!ee(this.currentPage)||this.currentPage<0)&&(this.currentPage=0),this.topDisplayedRowIndex=this.pageSize*this.currentPage,this.bottomDisplayedRowIndex=this.pageSize*(this.currentPage+1)-1,this.bottomDisplayedRowIndex>t&&(this.bottomDisplayedRowIndex=t)}else this.setZeroRows()},n.prototype.calculatedPagesNotActive=function(){this.pageSize=this.rowModel.getRowCount(),this.totalPages=1,this.currentPage=0,this.topDisplayedRowIndex=0,this.bottomDisplayedRowIndex=this.rowModel.getRowCount()-1},Gl([it("rowModel")],n.prototype,"rowModel",void 0),Gl([it("columnApi")],n.prototype,"columnApi",void 0),Gl([it("gridApi")],n.prototype,"gridApi",void 0),Gl([et],n.prototype,"postConstruct",null),n=Gl([nt("paginationProxy")],n)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),xl=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Vl=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}Ml(e,t),e.prototype.registerGridComp=function(t){this.gridPanel=t,this.addManagedListener(this.eventService,Wt.EVENT_BODY_HEIGHT_CHANGED,this.onBodyHeightChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_SCROLL_VISIBILITY_CHANGED,this.onScrollVisibilityChanged.bind(this)),this.checkPageSize()},e.prototype.notActive=function(){return!this.gridOptionsWrapper.isPaginationAutoPageSize()},e.prototype.onScrollVisibilityChanged=function(){this.checkPageSize()},e.prototype.onBodyHeightChanged=function(){this.checkPageSize()},e.prototype.checkPageSize=function(){if(!this.notActive()){var t=this.gridOptionsWrapper.getRowHeightAsNumber(),e=this.gridPanel.getBodyHeight();if(e>0){var o=Math.floor(e/t);this.gridOptionsWrapper.setProperty("paginationPageSize",o)}}},e=xl([nt("paginationAutoPageSizeService")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Hl=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Wl=(function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.cacheVersion=0,e}Vl(e,t),e.prototype.init=function(){this.active=this.gridOptionsWrapper.isValueCache(),this.neverExpires=this.gridOptionsWrapper.isValueCacheNeverExpires()},e.prototype.onDataChanged=function(){this.neverExpires||this.expire()},e.prototype.expire=function(){this.cacheVersion++},e.prototype.setValue=function(t,e,o){this.active&&(t.__cacheVersion!==this.cacheVersion&&(t.__cacheVersion=this.cacheVersion,t.__cacheData={}),t.__cacheData[e]=o)},e.prototype.getValue=function(t,e){if(this.active&&t.__cacheVersion===this.cacheVersion)return t.__cacheData[e]},Hl([et],e.prototype,"init",null),e=Hl([nt("valueCache")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),kl=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Bl=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}Wl(e,t),e.prototype.init=function(){this.rowModel.getType()===ht.ROW_MODEL_TYPE_CLIENT_SIDE&&(this.clientSideRowModel=this.rowModel),this.addManagedListener(this.eventService,Wt.EVENT_CELL_VALUE_CHANGED,this.onCellValueChanged.bind(this))},e.prototype.onCellValueChanged=function(t){t.source!==ht.SOURCE_PASTE&&this.doChangeDetection(t.node,t.column)},e.prototype.doChangeDetection=function(t,e){if(!this.gridOptionsWrapper.isSuppressChangeDetection()){if(this.clientSideRowModel&&!t.isRowPinned()){var o=this.gridOptionsWrapper.isAggregateOnlyChangedColumns(),n=new Kr(o,this.clientSideRowModel.getRootNode());n.addParentNode(t.parent,[e]),this.clientSideRowModel.doAggregate(n)}this.rowRenderer.refreshCells()}},kl([it("rowModel")],e.prototype,"rowModel",void 0),kl([it("rowRenderer")],e.prototype,"rowRenderer",void 0),kl([et],e.prototype,"init",null),e=kl([nt("changeDetectionService")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),jl=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Ul=function(t,e){return function(o,n){e(o,n,t)}},zl=(function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.consuming=!1,e}Bl(e,t),e.prototype.setBeans=function(t){this.logger=t.create("AlignedGridsService")},e.prototype.registerGridComp=function(t){this.gridPanel=t},e.prototype.init=function(){this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_MOVED,this.fireColumnEvent.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_VISIBLE,this.fireColumnEvent.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_PINNED,this.fireColumnEvent.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_GROUP_OPENED,this.fireColumnEvent.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_RESIZED,this.fireColumnEvent.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_BODY_SCROLL,this.fireScrollEvent.bind(this))},e.prototype.fireEvent=function(t){if(!this.consuming){var e=this.gridOptionsWrapper.getAlignedGrids();e&&e.forEach((function(e){if(e.api){var o=e.api.__getAlignedGridService();t(o)}}))}},e.prototype.onEvent=function(t){this.consuming=!0,t(),this.consuming=!1},e.prototype.fireColumnEvent=function(t){this.fireEvent((function(e){e.onColumnEvent(t)}))},e.prototype.fireScrollEvent=function(t){"horizontal"===t.direction&&this.fireEvent((function(e){e.onScrollEvent(t)}))},e.prototype.onScrollEvent=function(t){var e=this;this.onEvent((function(){e.gridPanel.setHorizontalScrollPosition(t.left)}))},e.prototype.getMasterColumns=function(t){var e=[];return t.columns?t.columns.forEach((function(t){e.push(t)})):t.column&&e.push(t.column),e},e.prototype.getColumnIds=function(t){var e=[];return t.columns?t.columns.forEach((function(t){e.push(t.getColId())})):t.column&&e.push(t.column.getColId()),e},e.prototype.onColumnEvent=function(t){var e=this;this.onEvent((function(){switch(t.type){case Wt.EVENT_COLUMN_MOVED:case Wt.EVENT_COLUMN_VISIBLE:case Wt.EVENT_COLUMN_PINNED:case Wt.EVENT_COLUMN_RESIZED:var o=t;e.processColumnEvent(o);break;case Wt.EVENT_COLUMN_GROUP_OPENED:var n=t;e.processGroupOpenedEvent(n);break;case Wt.EVENT_COLUMN_PIVOT_CHANGED:console.warn("AG Grid: pivoting is not supported with aligned grids. You can only use one of these features at a time in a grid.")}}))},e.prototype.processGroupOpenedEvent=function(t){var e=t.columnGroup,o=null;if(e){var n=e.getGroupId();o=this.columnController.getOriginalColumnGroup(n)}e&&!o||(this.logger.log("onColumnEvent-> processing "+t+" expanded = "+e.isExpanded()),this.columnController.setColumnGroupOpened(o,e.isExpanded(),"alignedGridChanged"))},e.prototype.processColumnEvent=function(t){var e=this,o=t.column,n=null;if(o&&(n=this.columnController.getPrimaryColumn(o.getColId())),!o||n){var i=this.getMasterColumns(t);switch(t.type){case Wt.EVENT_COLUMN_MOVED:var r=t,s=t.columnApi.getColumnState().map((function(t){return{colId:t.colId}}));this.columnController.applyColumnState({state:s,applyOrder:!0},"alignedGridChanged"),this.logger.log("onColumnEvent-> processing "+t.type+" toIndex = "+r.toIndex);break;case Wt.EVENT_COLUMN_VISIBLE:var a=t;s=t.columnApi.getColumnState().map((function(t){return{colId:t.colId,hide:t.hide}}));this.columnController.applyColumnState({state:s},"alignedGridChanged"),this.logger.log("onColumnEvent-> processing "+t.type+" visible = "+a.visible);break;case Wt.EVENT_COLUMN_PINNED:var l=t;s=t.columnApi.getColumnState().map((function(t){return{colId:t.colId,pinned:t.pinned}}));this.columnController.applyColumnState({state:s},"alignedGridChanged"),this.logger.log("onColumnEvent-> processing "+t.type+" pinned = "+l.pinned);break;case Wt.EVENT_COLUMN_RESIZED:var p=t;i.forEach((function(o){e.logger.log("onColumnEvent-> processing "+t.type+" actualWidth = "+o.getActualWidth());var n=[{key:o.getColId(),newWidth:o.getActualWidth()}];e.columnController.setColumnWidths(n,!1,p.finished,"alignedGridChanged")}))}var u=this.gridPanel.isVerticalScrollShowing(),c=this.gridOptionsWrapper.getAlignedGrids();c&&c.forEach((function(t){t.api&&t.api.setAlwaysShowVerticalScroll(u)}))}},jl([it("columnController")],e.prototype,"columnController",void 0),jl([Ul(0,at("loggerFactory"))],e.prototype,"setBeans",null),jl([et],e.prototype,"init",null),e=jl([nt("alignedGridsService")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Kl=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Yl=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}zl(e,t),e.prototype.adaptFunction=function(t,e,o,n){if(null==e)return{component:null,componentFromFramework:o,source:n,paramsFromSelector:null};var i=this.componentMetadataProvider.retrieve(t);return i&&i.functionAdapter?{componentFromFramework:o,component:i.functionAdapter(e),source:n,paramsFromSelector:null}:null},e.prototype.adaptCellRendererFunction=function(t){return function(){function e(){}return e.prototype.refresh=function(t){return!1},e.prototype.getGui=function(){var e=t(this.params),o=typeof e;return"string"===o||"number"===o||"boolean"===o?oo("<span>"+e+"</span>"):e},e.prototype.init=function(t){this.params=t},e}()},e.prototype.doesImplementIComponent=function(t){return!!t&&(t.prototype&&"getGui"in t.prototype)},Kl([it("componentMetadataProvider")],e.prototype,"componentMetadataProvider",void 0),e=Kl([nt("agComponentUtils")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),ql=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Xl=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}Yl(e,t),e.prototype.postConstruct=function(){this.componentMetaData={dateComponent:{mandatoryMethodList:["getDate","setDate"],optionalMethodList:["afterGuiAttached","setInputPlaceholder","setInputAriaLabel"]},detailCellRenderer:{mandatoryMethodList:[],optionalMethodList:["refresh"]},headerComponent:{mandatoryMethodList:[],optionalMethodList:["refresh"]},headerGroupComponent:{mandatoryMethodList:[],optionalMethodList:[]},loadingCellRenderer:{mandatoryMethodList:[],optionalMethodList:[]},loadingOverlayComponent:{mandatoryMethodList:[],optionalMethodList:[]},noRowsOverlayComponent:{mandatoryMethodList:[],optionalMethodList:[]},floatingFilterComponent:{mandatoryMethodList:["onParentModelChanged"],optionalMethodList:["afterGuiAttached"]},floatingFilterWrapperComponent:{mandatoryMethodList:[],optionalMethodList:[]},cellRenderer:{mandatoryMethodList:[],optionalMethodList:["refresh","afterGuiAttached"],functionAdapter:this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils)},cellEditor:{mandatoryMethodList:["getValue"],optionalMethodList:["isPopup","isCancelBeforeStart","isCancelAfterEnd","getPopupPosition","focusIn","focusOut","afterGuiAttached"]},innerRenderer:{mandatoryMethodList:[],optionalMethodList:["afterGuiAttached"],functionAdapter:this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils)},fullWidthCellRenderer:{mandatoryMethodList:[],optionalMethodList:["refresh","afterGuiAttached"],functionAdapter:this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils)},pinnedRowCellRenderer:{mandatoryMethodList:[],optionalMethodList:["refresh","afterGuiAttached"],functionAdapter:this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils)},groupRowRenderer:{mandatoryMethodList:[],optionalMethodList:["afterGuiAttached"],functionAdapter:this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils)},filter:{mandatoryMethodList:["isFilterActive","doesFilterPass","getModel","setModel"],optionalMethodList:["afterGuiAttached","onNewRowsLoaded","getModelAsString","onFloatingFilterChanged"]},filterComponent:{mandatoryMethodList:["isFilterActive","doesFilterPass","getModel","setModel"],optionalMethodList:["afterGuiAttached","onNewRowsLoaded","getModelAsString","onFloatingFilterChanged"]},statusPanel:{mandatoryMethodList:[],optionalMethodList:["afterGuiAttached"]},toolPanel:{mandatoryMethodList:[],optionalMethodList:["refresh","afterGuiAttached"]},tooltipComponent:{mandatoryMethodList:[],optionalMethodList:[]}}},e.prototype.retrieve=function(t){return this.componentMetaData[t]},ql([it("agComponentUtils")],e.prototype,"agComponentUtils",void 0),ql([et],e.prototype,"postConstruct",null),e=ql([nt("componentMetadataProvider")],e)}(Mt),function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s}),Ql=(function(){function t(){}t.prototype.registerGridComp=function(t){this.gridPanel=t},t.prototype.postConstruct=function(){this.doingMasterDetail=this.gridOptionsWrapper.isMasterDetail(),this.gridOptionsWrapper.isRowModelDefault()&&(this.clientSideRowModel=this.rowModel),this.gridOptionsWrapper.isRowModelServerSide()&&(this.serverSideRowModel=this.rowModel)},Xl([it("resizeObserverService")],t.prototype,"resizeObserverService",void 0),Xl([it("paginationProxy")],t.prototype,"paginationProxy",void 0),Xl([it("context")],t.prototype,"context",void 0),Xl([it("columnApi")],t.prototype,"columnApi",void 0),Xl([it("gridApi")],t.prototype,"gridApi",void 0),Xl([it("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),Xl([it("expressionService")],t.prototype,"expressionService",void 0),Xl([it("rowRenderer")],t.prototype,"rowRenderer",void 0),Xl([it("$compile")],t.prototype,"$compile",void 0),Xl([it("templateService")],t.prototype,"templateService",void 0),Xl([it("valueService")],t.prototype,"valueService",void 0),Xl([it("eventService")],t.prototype,"eventService",void 0),Xl([it("columnController")],t.prototype,"columnController",void 0),Xl([it("headerNavigationService")],t.prototype,"headerNavigationService",void 0),Xl([it("columnAnimationService")],t.prototype,"columnAnimationService",void 0),Xl([rt("rangeController")],t.prototype,"rangeController",void 0),Xl([it("focusController")],t.prototype,"focusController",void 0),Xl([rt("contextMenuFactory")],t.prototype,"contextMenuFactory",void 0),Xl([it("popupService")],t.prototype,"popupService",void 0),Xl([it("valueFormatterService")],t.prototype,"valueFormatterService",void 0),Xl([it("stylingService")],t.prototype,"stylingService",void 0),Xl([it("columnHoverService")],t.prototype,"columnHoverService",void 0),Xl([it("userComponentFactory")],t.prototype,"userComponentFactory",void 0),Xl([it("animationFrameService")],t.prototype,"taskQueue",void 0),Xl([it("dragAndDropService")],t.prototype,"dragAndDropService",void 0),Xl([it("sortController")],t.prototype,"sortController",void 0),Xl([it("filterManager")],t.prototype,"filterManager",void 0),Xl([it("maxDivHeightScaler")],t.prototype,"maxDivHeightScaler",void 0),Xl([it("frameworkOverrides")],t.prototype,"frameworkOverrides",void 0),Xl([it("detailRowCompCache")],t.prototype,"detailRowCompCache",void 0),Xl([it("cellPositionUtils")],t.prototype,"cellPositionUtils",void 0),Xl([it("rowPositionUtils")],t.prototype,"rowPositionUtils",void 0),Xl([it("selectionController")],t.prototype,"selectionController",void 0),Xl([rt("selectionHandleFactory")],t.prototype,"selectionHandleFactory",void 0),Xl([it("rowCssClassCalculator")],t.prototype,"rowCssClassCalculator",void 0),Xl([it("rowModel")],t.prototype,"rowModel",void 0),Xl([et],t.prototype,"postConstruct",null),t=Xl([nt("beans")],t)}(),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),$l=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Zl={"ag-theme-custom":{headerHeight:25,headerCellMinWidth:24,listItemHeight:20,rowHeight:25,chartMenuPanelWidth:220},"ag-theme-material":{headerHeight:56,headerCellMinWidth:48,listItemHeight:32,rowHeight:48,chartMenuPanelWidth:240},"ag-theme-balham":{headerHeight:32,headerCellMinWidth:24,listItemHeight:24,rowHeight:28,chartMenuPanelWidth:220},"ag-theme-alpine":{headerHeight:48,headerCellMinWidth:36,listItemHeight:24,rowHeight:42,chartMenuPanelWidth:240}},Jl={headerHeight:["ag-header-row"],headerCellMinWidth:["ag-header-cell"],listItemHeight:["ag-virtual-list-item"],rowHeight:["ag-row"],chartMenuPanelWidth:["ag-chart-docked-container"]},tp={},ep=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}Ql(e,t),e.prototype.getSassVariable=function(t,e){var o="ag-theme-"+(t.match("material")?"material":t.match("balham")?"balham":t.match("alpine")?"alpine":"custom"),n=Zl[o][e],i=0;tp[t]||(tp[t]={});var r=tp[t][e];if(null!=r)return r;if(Jl[e]){var s=Jl[e],a=document.createElement("div");Me(a,t),a.style.position="absolute";var l=s.reduce((function(t,e){var o=document.createElement("div");return o.style.position="static",Me(o,e),t.appendChild(o),o}),a);if(document.body){document.body.appendChild(a);var p=-1!==e.toLowerCase().indexOf("height")?"height":"width";i=parseInt(window.getComputedStyle(l)[p],10),document.body.removeChild(a)}}return tp[t][e]=i||n,tp[t][e]},e.prototype.isThemeDark=function(){var t=this.getTheme().theme;return!!t&&t.indexOf("dark")>=0},e.prototype.chartMenuPanelWidth=function(){var t=this.getTheme().themeFamily;return this.getSassVariable(t,"chartMenuPanelWidth")},e.prototype.getTheme=function(){for(var t=/\bag-(material|(?:theme-([\w\-]*)))\b/,e=this.eGridDiv,o=null;e&&!(o=t.exec(e.className));)e=e.parentElement||void 0;if(!o)return{};var n=o[0];if(void 0===o[2]){var i=n.replace("ag-","ag-theme-");z((function(){return console.warn("AG Grid: As of v19 old theme are no longer provided. Please replace "+n+" with "+i+".")}),"using-old-theme")}return{theme:n,el:e,themeFamily:n.replace(/-dark$/,"")}},$l([it("eGridDiv")],e.prototype,"eGridDiv",void 0),e=$l([nt("environment")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),op=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},np=(function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.createTasksP1={list:[],sorted:!1},e.createTasksP2={list:[],sorted:!1},e.destroyTasks=[],e.ticking=!1,e.scrollGoingDown=!0,e.lastScrollTop=0,e.taskCount=0,e.cancelledTasks=new Set,e}ep(e,t),e.prototype.setScrollTop=function(t){this.scrollGoingDown=t>this.lastScrollTop,this.lastScrollTop=t},e.prototype.init=function(){this.useAnimationFrame=!this.gridOptionsWrapper.isSuppressAnimationFrame()},e.prototype.registerGridComp=function(t){this.gridPanel=t},e.prototype.verifyAnimationFrameOn=function(t){!1===this.useAnimationFrame&&console.warn("AG Grid: AnimationFrameService."+t+" called but animation frames are off")},e.prototype.createTask=function(t,e,o){this.verifyAnimationFrameOn(o);var n={task:t,index:e,createOrder:++this.taskCount};this.addTaskToList(this[o],n),this.schedule()},e.prototype.cancelTask=function(t){this.cancelledTasks.add(t)},e.prototype.addTaskToList=function(t,e){t.list.push(e),t.sorted=!1},e.prototype.sortTaskList=function(t){if(!t.sorted){var e=this.scrollGoingDown?1:-1;t.list.sort((function(t,o){return t.index!==o.index?e*(o.index-t.index):o.createOrder-t.createOrder})),t.sorted=!0}},e.prototype.addDestroyTask=function(t){this.verifyAnimationFrameOn("createTasksP3"),this.destroyTasks.push(t),this.schedule()},e.prototype.executeFrame=function(t){this.verifyAnimationFrameOn("executeFrame");for(var e=this.createTasksP1,o=e.list,n=this.createTasksP2,i=n.list,r=this.destroyTasks,s=(new Date).getTime(),a=(new Date).getTime()-s,l=t<=0;l||a<t;){if(!this.gridPanel.executeAnimationFrameScroll()){var p=void 0;if(o.length)this.sortTaskList(e),p=o.pop().task;else if(i.length)this.sortTaskList(n),p=i.pop().task;else{if(!r.length){this.cancelledTasks.clear();break}p=r.pop()}this.cancelledTasks.has(p)||p()}a=(new Date).getTime()-s}o.length||i.length||r.length?this.requestFrame():this.stopTicking()},e.prototype.stopTicking=function(){this.ticking=!1;var t={type:Wt.EVENT_ANIMATION_QUEUE_EMPTY,columnApi:this.gridOptionsWrapper.getColumnApi(),api:this.gridOptionsWrapper.getApi()};this.eventService.dispatchEvent(t)},e.prototype.flushAllFrames=function(){this.useAnimationFrame&&this.executeFrame(-1)},e.prototype.schedule=function(){this.useAnimationFrame&&(this.ticking||(this.ticking=!0,this.requestFrame()))},e.prototype.requestFrame=function(){var t=this.executeFrame.bind(this,60);window.requestAnimationFrame?window.requestAnimationFrame(t):window.webkitRequestAnimationFrame?window.webkitRequestAnimationFrame(t):window.setTimeout(t,0)},e.prototype.isQueueEmpty=function(){return!this.ticking},op([et],e.prototype,"init",null),e=op([nt("animationFrameService")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),ip=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},rp=(function(t){function o(){var e=null!==t&&t.apply(this,arguments)||this;return e.timeLastPageEventProcessed=0,e}np(o,t),o.prototype.registerGridComp=function(t){this.gridPanel=t},o.prototype.handlePageScrollingKey=function(t){var e=t.which||t.keyCode,o=t.altKey,n=t.ctrlKey||t.metaKey,i=this.mouseEventService.getCellPositionForEvent(t);if(!i)return!1;var r=!1;switch(e){case jn.PAGE_HOME:case jn.PAGE_END:n||o||(this.onHomeOrEndKey(e),r=!0);break;case jn.LEFT:case jn.RIGHT:n&&!o&&(this.onCtrlLeftOrRight(e,i),r=!0);break;case jn.UP:case jn.DOWN:n&&!o&&(this.onCtrlUpOrDown(e,i),r=!0);break;case jn.PAGE_DOWN:n||o||(this.onPageDown(i),r=!0);break;case jn.PAGE_UP:n||o||(this.onPageUp(i),r=!0)}return r&&t.preventDefault(),r},o.prototype.isTimeSinceLastPageEventToRecent=function(){return(new Date).getTime()-this.timeLastPageEventProcessed<100},o.prototype.setTimeLastPageEventProcessed=function(){this.timeLastPageEventProcessed=(new Date).getTime()},o.prototype.navigateTo=function(t){var o=t.scrollIndex,n=t.scrollType,i=t.scrollColumn,r=t.focusIndex,s=t.focusColumn;if(e(i)&&this.gridPanel.ensureColumnVisible(i),e(o)&&this.gridPanel.ensureIndexVisible(o,n),this.animationFrameService.flushAllFrames(),this.focusController.setFocusedCell(r,s,null,!0),this.rangeController){var a={rowIndex:r,rowPinned:null,column:s};this.rangeController.setRangeToCell(a)}},o.prototype.onPageDown=function(t){if(!this.isTimeSinceLastPageEventToRecent()){var e=this.gridPanel.getVScrollPosition(),o=this.gridOptionsWrapper.getScrollbarWidth(),n=e.bottom-e.top;this.gridPanel.isHorizontalScrollShowing()&&(n-=o);var i=this.paginationProxy.getPixelOffset(),r=e.top+n,s=this.paginationProxy.getRowIndexAtPixel(r+i),a=this.paginationProxy.getRow(t.rowIndex).rowTop+n-i,l=this.paginationProxy.getRowIndexAtPixel(a+i),p=this.paginationProxy.getPageLastRow();l>p&&(l=p),s>p&&(s=p),this.navigateTo({scrollIndex:s,scrollType:"top",scrollColumn:null,focusIndex:l,focusColumn:t.column}),this.setTimeLastPageEventProcessed()}},o.prototype.onPageUp=function(t){if(!this.isTimeSinceLastPageEventToRecent()){var e=this.gridPanel.getVScrollPosition(),o=this.gridOptionsWrapper.getScrollbarWidth(),n=e.bottom-e.top;this.gridPanel.isHorizontalScrollShowing()&&(n-=o);var i=this.paginationProxy.getPixelOffset(),r=e.top,s=this.paginationProxy.getRowIndexAtPixel(r+i),a=this.paginationProxy.getRow(t.rowIndex),l=a.rowTop+a.rowHeight-n-i,p=this.paginationProxy.getRowIndexAtPixel(l+i),u=this.paginationProxy.getPageFirstRow();p<u&&(p=u),s<u&&(s=u),this.navigateTo({scrollIndex:s,scrollType:"bottom",scrollColumn:null,focusIndex:p,focusColumn:t.column}),this.setTimeLastPageEventProcessed()}},o.prototype.getIndexToFocus=function(t,e){var o=t;if(e){var n=this.paginationProxy.getRow(t);n&&n.stub&&(o-=1)}return o},o.prototype.onCtrlUpOrDown=function(t,e){var o=t===jn.UP,n=o?this.paginationProxy.getPageFirstRow():this.paginationProxy.getPageLastRow();this.navigateTo({scrollIndex:n,scrollType:null,scrollColumn:e.column,focusIndex:this.getIndexToFocus(n,!o),focusColumn:e.column})},o.prototype.onCtrlLeftOrRight=function(t,e){var o=t===jn.LEFT,n=this.columnController.getAllDisplayedColumns(),i=o?n[0]:d(n);this.navigateTo({scrollIndex:e.rowIndex,scrollType:null,scrollColumn:i,focusIndex:e.rowIndex,focusColumn:i})},o.prototype.onHomeOrEndKey=function(t){var e=t===jn.PAGE_HOME,o=this.columnController.getAllDisplayedColumns(),n=e?o[0]:d(o),i=e?this.paginationProxy.getPageFirstRow():this.paginationProxy.getPageLastRow();this.navigateTo({scrollIndex:i,scrollType:null,scrollColumn:n,focusIndex:this.getIndexToFocus(i,!e),focusColumn:n})},ip([it("mouseEventService")],o.prototype,"mouseEventService",void 0),ip([it("paginationProxy")],o.prototype,"paginationProxy",void 0),ip([it("focusController")],o.prototype,"focusController",void 0),ip([it("animationFrameService")],o.prototype,"animationFrameService",void 0),ip([rt("rangeController")],o.prototype,"rangeController",void 0),ip([it("columnController")],o.prototype,"columnController",void 0),o=ip([nt("navigationService")],o)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),sp=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},ap=(function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.scrollY=0,e.uiBodyHeight=0,e}rp(e,t),e.prototype.postConstruct=function(){this.addManagedListener(this.eventService,Wt.EVENT_BODY_HEIGHT_CHANGED,this.updateOffset.bind(this)),this.maxDivHeight=_e()},e.prototype.registerGridComp=function(t){this.gridPanel=t},e.prototype.isScaling=function(){return this.scaling},e.prototype.getOffset=function(){return this.offset},e.prototype.updateOffset=function(){if(this.scaling){var t=this.gridPanel.getVScrollPosition().top,e=this.getUiBodyHeight();(t!==this.scrollY||e!==this.uiBodyHeight)&&(this.scrollY=t,this.uiBodyHeight=e,this.calculateOffset())}},e.prototype.calculateOffset=function(){this.uiContainerHeight=this.maxDivHeight,this.pixelsToShave=this.modelHeight-this.uiContainerHeight,this.maxScrollY=this.uiContainerHeight-this.uiBodyHeight;var t=this.scrollY/this.maxScrollY;this.setOffset(t*this.pixelsToShave)},e.prototype.clearOffset=function(){this.uiContainerHeight=this.modelHeight,this.pixelsToShave=0,this.setOffset(0)},e.prototype.setOffset=function(t){var e="number"==typeof t?Math.floor(t):null;this.offset!==e&&(this.offset=e,this.eventService.dispatchEvent({type:Wt.EVENT_HEIGHT_SCALE_CHANGED}))},e.prototype.setModelHeight=function(t){this.modelHeight=t,this.scaling=this.maxDivHeight>0&&t>this.maxDivHeight,this.scaling?this.calculateOffset():this.clearOffset()},e.prototype.getUiContainerHeight=function(){return this.uiContainerHeight},e.prototype.getRealPixelPosition=function(t){return t-this.offset},e.prototype.getUiBodyHeight=function(){var t=this.gridPanel.getVScrollPosition();return t.bottom-t.top},e.prototype.getScrollPositionForPixel=function(t){if(this.pixelsToShave<=0)return t;var e=t/(this.modelHeight-this.getUiBodyHeight());return this.maxScrollY*e},sp([et],e.prototype,"postConstruct",null),e=sp([nt("maxDivHeightScaler")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),lp=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},pp=(function(t){function o(){return null!==t&&t.apply(this,arguments)||this}ap(o,t),o.prototype.init=function(){this.groupSelectsChildren=this.gridOptionsWrapper.isGroupSelectsChildren(),this.isRowSelectableFunc=this.gridOptionsWrapper.getIsRowSelectableFunc()},o.prototype.updateSelectableAfterGrouping=function(t){if(this.isRowSelectableFunc){this.recurseDown(t.childrenAfterGroup,(function(t){return t.childrenAfterGroup}))}},o.prototype.updateSelectableAfterFiltering=function(t){if(this.isRowSelectableFunc){this.recurseDown(t.childrenAfterGroup,(function(t){return t.childrenAfterFilter}))}},o.prototype.recurseDown=function(t,o){var n=this;t&&t.forEach((function(t){if(t.group){var i;if(t.hasChildren()&&n.recurseDown(o(t),o),n.groupSelectsChildren)i=e(a(o(t),"selectable",!0));else i=!!n.isRowSelectableFunc&&n.isRowSelectableFunc(t);t.setRowSelectable(i)}}))},lp([et],o.prototype,"init",null),o=lp([nt("selectableService")],o)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),up=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},cp=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}pp(e,t),e.prototype.registerGridComp=function(t){this.gridPanel=t},e.prototype.getPreferredHeightForRow=function(t){var e=this,o=document.createElement("div");this.addInRowCssClasses(t,o);var n=this.gridPanel.getCenterContainer();n.appendChild(o);var i=Cs.createChildScopeOrNull(t,this.$scope,this.beans.gridOptionsWrapper),r=i?i.scope:void 0,s=i?i.scopeDestroyFunc:void 0,a=[],l=this.columnController.getAllAutoRowHeightCols(),p=this.columnController.getAllDisplayedColumns();l.filter((function(t){return p.indexOf(t)>=0})).forEach((function(n){var i=new vs(r,e.beans,n,t,null,!0,!1);i.setParentRow(o),a.push(i)}));var u=a.map((function(t){return t.getCreateTemplate()})).join(" ");o.innerHTML=u,a.forEach((function(t){return t.afterAttached()})),r&&this.$compile(o)(r);for(var c=0,d=0;d<o.children.length;d++){var h=o.children[d];h.offsetHeight>c&&(c=h.offsetHeight)}return n.removeChild(o),a.forEach((function(t){t.detach(),t.destroy()})),s&&s(),c},e.prototype.addInRowCssClasses=function(t,e){var o=t.rowIndex,n={rowNode:t,rowIsEven:o%2==0,rowLevel:this.rowCssClassCalculator.calculateRowLevel(t),firstRowOnPage:o===this.beans.paginationProxy.getPageFirstRow(),lastRowOnPage:o===this.beans.paginationProxy.getPageLastRow(),printLayout:!1,expandable:t.isExpandable()};Me(e,this.rowCssClassCalculator.getInitialRowClasses(n).join(" "))},up([it("beans")],e.prototype,"beans",void 0),up([it("$scope")],e.prototype,"$scope",void 0),up([it("columnController")],e.prototype,"columnController",void 0),up([it("rowCssClassCalculator")],e.prototype,"rowCssClassCalculator",void 0),up([it("$compile")],e.prototype,"$compile",void 0),e=up([nt("autoHeightCalculator")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),dp=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},hp=(function(t){function e(){var e=t.call(this)||this;return e.previousAndFirstButtonsDisabled=!1,e.nextButtonDisabled=!1,e.lastButtonDisabled=!1,e}cp(e,t),e.prototype.postConstruct=function(){var t=this,e=this.gridOptionsWrapper.isEnableRtl();this.setTemplate(this.getTemplate()),this.btFirst.insertAdjacentElement("afterbegin",cn(e?"last":"first",this.gridOptionsWrapper)),this.btPrevious.insertAdjacentElement("afterbegin",cn(e?"next":"previous",this.gridOptionsWrapper)),this.btNext.insertAdjacentElement("afterbegin",cn(e?"previous":"next",this.gridOptionsWrapper)),this.btLast.insertAdjacentElement("afterbegin",cn(e?"first":"last",this.gridOptionsWrapper)),this.gridOptionsWrapper.isPagination()&&!this.gridOptionsWrapper.isSuppressPaginationPanel()?(this.addManagedListener(this.eventService,Wt.EVENT_PAGINATION_CHANGED,this.onPaginationChanged.bind(this)),[{el:this.btFirst,fn:this.onBtFirst.bind(this)},{el:this.btPrevious,fn:this.onBtPrevious.bind(this)},{el:this.btNext,fn:this.onBtNext.bind(this)},{el:this.btLast,fn:this.onBtLast.bind(this)}].forEach((function(e){var o=e.el,n=e.fn;t.addManagedListener(o,"click",n),t.addManagedListener(o,"keydown",(function(t){t.keyCode!==jn.ENTER&&t.keyCode!==jn.SPACE||(t.preventDefault(),n())}))})),this.onPaginationChanged()):this.setDisplayed(!1)},e.prototype.onPaginationChanged=function(){this.enableOrDisableButtons(),this.updateRowLabels(),this.setCurrentPageLabel(),this.setTotalLabels()},e.prototype.onBtFirst=function(){this.previousAndFirstButtonsDisabled||this.paginationProxy.goToFirstPage()},e.prototype.setCurrentPageLabel=function(){var t=this.paginationProxy.getTotalPages()>0,e=this.paginationProxy.getCurrentPage(),o=t?e+1:0;this.lbCurrent.innerHTML=this.formatNumber(o)},e.prototype.formatNumber=function(t){var e=this.gridOptionsWrapper.getPaginationNumberFormatterFunc();return e?e({value:t}):ne(t)},e.prototype.getTemplate=function(){var t=this.gridOptionsWrapper.getLocaleTextFunc(),e=t("page","Page"),o=t("to","to"),n=t("of","of"),i=t("firstPage","First Page"),r=t("previousPage","Previous Page"),s=t("nextPage","Next Page"),a=t("lastPage","Last Page"),l=this.getCompId();return'<div class="ag-paging-panel ag-unselectable" id="ag-'+l+'" aria-live="polite" aria-describedby="'+("ag-"+l+"-start-page ag-"+l+"-start-page-number ag-"+l+"-of-page ag-"+l+"-of-page-number")+" "+("ag-"+l+"-first-row ag-"+l+"-to ag-"+l+"-last-row ag-"+l+"-of ag-"+l+"-row-count")+'">\n <span class="ag-paging-row-summary-panel" aria-hidden="true">\n <span id="ag-'+l+'-first-row" ref="lbFirstRowOnPage" class="ag-paging-row-summary-panel-number"></span>\n <span id="ag-'+l+'-to">'+o+'</span>\n <span id="ag-'+l+'-last-row" ref="lbLastRowOnPage" class="ag-paging-row-summary-panel-number"></span>\n <span id="ag-'+l+'-of">'+n+'</span>\n <span id="ag-'+l+'-row-count" ref="lbRecordCount" class="ag-paging-row-summary-panel-number"></span>\n </span>\n <span class="ag-paging-page-summary-panel" role="presentation">\n <div ref="btFirst" class="ag-paging-button" role="button" aria-label="'+i+'" tabindex="0"></div>\n <div ref="btPrevious" class="ag-paging-button" role="button" aria-label="'+r+'" tabindex="0"></div>\n <span class="ag-paging-description" aria-hidden="true">\n <span id="ag-'+l+'-start-page">'+e+'</span>\n <span id="ag-'+l+'-start-page-number" ref="lbCurrent" class="ag-paging-number"></span>\n <span id="ag-'+l+'-of-page">'+n+'</span>\n <span id="ag-'+l+'-of-page-number" ref="lbTotal" class="ag-paging-number"></span>\n </span>\n <div ref="btNext" class="ag-paging-button" role="button" aria-label="'+s+'" tabindex="0"></div>\n <div ref="btLast" class="ag-paging-button" role="button" aria-label="'+a+'" tabindex="0"></div>\n </span>\n </div>'},e.prototype.onBtNext=function(){this.nextButtonDisabled||this.paginationProxy.goToNextPage()},e.prototype.onBtPrevious=function(){this.previousAndFirstButtonsDisabled||this.paginationProxy.goToPreviousPage()},e.prototype.onBtLast=function(){this.lastButtonDisabled||this.paginationProxy.goToLastPage()},e.prototype.enableOrDisableButtons=function(){var t=this.paginationProxy.getCurrentPage(),e=this.paginationProxy.isLastPageFound(),o=this.paginationProxy.getTotalPages();this.previousAndFirstButtonsDisabled=0===t,Ve(this.btFirst,"ag-disabled",this.previousAndFirstButtonsDisabled),xo(this.btFirst,this.previousAndFirstButtonsDisabled),Ve(this.btPrevious,"ag-disabled",this.previousAndFirstButtonsDisabled),xo(this.btPrevious,this.previousAndFirstButtonsDisabled);var n=this.isZeroPagesToDisplay(),i=e&&t===o-1;this.nextButtonDisabled=i||n,Ve(this.btNext,"ag-disabled",this.nextButtonDisabled),xo(this.btNext,this.nextButtonDisabled),this.lastButtonDisabled=!e||n||t===o-1,Ve(this.btLast,"ag-disabled",this.lastButtonDisabled),xo(this.btLast,this.lastButtonDisabled)},e.prototype.updateRowLabels=function(){var t,e,o=this.paginationProxy.getCurrentPage(),n=this.paginationProxy.getPageSize(),i=this.paginationProxy.isLastPageFound(),r=this.paginationProxy.isLastPageFound()?this.paginationProxy.getMasterRowCount():null;this.isZeroPagesToDisplay()?t=e=0:(e=(t=n*o+1)+n-1,i&&e>r&&(e=r)),this.lbFirstRowOnPage.innerHTML=this.formatNumber(t),this.rowNodeBlockLoader.isLoading()?this.lbLastRowOnPage.innerHTML="?":this.lbLastRowOnPage.innerHTML=this.formatNumber(e)},e.prototype.isZeroPagesToDisplay=function(){var t=this.paginationProxy.isLastPageFound(),e=this.paginationProxy.getTotalPages();return t&&0===e},e.prototype.setTotalLabels=function(){var t=this.paginationProxy.isLastPageFound(),e=this.paginationProxy.getTotalPages(),o=t?this.paginationProxy.getMasterRowCount():null;if(t)this.lbTotal.innerHTML=this.formatNumber(e),this.lbRecordCount.innerHTML=this.formatNumber(o);else{var n=this.gridOptionsWrapper.getLocaleTextFunc()("more","more");this.lbTotal.innerHTML=n,this.lbRecordCount.innerHTML=n}},dp([it("paginationProxy")],e.prototype,"paginationProxy",void 0),dp([it("rowModel")],e.prototype,"rowModel",void 0),dp([it("rowNodeBlockLoader")],e.prototype,"rowNodeBlockLoader",void 0),dp([Wn("btFirst")],e.prototype,"btFirst",void 0),dp([Wn("btPrevious")],e.prototype,"btPrevious",void 0),dp([Wn("btNext")],e.prototype,"btNext",void 0),dp([Wn("btLast")],e.prototype,"btLast",void 0),dp([Wn("lbRecordCount")],e.prototype,"lbRecordCount",void 0),dp([Wn("lbFirstRowOnPage")],e.prototype,"lbFirstRowOnPage",void 0),dp([Wn("lbLastRowOnPage")],e.prototype,"lbLastRowOnPage",void 0),dp([Wn("lbCurrent")],e.prototype,"lbCurrent",void 0),dp([Wn("lbTotal")],e.prototype,"lbTotal",void 0),dp([et],e.prototype,"postConstruct",null)}(xn),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),fp=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},gp=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}hp(e,t),e.prototype.observeResize=function(t,e,o){void 0===o&&(o=50);var n,i,r,s,a,l=this.getFrameworkOverrides(),p=$(e,o),u=this.gridOptionsWrapper.isSuppressBrowserResizeObserver();return!!window.ResizeObserver&&!u?((a=new window.ResizeObserver(p)).observe(t),function(){return a.disconnect()}):(n=ro(t),i=io(t),r=!0,(s=function(){if(r){var a=ro(t),p=io(t);(a!==n||p!==i)&&(n=a,i=p,e()),l.setTimeout(s,o)}})(),function(){return r=!1})},e=fp([nt("resizeObserverService")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),yp=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s};!function(t){t[t.Loading=0]="Loading",t[t.NoRows=1]="NoRows"}(Ba||(Ba={}));!function(t){function e(){var o=t.call(this,e.TEMPLATE)||this;return o.inProgress=!1,o.destroyRequested=!1,o}gp(e,t),e.prototype.postConstruct=function(){this.gridOptionsWrapper.addLayoutElement(this.eOverlayWrapper),this.setDisplayed(!1)},e.prototype.setWrapperTypeClass=function(t){Ve(this.eOverlayWrapper,"ag-overlay-loading-wrapper",t===Ba.Loading),Ve(this.eOverlayWrapper,"ag-overlay-no-rows-wrapper",t===Ba.NoRows)},e.prototype.showLoadingOverlay=function(){var t=this.userComponentFactory.newLoadingOverlayComponent({api:this.gridOptionsWrapper.getApi()});this.showOverlay(t,Ba.Loading)},e.prototype.showNoRowsOverlay=function(){var t=this.userComponentFactory.newNoRowsOverlayComponent({api:this.gridOptionsWrapper.getApi()});this.showOverlay(t,Ba.NoRows)},e.prototype.showOverlay=function(t,e){var o=this;this.inProgress||(this.setWrapperTypeClass(e),this.destroyActiveOverlay(),this.inProgress=!0,t&&t.then((function(t){o.inProgress=!1,o.eOverlayWrapper.appendChild(t.getGui()),o.activeOverlay=t,o.destroyRequested&&(o.destroyRequested=!1,o.destroyActiveOverlay())})),this.setDisplayed(!0))},e.prototype.destroyActiveOverlay=function(){this.inProgress?this.destroyRequested=!0:this.activeOverlay&&(this.activeOverlay=this.getContext().destroyBean(this.activeOverlay),Je(this.eOverlayWrapper))},e.prototype.hideOverlay=function(){this.destroyActiveOverlay(),this.setDisplayed(!1)},e.prototype.destroy=function(){this.destroyActiveOverlay(),t.prototype.destroy.call(this)},e.TEMPLATE='\n <div class="ag-overlay" aria-hidden="true">\n <div class="ag-overlay-panel">\n <div class="ag-overlay-wrapper" ref="eOverlayWrapper"></div>\n </div>\n </div>',yp([it("userComponentFactory")],e.prototype,"userComponentFactory",void 0),yp([Wn("eOverlayWrapper")],e.prototype,"eOverlayWrapper",void 0),yp([et],e.prototype,"postConstruct",null)}(xn);
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/var vp,mp=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Cp=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},wp=(function(t){function e(o){void 0===o&&(o={});var n=t.call(this,e.getTemplate(o))||this;n.suppressEnabledCheckbox=!0,n.suppressOpenCloseIcons=!1;var i=o.title,r=o.enabled,s=o.items,a=o.suppressEnabledCheckbox,l=o.suppressOpenCloseIcons;return n.title=i,n.cssIdentifier=o.cssIdentifier||"default",n.enabled=null==r||r,n.items=s||[],n.alignItems=o.alignItems||"center",null!=a&&(n.suppressEnabledCheckbox=a),null!=l&&(n.suppressOpenCloseIcons=l),n}mp(e,t),e.getTemplate=function(t){var e=t.cssIdentifier||"default";return'<div class="ag-group ag-'+e+'-group">\n <div class="ag-group-title-bar ag-'+e+'-group-title-bar ag-unselectable" ref="eTitleBar">\n <span class="ag-group-title-bar-icon ag-'+e+'-group-title-bar-icon" ref="eGroupOpenedIcon"></span>\n <span class="ag-group-title-bar-icon ag-'+e+'-group-title-bar-icon" ref="eGroupClosedIcon"></span>\n <span ref="eTitle" class="ag-group-title ag-'+e+'-group-title"></span>\n </div>\n <div ref="eToolbar" class="ag-group-toolbar ag-'+e+'-group-toolbar">\n <ag-checkbox ref="cbGroupEnabled"></ag-checkbox>\n </div>\n <div ref="eContainer" class="ag-group-container ag-group-container-'+(t.direction||"vertical")+" ag-"+e+'-group-container"></div>\n </div>'},e.prototype.postConstruct=function(){if(this.items.length){var t=this.items;this.items=[],this.addItems(t)}var e=this.gridOptionsWrapper.getLocaleTextFunc();this.cbGroupEnabled.setLabel(e("enabled","Enabled")),this.title&&this.setTitle(this.title),this.enabled&&this.setEnabled(this.enabled),this.setAlignItems(this.alignItems),this.hideEnabledCheckbox(this.suppressEnabledCheckbox),this.hideOpenCloseIcons(this.suppressOpenCloseIcons),this.setupExpandContract(),this.refreshChildDisplay()},e.prototype.setupExpandContract=function(){var t=this;this.eGroupClosedIcon.appendChild(un("columnSelectClosed",this.gridOptionsWrapper,null)),this.eGroupOpenedIcon.appendChild(un("columnSelectOpen",this.gridOptionsWrapper,null)),this.addManagedListener(this.eTitleBar,"click",(function(){return t.toggleGroupExpand()})),this.addManagedListener(this.eTitleBar,"keydown",(function(e){switch(e.keyCode){case jn.ENTER:t.toggleGroupExpand();break;case jn.RIGHT:t.toggleGroupExpand(!0);break;case jn.LEFT:t.toggleGroupExpand(!1)}}))},e.prototype.refreshChildDisplay=function(){var t=!this.suppressOpenCloseIcons;ke(this.eToolbar,this.expanded&&!this.suppressEnabledCheckbox),ke(this.eGroupOpenedIcon,t&&this.expanded),ke(this.eGroupClosedIcon,t&&!this.expanded)},e.prototype.isExpanded=function(){return this.expanded},e.prototype.setAlignItems=function(t){var e=this.getGui();return this.alignItems!==t&&xe(e,"ag-group-item-alignment-"+this.alignItems),this.alignItems=t,Me(e,"ag-group-item-alignment-"+this.alignItems),this},e.prototype.toggleGroupExpand=function(t){return this.suppressOpenCloseIcons?(this.expanded=!0,this.refreshChildDisplay(),ke(this.eContainer,!0),this):(t=null!=t?t:!this.expanded,this.expanded===t||(this.expanded=t,this.refreshChildDisplay(),ke(this.eContainer,t),this.dispatchEvent({type:this.expanded?e.EVENT_EXPANDED:e.EVENT_COLLAPSED})),this)},e.prototype.addItems=function(t){var e=this;t.forEach((function(t){return e.addItem(t)}))},e.prototype.addItem=function(t){var e=this.eContainer,o=t instanceof xn?t.getGui():t;Me(o,"ag-group-item"),Me(o,"ag-"+this.cssIdentifier+"-group-item"),e.appendChild(o),this.items.push(o)},e.prototype.hideItem=function(t,e){Ve(this.items[e],"ag-hidden",t)},e.prototype.setTitle=function(t){return this.eTitle.innerText=t,this},e.prototype.addCssClassToTitleBar=function(t){Me(this.eTitleBar,t)},e.prototype.setEnabled=function(t,e){return this.enabled=t,this.refreshDisabledStyles(),this.toggleGroupExpand(t),e||this.cbGroupEnabled.setValue(t),this},e.prototype.isEnabled=function(){return this.enabled},e.prototype.onEnableChange=function(t){var e=this;return this.cbGroupEnabled.onValueChange((function(o){e.setEnabled(o,!0),t(o)})),this},e.prototype.hideEnabledCheckbox=function(t){return this.suppressEnabledCheckbox=t,this.refreshChildDisplay(),this.refreshDisabledStyles(),this},e.prototype.hideOpenCloseIcons=function(t){return this.suppressOpenCloseIcons=t,t&&this.toggleGroupExpand(!0),this},e.prototype.refreshDisabledStyles=function(){Ve(this.getGui(),"ag-disabled",!this.enabled),this.suppressEnabledCheckbox&&!this.enabled?(Me(this.eTitleBar,"ag-disabled-group-title-bar"),this.eTitleBar.removeAttribute("tabindex")):(xe(this.eTitleBar,"ag-disabled-group-title-bar"),this.eTitleBar.setAttribute("tabindex","0")),Ve(this.eContainer,"ag-disabled-group-container",!this.enabled)},e.EVENT_EXPANDED="expanded",e.EVENT_COLLAPSED="collapsed",Cp([Wn("eTitleBar")],e.prototype,"eTitleBar",void 0),Cp([Wn("eGroupOpenedIcon")],e.prototype,"eGroupOpenedIcon",void 0),Cp([Wn("eGroupClosedIcon")],e.prototype,"eGroupClosedIcon",void 0),Cp([Wn("eToolbar")],e.prototype,"eToolbar",void 0),Cp([Wn("cbGroupEnabled")],e.prototype,"cbGroupEnabled",void 0),Cp([Wn("eTitle")],e.prototype,"eTitle",void 0),Cp([Wn("eContainer")],e.prototype,"eContainer",void 0),Cp([et],e.prototype,"postConstruct",null)}(xn),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Ep=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Rp=function(t){function e(o){var n=t.call(this,e.getTemplate(o))||this;return n.closable=!0,n.positioned=!1,n.dragStartPosition={x:0,y:0},n.position={x:0,y:0},n.size={width:void 0,height:void 0},n.config=o,n}return wp(e,t),e.getTemplate=function(t){var e=t&&t.cssIdentifier||"default";return'<div class="ag-panel ag-'+e+'-panel" tabindex="-1">\n <div ref="eTitleBar" class="ag-panel-title-bar ag-'+e+'-panel-title-bar ag-unselectable">\n <span ref="eTitle" class="ag-panel-title-bar-title ag-'+e+'-panel-title-bar-title"></span>\n <div ref="eTitleBarButtons" class="ag-panel-title-bar-buttons ag-'+e+'-panel-title-bar-buttons"></div>\n </div>\n <div ref="eContentWrapper" class="ag-panel-content-wrapper ag-'+e+'-panel-content-wrapper"></div>\n </div>'},e.prototype.postConstruct=function(){var t=this,e=this.config,o=e.component,n=e.closable,i=e.hideTitleBar,r=e.title,s=e.minWidth,a=e.width,l=e.minHeight,p=e.height,u=e.centered,c=e.x,d=e.y,h=this.getGui();o&&this.setBodyComponent(o),i?Me(this.eTitleBar,"ag-hidden"):(r&&this.setTitle(r),this.setClosable(null!=n?n:this.closable)),this.addManagedListener(this.eTitleBar,"mousedown",(function(e){if(h.contains(e.relatedTarget)||h.contains(document.activeElement)||t.eTitleBarButtons.contains(e.target))e.preventDefault();else{var o=t.eContentWrapper.querySelector("button, [href], input, select, textarea, [tabindex]");o&&o.focus()}})),this.positioned||(this.minHeight=null!=l?l:250,this.minWidth=null!=s?s:250,this.popupParent=this.popupService.getPopupParent(),a&&this.setWidth(a),p&&this.setHeight(p),this.renderComponent&&this.renderComponent(),a&&p||this.refreshSize(),u?this.center():(c||d)&&this.offsetElement(c,d),this.positioned=!0,this.eContentWrapper.style.height="0")},e.prototype.renderComponent=function(){var t=this,e=this.getGui();e.focus(),this.close=function(){e.parentElement.removeChild(e),t.destroy()}},e.prototype.updateDragStartPosition=function(t,e){this.dragStartPosition={x:t,y:e}},e.prototype.calculateMouseMovement=function(t){var e=this.popupParent.getBoundingClientRect(),o=t.e,n=t.isLeft,i=t.isTop,r=t.anywhereWithin,s=t.topBuffer,a=o.clientX-this.dragStartPosition.x,l=o.clientY-this.dragStartPosition.y,p=this.getWidth(),u=this.getHeight(),c=e.left>=o.clientX&&this.position.x<=0||e.right<=o.clientX&&e.right<=this.position.x+e.left+p;return c||(c=n?a<0&&o.clientX>this.position.x+e.left||a>0&&o.clientX<this.position.x+e.left:r?a<0&&o.clientX>this.position.x+e.left+p||a>0&&o.clientX<this.position.x+e.left:a<0&&o.clientX>this.position.x+e.left+p||a>0&&o.clientX<this.position.x+e.left+p),{movementX:a=c?0:a,movementY:l=e.top>=o.clientY&&this.position.y<=0||e.bottom<=o.clientY&&e.bottom<=this.position.y+e.top+u||i&&(l<0&&o.clientY>this.position.y+e.top+(s||0)||l>0&&o.clientY<this.position.y+e.top)||!i&&(l<0&&o.clientY>this.position.y+e.top+u||l>0&&o.clientY<this.position.y+e.top+u)?0:l}},e.prototype.refreshSize=function(){var t=this.size,e=t.width,o=t.height;e||this.setWidth(this.getGui().offsetWidth),o||this.setHeight(this.getGui().offsetHeight)},e.prototype.offsetElement=function(t,e){void 0===t&&(t=0),void 0===e&&(e=0);var o=this.getGui();this.popupService.positionPopup({ePopup:o,x:t,y:e,minWidth:this.minWidth,minHeight:this.minHeight,keepWithinBounds:!0}),this.position.x=parseInt(o.style.left,10),this.position.y=parseInt(o.style.top,10)},e.prototype.getHeight=function(){return this.size.height},e.prototype.setHeight=function(t){var e=this.getGui(),o=!1;if("string"==typeof t&&-1!==t.indexOf("%"))go(e,t),t=qe(e),o=!0;else{t=Math.max(this.minHeight,t);var n=e.offsetParent;n&&n.clientHeight&&t+this.position.y>n.clientHeight&&(t=n.clientHeight-this.position.y)}this.size.height!==t&&(this.size.height=t,o?(e.style.maxHeight="unset",e.style.minHeight="unset"):go(e,t))},e.prototype.getWidth=function(){return this.size.width},e.prototype.setWidth=function(t){var e=this.getGui(),o=!1;if("string"==typeof t&&-1!==t.indexOf("%"))fo(e,t),t=Xe(e),o=!0;else{t=Math.max(this.minWidth,t);var n=e.offsetParent;n&&n.clientWidth&&t+this.position.x>n.clientWidth&&(t=n.clientWidth-this.position.x)}this.size.width!==t&&(this.size.width=t,o?(e.style.maxWidth="unset",e.style.minWidth="unset"):fo(e,t))},e.prototype.center=function(){var t=this.getGui(),e=t.offsetParent.clientWidth/2-this.getWidth()/2,o=t.offsetParent.clientHeight/2-this.getHeight()/2;this.offsetElement(e,o)},e.prototype.setClosable=function(t){if(t!==this.closable&&(this.closable=t),t){var o=this.closeButtonComp=new xn(e.CLOSE_BTN_TEMPLATE);this.getContext().createBean(o),(n=o.getGui()).appendChild(Me(cn("close",this.gridOptionsWrapper),"ag-panel-title-bar-button-icon")),this.addTitleBarButton(o),o.addManagedListener(n,"click",this.onBtClose.bind(this))}else if(this.closeButtonComp){var n;(n=this.closeButtonComp.getGui()).parentElement.removeChild(n),this.closeButtonComp=this.destroyBean(this.closeButtonComp)}},e.prototype.setBodyComponent=function(t){t.setParentComponent(this),this.eContentWrapper.appendChild(t.getGui())},e.prototype.addTitleBarButton=function(t,e){var o=this.eTitleBarButtons,n=o.children,i=n.length;null==e&&(e=i),e=Math.max(0,Math.min(e,i));var r=t.getGui();Me(r,"ag-panel-title-bar-button"),0===e?o.insertAdjacentElement("afterbegin",r):e===i?o.insertAdjacentElement("beforeend",r):n[e-1].insertAdjacentElement("afterend",r),t.setParentComponent(this)},e.prototype.getBodyHeight=function(){return Ke(this.eContentWrapper)},e.prototype.getBodyWidth=function(){return Ye(this.eContentWrapper)},e.prototype.setTitle=function(t){this.eTitle.innerText=t},e.prototype.onBtClose=function(){this.close()},e.prototype.destroy=function(){this.closeButtonComp&&(this.closeButtonComp=this.destroyBean(this.closeButtonComp));var e=this.getGui();e&&e.offsetParent&&this.close(),t.prototype.destroy.call(this)},e.CLOSE_BTN_TEMPLATE='<div class="ag-button"></div>',Ep([it("popupService")],e.prototype,"popupService",void 0),Ep([Wn("eContentWrapper")],e.prototype,"eContentWrapper",void 0),Ep([Wn("eTitleBar")],e.prototype,"eTitleBar",void 0),Ep([Wn("eTitleBarButtons")],e.prototype,"eTitleBarButtons",void 0),Ep([Wn("eTitle")],e.prototype,"eTitle",void 0),Ep([et],e.prototype,"postConstruct",null),e}(xn),Op=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Pp=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Sp=function(t){function e(e){var o=t.call(this,e)||this;return o.RESIZE_TEMPLATE='<div class="ag-resizer-wrapper">\n <div ref="eTopLeftResizer" class="ag-resizer ag-resizer-topLeft"></div>\n <div ref="eTopResizer" class="ag-resizer ag-resizer-top"></div>\n <div ref="eTopRightResizer" class="ag-resizer ag-resizer-topRight"></div>\n <div ref="eRightResizer" class="ag-resizer ag-resizer-right"></div>\n <div ref="eBottomRightResizer" class="ag-resizer ag-resizer-bottomRight"></div>\n <div ref="eBottomResizer" class="ag-resizer ag-resizer-bottom"></div>\n <div ref="eBottomLeftResizer" class="ag-resizer ag-resizer-bottomLeft"></div>\n <div ref="eLeftResizer" class="ag-resizer ag-resizer-left"></div>\n </div>',o.resizable={},o.movable=!1,o.isMoving=!1,o.isMaximizable=!1,o.isMaximized=!1,o.maximizeListeners=[],o.resizeListenerDestroy=null,o.isResizing=!1,o.lastPosition={x:0,y:0,width:0,height:0},o}return Op(e,t),e.prototype.postConstruct=function(){var e=this,o=this.getGui(),n=this.config,i=n.movable,r=n.resizable,s=n.maximizable;Me(o,"ag-dialog"),this.moveElement=this.eTitleBar,t.prototype.postConstruct.call(this),this.addManagedListener(o,"focusin",(function(t){o.contains(t.relatedTarget)||e.popupService.bringPopupToFront(o)})),i&&this.setMovable(i),s&&this.setMaximizable(s),this.addResizers(),r&&this.setResizable(r)},e.prototype.renderComponent=function(){var t=this.getGui(),e=this.config,o=e.alwaysOnTop,n=e.modal,i=this.popupService.addPopup({modal:n,eChild:t,closeOnEsc:!0,closedCallback:this.destroy.bind(this),alwaysOnTop:o});i&&(this.close=i.hideFunc)},e.prototype.addResizers=function(){var t=this.getGui();if(t){var e=(new DOMParser).parseFromString(this.RESIZE_TEMPLATE,"text/html").body;t.appendChild(e.firstChild),this.createMap()}},e.prototype.createMap=function(){var t=this.getGui();this.resizerMap={topLeft:{element:t.querySelector("[ref=eTopLeftResizer]")},top:{element:t.querySelector("[ref=eTopResizer]")},topRight:{element:t.querySelector("[ref=eTopRightResizer]")},right:{element:t.querySelector("[ref=eRightResizer]")},bottomRight:{element:t.querySelector("[ref=eBottomRightResizer]")},bottom:{element:t.querySelector("[ref=eBottomResizer]")},bottomLeft:{element:t.querySelector("[ref=eBottomLeftResizer]")},left:{element:t.querySelector("[ref=eLeftResizer]")}}},e.prototype.getResizerElement=function(t){return this.resizerMap[t].element},e.prototype.onResizeStart=function(t){this.isResizing=!0,this.updateDragStartPosition(t.clientX,t.clientY)},e.prototype.onResize=function(t,e){if(this.isResizing){var o=!!e.match(/left/i),n=!!e.match(/right/i),i=!!e.match(/top/i),r=!!e.match(/bottom/i),s=o||n,a=i||r,l=this.calculateMouseMovement({e:t,isLeft:o,isTop:i}),p=l.movementX,u=l.movementY,c=0,d=0;if(s&&p){var h=o?-1:1,f=this.getWidth(),g=f+p*h,y=!1;o&&(c=f-g,(this.position.x+c<=0||g<=this.minWidth)&&(y=!0,c=0)),y||this.setWidth(g)}if(a&&u){h=i?-1:1;var v=this.getHeight(),m=v+u*h,C=!1;i&&(d=v-m,(this.position.y+d<=0||m<=this.minHeight)&&(C=!0,d=0)),C||this.setHeight(m)}this.updateDragStartPosition(t.clientX,t.clientY),(c||d)&&this.offsetElement(this.position.x+c,this.position.y+d)}},e.prototype.onResizeEnd=function(){this.isResizing=!1;var t={type:"resize",api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi()};this.dispatchEvent(t)},e.prototype.onMoveStart=function(t){this.isMoving=!0,this.updateDragStartPosition(t.clientX,t.clientY)},e.prototype.onMove=function(t){if(this.isMoving){var e=this.position,o=e.x,n=e.y,i=this.calculateMouseMovement({e:t,isTop:!0,anywhereWithin:!0,topBuffer:this.getHeight()-this.getBodyHeight()}),r=i.movementX,s=i.movementY;this.offsetElement(o+r,n+s),this.updateDragStartPosition(t.clientX,t.clientY)}},e.prototype.onMoveEnd=function(){this.isMoving=!1},e.prototype.toggleMaximize=function(){if(this.isMaximized){var t=this.lastPosition,e=t.x,o=t.y,n=t.width,i=t.height;this.setWidth(n),this.setHeight(i),this.offsetElement(e,o)}else this.lastPosition.width=this.getWidth(),this.lastPosition.height=this.getHeight(),this.lastPosition.x=this.position.x,this.lastPosition.y=this.position.y,this.offsetElement(0,0),this.setHeight("100%"),this.setWidth("100%");this.isMaximized=!this.isMaximized,this.refreshMaximizeIcon()},e.prototype.refreshMaximizeIcon=function(){ke(this.maximizeIcon,!this.isMaximized),ke(this.minimizeIcon,this.isMaximized)},e.prototype.clearMaximizebleListeners=function(){this.maximizeListeners.length&&(this.maximizeListeners.forEach((function(t){return t()})),this.maximizeListeners.length=0),this.resizeListenerDestroy&&(this.resizeListenerDestroy(),this.resizeListenerDestroy=null)},e.prototype.destroy=function(){this.setResizable(!1),this.setMovable(!1),this.maximizeButtonComp=this.destroyBean(this.maximizeButtonComp),this.clearMaximizebleListeners(),t.prototype.destroy.call(this)},e.prototype.setResizable=function(t){var e=this;"boolean"==typeof t&&(t={topLeft:t,top:t,topRight:t,right:t,bottomRight:t,bottom:t,bottomLeft:t,left:t}),Object.keys(t).forEach((function(o){var n=o,i=!!t[n],r=e.getResizerElement(n),s=e.resizerMap[n].dragSource||{eElement:r,onDragStart:e.onResizeStart.bind(e),onDragging:function(t){return e.onResize(t,n)},onDragStop:e.onResizeEnd.bind(e)};!!e.resizable[n]===i&&(e.isAlive()||i)||(i?(e.dragService.addDragSource(s),r.style.pointerEvents="all"):(e.dragService.removeDragSource(s),r.style.pointerEvents="none"),e.resizerMap[n].dragSource=i?s:void 0)}))},e.prototype.setMovable=function(t){if(t!==this.movable){this.movable=t;var e=this.moveElementDragListener||{eElement:this.moveElement,onDragStart:this.onMoveStart.bind(this),onDragging:this.onMove.bind(this),onDragStop:this.onMoveEnd.bind(this)};t?(this.dragService.addDragSource(e),this.moveElementDragListener=e):(this.dragService.removeDragSource(e),this.moveElementDragListener=void 0)}},e.prototype.setMaximizable=function(t){var e=this;if(!t)return this.clearMaximizebleListeners(),void(this.maximizeButtonComp&&(this.destroyBean(this.maximizeButtonComp),this.maximizeButtonComp=this.maximizeIcon=this.minimizeIcon=void 0));var o=this.eTitleBar;if(o&&t!==this.isMaximizable){var n=this.maximizeButtonComp=this.createBean(new xn('<div class="ag-dialog-button"></span>')),i=n.getGui();i.appendChild(this.maximizeIcon=cn("maximize",this.gridOptionsWrapper)),Me(this.maximizeIcon,"ag-panel-title-bar-button-icon"),i.appendChild(this.minimizeIcon=cn("minimize",this.gridOptionsWrapper)),Me(this.minimizeIcon,"ag-panel-title-bar-button-icon"),Me(this.minimizeIcon,"ag-hidden"),n.addManagedListener(i,"click",this.toggleMaximize.bind(this)),this.addTitleBarButton(n,0),this.maximizeListeners.push(this.addManagedListener(o,"dblclick",this.toggleMaximize.bind(this))),this.resizeListenerDestroy=this.addManagedListener(this,"resize",(function(){e.isMaximized=!1,e.refreshMaximizeIcon()}))}},Pp([it("dragService")],e.prototype,"dragService",void 0),e}(Rp),bp=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Dp=function(t){function o(e,o,n){return void 0===o&&(o="ag-text-field"),void 0===n&&(n="text"),t.call(this,e,o,n)||this}return bp(o,t),o.prototype.postConstruct=function(){t.prototype.postConstruct.call(this),this.config.allowedCharPattern&&this.preventDisallowedCharacters()},o.prototype.setValue=function(o,n){var i=t.prototype.setValue.call(this,o,n);return this.eInput.value!==o&&(this.eInput.value=e(o)?o:""),i},o.prototype.preventDisallowedCharacters=function(){var t=new RegExp("["+this.config.allowedCharPattern+"]");this.addManagedListener(this.eInput,"keypress",(function(e){e.key&&!t.test(e.key)&&e.preventDefault()})),this.addManagedListener(this.eInput,"paste",(function(e){O(e.clipboardData.getData("text"),(function(e){return!t.test(e)}))&&e.preventDefault()}))},o}(Ws),Ap=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Tp=(function(t){function e(e){return t.call(this,e,"ag-text-area",null,"textarea")||this}Ap(e,t),e.prototype.setValue=function(e,o){var n=t.prototype.setValue.call(this,e,o);return this.eInput.value=e,n},e.prototype.setCols=function(t){return this.eInput.cols=t,this},e.prototype.setRows=function(t){return this.eInput.rows=t,this}}(Ws),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),_p=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Fp=(function(t){function e(o){var n=t.call(this,o,e.TEMPLATE)||this;return n.labelAlignment="top",n}Tp(e,t),e.prototype.init=function(){Me(this.eSlider.getGui(),"ag-slider-field")},e.prototype.onValueChange=function(t){var e=this,o=xs.EVENT_CHANGED;return this.addManagedListener(this.eText,o,(function(){var o=parseFloat(e.eText.getValue());e.eSlider.setValue(o.toString(),!0),t(o||0)})),this.addManagedListener(this.eSlider,o,(function(){var o=e.eSlider.getValue();e.eText.setValue(o,!0),t(parseFloat(o))})),this},e.prototype.setSliderWidth=function(t){return this.eSlider.setWidth(t),this},e.prototype.setTextFieldWidth=function(t){return this.eText.setWidth(t),this},e.prototype.setMinValue=function(t){return this.eSlider.setMinValue(t),this.eText.setMin(t),this},e.prototype.setMaxValue=function(t){return this.eSlider.setMaxValue(t),this.eText.setMax(t),this},e.prototype.getValue=function(){return this.eText.getValue()},e.prototype.setValue=function(t){return this.getValue()===t||(this.eText.setValue(t,!0),this.eSlider.setValue(t,!0),this.dispatchEvent({type:xs.EVENT_CHANGED})),this},e.prototype.setStep=function(t){return this.eSlider.setStep(t),this.eText.setStep(t),this},e.TEMPLATE='<div class="ag-slider">\n <label ref="eLabel"></label>\n <div class="ag-wrapper ag-slider-wrapper">\n <ag-input-range ref="eSlider"></ag-input-range>\n <ag-input-number-field ref="eText"></ag-input-number-field>\n </div>\n </div>',_p([Wn("eLabel")],e.prototype,"eLabel",void 0),_p([Wn("eSlider")],e.prototype,"eSlider",void 0),_p([Wn("eText")],e.prototype,"eText",void 0),_p([et],e.prototype,"init",null)}(Gs),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Np=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Lp=function(t){function o(e){var n=t.call(this,o.TEMPLATE)||this;return n.H=1,n.S=1,n.B=1,n.A=1,n.isSpectrumDragging=!1,n.isSpectrumHueDragging=!1,n.isSpectrumAlphaDragging=!1,n.colorChanged=!1,n.picker=e.picker,n}return Fp(o,t),o.prototype.postConstruct=function(){var t=this.getGui();this.initRecentColors(),this.addManagedListener(this.spectrumVal,"mousedown",this.onSpectrumDraggerDown.bind(this)),this.addManagedListener(t,"mousemove",this.onSpectrumDraggerMove.bind(this)),this.addManagedListener(this.spectrumHue,"mousedown",this.onSpectrumHueDown.bind(this)),this.addManagedListener(t,"mousemove",this.onSpectrumHueMove.bind(this)),this.addManagedListener(this.spectrumAlpha,"mousedown",this.onSpectrumAlphaDown.bind(this)),this.addManagedListener(t,"mousemove",this.onSpectrumAlphaMove.bind(this)),this.addManagedListener(document,"mouseup",this.onMouseUp.bind(this)),this.addManagedListener(this.recentColors,"click",this.onRecentColorClick.bind(this))},o.prototype.refreshSpectrumRect=function(){return this.spectrumValRect=this.spectrumVal.getBoundingClientRect()},o.prototype.refreshHueRect=function(){return this.spectrumHueRect=this.spectrumHue.getBoundingClientRect()},o.prototype.refreshAlphaRect=function(){return this.spectrumAlphaRect=this.spectrumAlpha.getBoundingClientRect()},o.prototype.onSpectrumDraggerDown=function(t){this.refreshSpectrumRect(),this.isSpectrumDragging=!0,this.moveDragger(t)},o.prototype.onSpectrumDraggerMove=function(t){this.isSpectrumDragging&&this.moveDragger(t)},o.prototype.onSpectrumHueDown=function(t){this.refreshHueRect(),this.isSpectrumHueDragging=!0,this.moveHueSlider(t)},o.prototype.onSpectrumHueMove=function(t){this.isSpectrumHueDragging&&this.moveHueSlider(t)},o.prototype.onSpectrumAlphaDown=function(t){this.refreshAlphaRect(),this.isSpectrumAlphaDragging=!0,this.moveAlphaSlider(t)},o.prototype.onSpectrumAlphaMove=function(t){this.isSpectrumAlphaDragging&&this.moveAlphaSlider(t)},o.prototype.onMouseUp=function(){this.isSpectrumDragging=!1,this.isSpectrumHueDragging=!1,this.isSpectrumAlphaDragging=!1},o.prototype.moveDragger=function(t){var e=this.spectrumValRect;if(e){var o=t.clientX-e.left,n=t.clientY-e.top;o=Math.max(o,0),o=Math.min(o,e.width),n=Math.max(n,0),n=Math.min(n,e.height),this.setSpectrumValue(o/e.width,1-n/e.height)}},o.prototype.moveHueSlider=function(t){var e=this.spectrumHueRect;if(e){var o=this.spectrumHueSlider,n=o.getBoundingClientRect(),i=t.clientX-e.left;i=Math.max(i,0),i=Math.min(i,e.width),this.H=1-i/e.width,o.style.left=i+n.width/2+"px",this.update()}},o.prototype.moveAlphaSlider=function(t){var e=this.spectrumAlphaRect;if(e){var o=this.spectrumAlphaSlider,n=o.getBoundingClientRect(),i=t.clientX-e.left;i=Math.max(i,0),i=Math.min(i,e.width),this.A=i/e.width,o.style.left=i+n.width/2+"px",this.update()}},o.prototype.update=function(){var t=ge.fromHSB(360*this.H,this.S,this.B,this.A),e=ge.fromHSB(360*this.H,1,1),o=t.toRgbaString(),n=this.picker;ge.fromString(n.getValue()).toRgbaString()!==o&&(this.colorChanged=!0),n.setValue(o),this.spectrumColor.style.backgroundColor=e.toRgbaString(),this.spectrumDragger.style.backgroundColor=o},o.prototype.setSpectrumValue=function(t,e){var o=this.spectrumValRect||this.refreshSpectrumRect();if(o){var n=this.spectrumDragger,i=n.getBoundingClientRect();t=Math.max(0,t),t=Math.min(1,t),e=Math.max(0,e),e=Math.min(1,e),this.S=t,this.B=e,n.style.left=t*o.width-i.width/2+"px",n.style.top=(1-e)*o.height-i.height/2+"px",this.update()}},o.prototype.initRecentColors=function(){var t=o.recentColors.map((function(t,e){return'<div class="ag-recent-color" id='+e+' style="background-color: '+t+'; width: 15px; height: 15px;" recent-color="'+t+'"></div>'}));this.recentColors.innerHTML=t.join("")},o.prototype.setValue=function(t){var e=ge.fromString(t),o=e.toHSB(),n=o[0],i=o[1],r=o[2];this.H=(isNaN(n)?0:n)/360,this.A=e.a;var s=this.spectrumHueRect||this.refreshHueRect(),a=this.spectrumAlphaRect||this.refreshAlphaRect();this.spectrumHueSlider.style.left=(this.H-1)*-s.width+"px",this.spectrumAlphaSlider.style.left=this.A*a.width+"px",this.setSpectrumValue(i,r)},o.prototype.onRecentColorClick=function(t){var n=t.target;if(e(n.id)){var i=parseInt(n.id,10);this.setValue(o.recentColors[i]),this.destroy()}},o.prototype.addRecentColor=function(){var t=ge.fromHSB(360*this.H,this.S,this.B,this.A).toRgbaString(),e=o.recentColors;this.colorChanged&&e[0]!==t&&(e=e.filter((function(e){return e!=t})),(e=[t].concat(e)).length>o.maxRecentColors&&(e=e.slice(0,o.maxRecentColors)),o.recentColors=e)},o.prototype.destroy=function(){this.addRecentColor(),t.prototype.destroy.call(this)},o.maxRecentColors=8,o.recentColors=[],o.TEMPLATE='<div class="ag-color-panel">\n <div ref="spectrumColor" class="ag-spectrum-color">\n <div class="ag-spectrum-sat ag-spectrum-fill">\n <div ref="spectrumVal" class="ag-spectrum-val ag-spectrum-fill">\n <div ref="spectrumDragger" class="ag-spectrum-dragger"></div>\n </div>\n </div>\n </div>\n <div class="ag-spectrum-tools">\n <div ref="spectrumHue" class="ag-spectrum-hue ag-spectrum-tool">\n <div class="ag-spectrum-hue-background"></div>\n <div ref="spectrumHueSlider" class="ag-spectrum-slider"></div>\n </div>\n <div ref="spectrumAlpha" class="ag-spectrum-alpha ag-spectrum-tool">\n <div class="ag-spectrum-alpha-background"></div>\n <div ref="spectrumAlphaSlider" class="ag-spectrum-slider"></div>\n </div>\n <div ref="recentColors" class="ag-recent-colors"></div>\n </div>\n </div>',Np([Wn("spectrumColor")],o.prototype,"spectrumColor",void 0),Np([Wn("spectrumVal")],o.prototype,"spectrumVal",void 0),Np([Wn("spectrumDragger")],o.prototype,"spectrumDragger",void 0),Np([Wn("spectrumHue")],o.prototype,"spectrumHue",void 0),Np([Wn("spectrumHueSlider")],o.prototype,"spectrumHueSlider",void 0),Np([Wn("spectrumAlpha")],o.prototype,"spectrumAlpha",void 0),Np([Wn("spectrumAlphaSlider")],o.prototype,"spectrumAlphaSlider",void 0),Np([Wn("recentColors")],o.prototype,"recentColors",void 0),Np([et],o.prototype,"postConstruct",null),o}(xn),Ip=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Gp=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Mp=function(t){function o(e,o,n,i){var r=t.call(this,e,'<div class="ag-picker-field" role="presentation">\n <div ref="eLabel"></div>\n <div ref="eWrapper"\n class="ag-wrapper ag-picker-field-wrapper"\n tabIndex="-1"\n '+(i?'aria-haspopup="'+i+'"':"")+'\n >\n <div ref="eDisplayField" class="ag-picker-field-display"></div>\n <div ref="eIcon" class="ag-picker-field-icon" aria-hidden="true"></div>\n </div>\n </div>',o)||this;return r.pickerIcon=n,r.isPickerDisplayed=!1,r.isDestroyingPicker=!1,r.skipClick=!1,r}return Ip(o,t),o.prototype.postConstruct=function(){var e=this;t.prototype.postConstruct.call(this);var o=this.getCompId()+"-display";this.eDisplayField.setAttribute("id",o),Mo(this.eWrapper,o);var n=function(){e.skipClick?e.skipClick=!1:e.isDisabled()||(e.pickerComponent=e.showPicker())},i=this.getGui();if(this.addManagedListener(i,"mousedown",(function(t){!e.skipClick&&e.pickerComponent&&e.pickerComponent.isAlive()&&eo(e.pickerComponent.getGui())&&i.contains(t.target)&&(e.skipClick=!0)})),this.addManagedListener(i,"keydown",(function(t){switch(t.keyCode){case jn.UP:case jn.DOWN:case jn.ENTER:case jn.SPACE:n();case jn.ESCAPE:e.isPickerDisplayed&&t.preventDefault()}})),this.addManagedListener(this.eWrapper,"click",n),this.addManagedListener(this.eLabel,"click",n),this.pickerIcon){var r=cn(this.pickerIcon,this.gridOptionsWrapper);r&&this.eIcon.appendChild(r)}},o.prototype.refreshLabel=function(){e(this.getLabel())?Go(this.eWrapper,this.getLabelId()):this.eWrapper.removeAttribute("aria-labelledby"),t.prototype.refreshLabel.call(this)},o.prototype.setAriaLabel=function(t){return Io(this.eWrapper,t),this},o.prototype.setInputWidth=function(t){return ho(this.eWrapper,t),this},o.prototype.getFocusableElement=function(){return this.eWrapper},Gp([Wn("eLabel")],o.prototype,"eLabel",void 0),Gp([Wn("eWrapper")],o.prototype,"eWrapper",void 0),Gp([Wn("eDisplayField")],o.prototype,"eDisplayField",void 0),Gp([Wn("eIcon")],o.prototype,"eIcon",void 0),o}(xs),xp=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Vp=(function(t){function e(e){var o=t.call(this,e,"ag-color-picker","colorPicker")||this;return e&&e.color&&(o.value=e.color),o}xp(e,t),e.prototype.postConstruct=function(){t.prototype.postConstruct.call(this),this.value&&this.setValue(this.value)},e.prototype.showPicker=function(){var t=this,e=this.getGui().getBoundingClientRect(),o=this.createBean(new Sp({closable:!1,modal:!0,hideTitleBar:!0,minWidth:190,width:190,height:250,x:e.right-190,y:e.top-250}));this.isPickerDisplayed=!0,Me(o.getGui(),"ag-color-dialog");var n=this.createBean(new Lp({picker:this}));return n.addDestroyFunc((function(){o.isAlive()&&t.destroyBean(o)})),o.setParentComponent(this),o.setBodyComponent(n),n.setValue(this.getValue()),o.addDestroyFunc((function(){t.isDestroyingPicker?t.isDestroyingPicker=!1:(t.isDestroyingPicker=!0,n.isAlive()&&t.destroyBean(n)),t.isAlive()&&t.getFocusableElement().focus(),t.isPickerDisplayed=!1})),o},e.prototype.setValue=function(e){return this.value===e?this:(this.eDisplayField.style.backgroundColor=e,t.prototype.setValue.call(this,e))},e.prototype.getValue=function(){return this.value}}(Mp),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Hp=(function(t){function e(e){return t.call(this,e,"ag-number-field","number")||this}Vp(e,t),e.prototype.postConstruct=function(){var e=this;t.prototype.postConstruct.call(this),this.addManagedListener(this.eInput,"blur",(function(){var t=parseFloat(e.eInput.value),o=isNaN(t)?"":e.normalizeValue(t.toString());e.value!==o&&e.setValue(o)}))},e.prototype.normalizeValue=function(t){if(""===t)return"";this.precision&&(t=this.adjustPrecision(t));var e=parseFloat(t);return null!=this.min&&e<this.min?t=this.min.toString():null!=this.max&&e>this.max&&(t=this.max.toString()),t},e.prototype.adjustPrecision=function(t){if(this.precision){var e=parseFloat(t).toFixed(this.precision);t=parseFloat(e).toString()}return t},e.prototype.setMin=function(t){return this.min===t||(this.min=t,Ro(this.eInput,"min",t)),this},e.prototype.setMax=function(t){return this.max===t||(this.max=t,Ro(this.eInput,"max",t)),this},e.prototype.setPrecision=function(t){return this.precision=t,this},e.prototype.setStep=function(t){return this.step===t||(this.step=t,Ro(this.eInput,"step",t)),this},e.prototype.setValue=function(e,o){return(e=this.adjustPrecision(e))!=this.normalizeValue(e)?this:t.prototype.setValue.call(this,e,o)}}(Dp),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Wp=(function(t){function e(e){return t.call(this,e,"ag-range-field","range")||this}Hp(e,t),e.prototype.postConstruct=function(){t.prototype.postConstruct.call(this);var e=this.config,o=e.min,n=e.max,i=e.step;null!=o&&this.setMinValue(o),null!=n&&this.setMaxValue(n),this.setStep(i||1)},e.prototype.addInputListeners=function(){var t=this,e=Oe()?"change":"input";this.addManagedListener(this.eInput,e,(function(e){var o=e.target.value;t.setValue(o)}))},e.prototype.setMinValue=function(t){return this.min=t,this.eInput.setAttribute("min",t.toString()),this},e.prototype.setMaxValue=function(t){return this.max=t,this.eInput.setAttribute("max",t.toString()),this},e.prototype.setStep=function(t){return this.eInput.setAttribute("step",t.toString()),this},e.prototype.setValue=function(e,o){null!=this.min&&(e=Math.max(parseFloat(e),this.min).toString()),null!=this.max&&(e=Math.min(parseFloat(e),this.max).toString());var n=t.prototype.setValue.call(this,e,o);return this.eInput.value=e,n}}(Ws),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),kp=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Bp=function(t){function e(e){void 0===e&&(e="default");var o=t.call(this,'<div class="ag-list ag-'+e+'-list" role="listbox"></div>')||this;return o.cssIdentifier=e,o.options=[],o.itemEls=[],o}return Wp(e,t),e.prototype.init=function(){this.addManagedListener(this.getGui(),"keydown",this.handleKeyDown.bind(this))},e.prototype.handleKeyDown=function(t){var e=t.keyCode;switch(e){case jn.ENTER:if(this.highlightedEl){var o=this.itemEls.indexOf(this.highlightedEl);this.setValueByIndex(o)}else this.setValue(this.getValue());break;case jn.DOWN:case jn.UP:var n=e===jn.DOWN,i=void 0;if(t.preventDefault(),this.highlightedEl){var r=this.itemEls.indexOf(this.highlightedEl)+(n?1:-1);r=Math.min(Math.max(r,0),this.itemEls.length-1),i=this.itemEls[r]}else i=this.itemEls[n?0:this.itemEls.length-1];this.highlightItem(i)}},e.prototype.addOptions=function(t){var e=this;return t.forEach((function(t){return e.addOption(t)})),this},e.prototype.addOption=function(t){var e=t.value,o=Kt(t.text||e);return this.options.push({value:e,text:o}),this.renderOption(e,o),this},e.prototype.renderOption=function(t,e){var o=this,n=document.createElement("div");n.setAttribute("role","option"),Me(n,"ag-list-item"),Me(n,"ag-"+this.cssIdentifier+"-list-item"),n.innerHTML="<span>"+e+"</span>",n.tabIndex=-1,this.itemEls.push(n),this.addManagedListener(n,"mouseover",(function(){return o.highlightItem(n)})),this.addManagedListener(n,"mouseleave",(function(){return o.clearHighlighted()})),this.addManagedListener(n,"click",(function(){return o.setValue(t)})),this.getGui().appendChild(n)},e.prototype.setValue=function(t,e){if(this.value===t)return this.fireItemSelected(),this;if(null==t)return this.reset(),this;var o=E(this.options,(function(e){return e.value===t}));if(-1!==o){var n=this.options[o];this.value=n.value,this.displayValue=null!=n.text?n.text:n.value,this.highlightItem(this.itemEls[o]),e||this.fireChangeEvent()}return this},e.prototype.setValueByIndex=function(t){return this.setValue(this.options[t].value)},e.prototype.getValue=function(){return this.value},e.prototype.getDisplayValue=function(){return this.displayValue},e.prototype.refreshHighlighted=function(){var t=this;this.clearHighlighted();var e=E(this.options,(function(e){return e.value===t.value}));-1!==e&&this.highlightItem(this.itemEls[e])},e.prototype.reset=function(){this.value=null,this.displayValue=null,this.clearHighlighted(),this.fireChangeEvent()},e.prototype.highlightItem=function(t){t.offsetParent&&(this.clearHighlighted(),this.highlightedEl=t,Me(this.highlightedEl,e.ACTIVE_CLASS),Qo(this.highlightedEl,!0),this.highlightedEl.focus())},e.prototype.clearHighlighted=function(){this.highlightedEl&&this.highlightedEl.offsetParent&&(xe(this.highlightedEl,e.ACTIVE_CLASS),Qo(this.highlightedEl,!1),this.highlightedEl=null)},e.prototype.fireChangeEvent=function(){this.dispatchEvent({type:xs.EVENT_CHANGED}),this.fireItemSelected()},e.prototype.fireItemSelected=function(){this.dispatchEvent({type:e.EVENT_ITEM_SELECTED})},e.EVENT_ITEM_SELECTED="selectedItem",e.ACTIVE_CLASS="ag-active-item",kp([et],e.prototype,"init",null),e}(xn),jp=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Up=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},zp=(function(t){function e(e){return t.call(this,e,"ag-select","smallDown","listbox")||this}jp(e,t),e.prototype.init=function(){var t=this;this.listComponent=this.createBean(new Bp("select")),this.listComponent.setParentComponent(this),this.eWrapper.tabIndex=0,this.listComponent.addManagedListener(this.listComponent,Bp.EVENT_ITEM_SELECTED,(function(){t.hideList&&t.hideList()})),this.listComponent.addManagedListener(this.listComponent,xs.EVENT_CHANGED,(function(){t.setValue(t.listComponent.getValue(),!1,!0),t.hideList&&t.hideList()}))},e.prototype.showPicker=function(){var t=this,e=this.listComponent.getGui(),o=this.addManagedListener(document.body,"wheel",(function(o){!e.contains(o.target)&&t.hideList&&t.hideList()})),n=this.addManagedListener(e,"focusout",(function(o){!e.contains(o.relatedTarget)&&t.hideList&&t.hideList()})),i=this.popupService.addPopup({modal:!0,eChild:e,closeOnEsc:!0,closedCallback:function(){t.hideList=null,t.isPickerDisplayed=!1,n(),o(),t.isAlive()&&t.getFocusableElement().focus()}});return i&&(this.hideList=i.hideFunc),this.isPickerDisplayed=!0,ho(e,Xe(this.eWrapper)),e.style.maxHeight=Ke(this.popupService.getPopupParent())+"px",e.style.position="absolute",this.popupService.positionPopupUnderComponent({type:"ag-list",eventSource:this.eWrapper,ePopup:e,keepWithinBounds:!0}),this.listComponent.refreshHighlighted(),this.listComponent},e.prototype.addOptions=function(t){var e=this;return t.forEach((function(t){return e.addOption(t)})),this},e.prototype.addOption=function(t){return this.listComponent.addOption(t),this},e.prototype.setValue=function(e,o,n){return this.value===e?this:(n||this.listComponent.setValue(e,!0),this.listComponent.getValue()===this.getValue()?this:(this.eDisplayField.innerHTML=this.listComponent.getDisplayValue(),t.prototype.setValue.call(this,e,o)))},e.prototype.destroy=function(){this.hideList&&this.hideList(),this.destroyBean(this.listComponent),t.prototype.destroy.call(this)},Up([it("popupService")],e.prototype,"popupService",void 0),Up([et],e.prototype,"init",null)}(Mp),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Kp=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Yp=(function(t){function o(e){var n=t.call(this,e,o.TEMPLATE)||this;return n.radius=0,n.offsetX=0,n.offsetY=0,n}zp(o,t),o.prototype.postConstruct=function(){var o=this;t.prototype.postConstruct.call(this),this.dragListener={eElement:this.eParentCircle,dragStartPixels:0,onDragStart:function(t){o.parentCircleRect=o.eParentCircle.getBoundingClientRect()},onDragging:function(t){return o.calculateAngleDrag(t)},onDragStop:function(){}},this.dragService.addDragSource(this.dragListener),this.eAngleValue.setLabel("").setLabelWidth(5).setInputWidth(45).setMin(0).setMax(360).setValue(""+this.degrees).onValueChange((function(t){null!=t&&""!==t||(t="0"),t=o.eAngleValue.normalizeValue(t);var e=parseFloat(t);e>180&&(e-=360),o.setValue(e)})),this.updateNumberInput(),e(this.getValue())&&this.eAngleValue.setValue(this.normalizeNegativeValue(this.getValue()).toString()),this.addManagedListener(this,xs.EVENT_CHANGED,(function(){o.eAngleValue.getInputElement().contains(document.activeElement)||o.updateNumberInput()}))},o.prototype.updateNumberInput=function(){var t=this.normalizeNegativeValue(this.getValue());this.eAngleValue.setValue(t.toString())},o.prototype.positionChildCircle=function(t){var e=this.parentCircleRect||{width:24,height:24},o=this.eChildCircle,n=e.width/2,i=e.height/2;o.style.left=n+8*Math.cos(t)+"px",o.style.top=i+8*Math.sin(t)+"px"},o.prototype.calculatePolar=function(){var t=this.offsetX,e=this.offsetY,o=Math.atan2(e,t);this.degrees=this.toDegrees(o),this.radius=Math.sqrt(t*t+e*e),this.positionChildCircle(o)},o.prototype.calculateCartesian=function(){var t=this.toRadians(this.getValue()),e=this.getRadius();this.setOffsetX(Math.cos(t)*e).setOffsetY(Math.sin(t)*e)},o.prototype.setOffsetX=function(t){return this.offsetX!==t&&(this.offsetX=t,this.calculatePolar()),this},o.prototype.setOffsetY=function(t){return this.offsetY!==t&&(this.offsetY=t,this.calculatePolar()),this},o.prototype.calculateAngleDrag=function(t){var e=this.parentCircleRect,o=e.width/2,n=e.height/2,i=t.clientX-e.left-o,r=t.clientY-e.top-n,s=Math.atan2(r,i);this.setValue(s,!0)},o.prototype.toDegrees=function(t){return t/Math.PI*180},o.prototype.toRadians=function(t){return t/180*Math.PI},o.prototype.normalizeNegativeValue=function(t){return t<0?360+t:t},o.prototype.normalizeAngle180=function(t){return(t%=2*Math.PI)<-Math.PI?t+=2*Math.PI:t>=Math.PI&&(t-=2*Math.PI),t},o.prototype.getRadius=function(){return this.radius},o.prototype.setRadius=function(t){return this.radius===t||(this.radius=t,this.calculateCartesian()),this},o.prototype.onValueChange=function(t){var e=this;return this.addManagedListener(this,xs.EVENT_CHANGED,(function(){t(e.degrees)})),this},o.prototype.getValue=function(t){return t?this.toRadians(this.degrees):this.degrees},o.prototype.setValue=function(t,e){var o;return o=e?t:this.normalizeAngle180(this.toRadians(t)),t=this.toDegrees(o),this.degrees!==t&&(this.degrees=Math.floor(t),this.calculateCartesian(),this.positionChildCircle(o),this.dispatchEvent({type:xs.EVENT_CHANGED})),this},o.prototype.setWidth=function(t){return fo(this.getGui(),t),this},o.prototype.destroy=function(){this.dragService.removeDragSource(this.dragListener),t.prototype.destroy.call(this)},o.TEMPLATE='<div class="ag-angle-select">\n <div ref="eLabel"></div>\n <div class="ag-wrapper ag-angle-select-wrapper">\n <div ref="eAngleSelectField" class="ag-angle-select-field">\n <div ref="eParentCircle" class="ag-angle-select-parent-circle">\n <div ref="eChildCircle" class="ag-angle-select-child-circle"></div>\n </div>\n </div>\n <ag-input-number-field ref="eAngleValue"></ag-input-number-field>\n </div>\n </div>',Kp([Wn("eLabel")],o.prototype,"eLabel",void 0),Kp([Wn("eParentCircle")],o.prototype,"eParentCircle",void 0),Kp([Wn("eChildCircle")],o.prototype,"eChildCircle",void 0),Kp([Wn("eAngleValue")],o.prototype,"eAngleValue",void 0),Kp([it("dragService")],o.prototype,"dragService",void 0)}(Gs),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),qp=(function(t){function e(e){return t.call(this,e,"ag-toggle-button")||this}Yp(e,t),e.prototype.setValue=function(e,o){return t.prototype.setValue.call(this,e,o),Ve(this.getGui(),"ag-selected",this.getValue()),this}}(Bs),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Xp=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Qp=(function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.cacheItems=[],e}qp(e,t),e.prototype.postConstruct=function(){this.active=this.gridOptionsWrapper.isKeepDetailRows(),this.maxCacheSize=this.gridOptionsWrapper.getKeepDetailRowsCount()},e.prototype.addOrDestroy=function(t,e,o){if(!this.active||!t.detail)this.destroyFullWidthRow(o);else{var n=this.getCacheItem(t,!0);switch(e){case ht.PINNED_LEFT:this.destroyFullWidthRow(n.left),n.left=o;break;case ht.PINNED_RIGHT:this.destroyFullWidthRow(n.right),n.right=o;break;default:this.destroyFullWidthRow(n.center),n.center=o}this.cacheItems.sort((function(t,e){return e.lastAccessedTime-t.lastAccessedTime})),this.purgeCache(this.maxCacheSize)}},e.prototype.getCacheItem=function(t,e){void 0===e&&(e=!1);for(var o=null,n=0;n<this.cacheItems.length;n++){var i=this.cacheItems[n];if(i.rowNode===t){o=i;break}}return!o&&e&&(o={rowNode:t},this.cacheItems.push(o)),o&&this.stampCacheItem(o),o},e.prototype.stampCacheItem=function(t){t.lastAccessedTime=(new Date).getTime()},e.prototype.destroyFullWidthRow=function(t){this.getContext().destroyBean(t)},e.prototype.purgeCache=function(t){for(var e=t;e<this.cacheItems.length;e++){var o=this.cacheItems[e];this.destroyFullWidthRow(o.center),this.destroyFullWidthRow(o.left),this.destroyFullWidthRow(o.right)}this.cacheItems.length>t&&(this.cacheItems.length=t)},e.prototype.get=function(t,e){if(t.detail){var o,n=this.getCacheItem(t);if(n)switch(e){case ht.PINNED_LEFT:n.left&&(o=n.left,n.left=void 0);break;case ht.PINNED_RIGHT:n.right&&(o=n.right,n.right=void 0);break;default:n.center&&(o=n.center,n.center=void 0)}return o}},e.prototype.destroy=function(){t.prototype.destroy.call(this),this.purgeCache(0)},Xp([et],e.prototype,"postConstruct",null),Xp([ot],e.prototype,"destroy",null),e=Xp([nt("detailRowCompCache")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),$p=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Zp=(function(t){function o(){return null!==t&&t.apply(this,arguments)||this}Qp(o,t),o.prototype.getFirstRow=function(){var t,e=0;return this.pinnedRowModel.getPinnedTopRowCount()?t=ht.PINNED_TOP:this.rowModel.getRowCount()?(t=null,e=this.paginationProxy.getPageFirstRow()):this.pinnedRowModel.getPinnedBottomRowCount()&&(t=ht.PINNED_BOTTOM),void 0===t?null:{rowIndex:e,rowPinned:t}},o.prototype.getLastRow=function(){var t,e,o=this.pinnedRowModel.getPinnedBottomRowCount(),n=this.pinnedRowModel.getPinnedTopRowCount();return o?(e=ht.PINNED_BOTTOM,t=o-1):this.rowModel.getRowCount()?(e=null,t=this.paginationProxy.getPageLastRow()):n&&(e=ht.PINNED_TOP,t=n-1),void 0===t?null:{rowIndex:t,rowPinned:e}},o.prototype.getRowNode=function(t){switch(t.rowPinned){case ht.PINNED_TOP:return this.pinnedRowModel.getPinnedTopRowData()[t.rowIndex];case ht.PINNED_BOTTOM:return this.pinnedRowModel.getPinnedBottomRowData()[t.rowIndex];default:return this.rowModel.getRow(t.rowIndex)}},o.prototype.sameRow=function(t,e){return!t&&!e||!(t&&!e||!t&&e)&&(t.rowIndex===e.rowIndex&&t.rowPinned==e.rowPinned)},o.prototype.before=function(t,o){switch(t.rowPinned){case ht.PINNED_TOP:if(o.rowPinned!==ht.PINNED_TOP)return!0;break;case ht.PINNED_BOTTOM:if(o.rowPinned!==ht.PINNED_BOTTOM)return!1;break;default:if(e(o.rowPinned))return o.rowPinned!==ht.PINNED_TOP}return t.rowIndex<o.rowIndex},$p([it("rowModel")],o.prototype,"rowModel",void 0),$p([it("pinnedRowModel")],o.prototype,"pinnedRowModel",void 0),$p([it("paginationProxy")],o.prototype,"paginationProxy",void 0),o=$p([nt("rowPositionUtils")],o)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Jp=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},tu=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}Zp(e,t),e.prototype.createId=function(t){var e=t.rowIndex,o=t.rowPinned,n=t.column;return this.createIdFromValues(e,n,o)},e.prototype.createIdFromValues=function(t,e,o){return t+"."+(null==o?"null":o)+"."+e.getId()},e.prototype.equals=function(t,e){var o=t.column===e.column,n=t.rowPinned===e.rowPinned,i=t.rowIndex===e.rowIndex;return o&&n&&i},e=Jp([nt("cellPositionUtils")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),eu=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},ou=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}tu(e,t),e.prototype.init=function(){this.setPinnedTopRowData(this.gridOptionsWrapper.getPinnedTopRowData()),this.setPinnedBottomRowData(this.gridOptionsWrapper.getPinnedBottomRowData())},e.prototype.isEmpty=function(t){return n(t===ht.PINNED_TOP?this.pinnedTopRows:this.pinnedBottomRows)},e.prototype.isRowsToRender=function(t){return!this.isEmpty(t)},e.prototype.getRowAtPixel=function(t,e){var o=e===ht.PINNED_TOP?this.pinnedTopRows:this.pinnedBottomRows;if(n(o))return 0;for(var i=0;i<o.length;i++){var r=o[i];if(r.rowTop+r.rowHeight-1>=t)return i}return o.length-1},e.prototype.setPinnedTopRowData=function(t){this.pinnedTopRows=this.createNodesFromData(t,!0);var e={type:Wt.EVENT_PINNED_ROW_DATA_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(e)},e.prototype.setPinnedBottomRowData=function(t){this.pinnedBottomRows=this.createNodesFromData(t,!1);var e={type:Wt.EVENT_PINNED_ROW_DATA_CHANGED,api:this.gridApi,columnApi:this.columnApi};this.eventService.dispatchEvent(e)},e.prototype.createNodesFromData=function(t,e){var o=this,n=[];if(t){var i=0;t.forEach((function(t,r){var s=new Ci;o.context.createBean(s),s.data=t;var a=e?Ci.ID_PREFIX_TOP_PINNED:Ci.ID_PREFIX_BOTTOM_PINNED;s.id=a+r,s.rowPinned=e?ht.PINNED_TOP:ht.PINNED_BOTTOM,s.setRowTop(i),s.setRowHeight(o.gridOptionsWrapper.getRowHeightForNode(s).height),s.setRowIndex(r),i+=s.rowHeight,n.push(s)}))}return n},e.prototype.getPinnedTopRowData=function(){return this.pinnedTopRows},e.prototype.getPinnedBottomRowData=function(){return this.pinnedBottomRows},e.prototype.getPinnedTopTotalHeight=function(){return this.getTotalHeight(this.pinnedTopRows)},e.prototype.getPinnedTopRowCount=function(){return this.pinnedTopRows?this.pinnedTopRows.length:0},e.prototype.getPinnedBottomRowCount=function(){return this.pinnedBottomRows?this.pinnedBottomRows.length:0},e.prototype.getPinnedTopRow=function(t){return this.pinnedTopRows[t]},e.prototype.getPinnedBottomRow=function(t){return this.pinnedBottomRows[t]},e.prototype.forEachPinnedTopRow=function(t){n(this.pinnedTopRows)||this.pinnedTopRows.forEach(t)},e.prototype.forEachPinnedBottomRow=function(t){n(this.pinnedBottomRows)||this.pinnedBottomRows.forEach(t)},e.prototype.getPinnedBottomTotalHeight=function(){return this.getTotalHeight(this.pinnedBottomRows)},e.prototype.getTotalHeight=function(t){if(!t||0===t.length)return 0;var e=d(t);return e.rowTop+e.rowHeight},eu([it("columnApi")],e.prototype,"columnApi",void 0),eu([it("gridApi")],e.prototype,"gridApi",void 0),eu([et],e.prototype,"init",null),e=eu([nt("pinnedRowModel")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),nu=function(t){this.cellValueChanges=t},iu=function(t){function e(e,o,n){var i=t.call(this,e)||this;return i.initialRange=o,i.finalRange=n,i}return ou(e,t),e}(nu),ru=function(){function t(e){this.actionStack=[],this.maxStackSize=e||t.DEFAULT_STACK_SIZE,this.actionStack=new Array(this.maxStackSize)}return t.prototype.pop=function(){return this.actionStack.pop()},t.prototype.push=function(t){t.cellValueChanges&&t.cellValueChanges.length>0&&(this.actionStack.length===this.maxStackSize&&this.actionStack.shift(),this.actionStack.push(t))},t.prototype.clear=function(){this.actionStack=[]},t.prototype.getCurrentStackSize=function(){return this.actionStack.length},t.DEFAULT_STACK_SIZE=10,t}(),su=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),au=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},lu=(function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.cellValueChanges=[],e.isCellEditing=!1,e.isRowEditing=!1,e.isPasting=!1,e.isFilling=!1,e.onCellValueChanged=function(t){if(e.isCellEditing||e.isRowEditing||e.isPasting||e.isFilling){var o=t.rowPinned,n=t.rowIndex,i=t.column,r=t.oldValue,s=t.value,a={rowPinned:o,rowIndex:n,columnId:i.getColId(),newValue:s,oldValue:r};e.cellValueChanges.push(a)}},e.clearStacks=function(){e.undoStack.clear(),e.redoStack.clear()},e}su(e,t),e.prototype.init=function(){if(this.gridOptionsWrapper.isUndoRedoCellEditing()){var t=this.gridOptionsWrapper.getUndoRedoCellEditingLimit();t<=0||(this.undoStack=new ru(t),this.redoStack=new ru(t),this.addRowEditingListeners(),this.addCellEditingListeners(),this.addPasteListeners(),this.addFillListeners(),this.addManagedListener(this.eventService,Wt.EVENT_CELL_VALUE_CHANGED,this.onCellValueChanged),this.addManagedListener(this.eventService,Wt.EVENT_MODEL_UPDATED,this.clearStacks),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_PIVOT_MODE_CHANGED,this.clearStacks),this.addManagedListener(this.eventService,Wt.EVENT_NEW_COLUMNS_LOADED,this.clearStacks),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_GROUP_OPENED,this.clearStacks),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_ROW_GROUP_CHANGED,this.clearStacks),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_MOVED,this.clearStacks),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_PINNED,this.clearStacks),this.addManagedListener(this.eventService,Wt.EVENT_COLUMN_VISIBLE,this.clearStacks),this.addManagedListener(this.eventService,Wt.EVENT_ROW_DRAG_END,this.clearStacks))}},e.prototype.getCurrentUndoStackSize=function(){return this.undoStack?this.undoStack.getCurrentStackSize():0},e.prototype.getCurrentRedoStackSize=function(){return this.redoStack?this.redoStack.getCurrentStackSize():0},e.prototype.undo=function(){if(this.undoStack){var t=this.undoStack.pop();t&&t.cellValueChanges&&(this.processAction(t,(function(t){return t.oldValue})),t instanceof iu?this.processRangeAndCellFocus(t.cellValueChanges,t.initialRange):this.processRangeAndCellFocus(t.cellValueChanges),this.redoStack.push(t))}},e.prototype.redo=function(){if(this.redoStack){var t=this.redoStack.pop();t&&t.cellValueChanges&&(this.processAction(t,(function(t){return t.newValue})),t instanceof iu?this.processRangeAndCellFocus(t.cellValueChanges,t.finalRange):this.processRangeAndCellFocus(t.cellValueChanges),this.undoStack.push(t))}},e.prototype.processAction=function(t,e){var o=this;t.cellValueChanges.forEach((function(t){var n=t.rowIndex,i=t.rowPinned,r=t.columnId,s={rowIndex:n,rowPinned:i},a=o.getRowNode(s);a.displayed&&a.setDataValue(r,e(t))}))},e.prototype.processRangeAndCellFocus=function(t,e){var o;if(e){var n=e.startRow,i=e.endRow;o={rowPinned:n.rowPinned,rowIndex:n.rowIndex,columnId:e.startColumn.getColId()},this.setLastFocusedCell(o);var r={rowStartIndex:n.rowIndex,rowStartPinned:n.rowPinned,rowEndIndex:i.rowIndex,rowEndPinned:i.rowPinned,columnStart:e.startColumn,columns:e.columns};this.gridApi.addCellRange(r)}else{var s=t[0],a={rowIndex:s.rowIndex,rowPinned:s.rowPinned},l=this.getRowNode(a);o={rowPinned:s.rowPinned,rowIndex:l.rowIndex,columnId:s.columnId},this.setLastFocusedCell(o)}},e.prototype.setLastFocusedCell=function(t){var e=t.rowIndex,o=t.columnId,n=t.rowPinned;this.gridApi.ensureIndexVisible(e),this.gridApi.ensureColumnVisible(o),ft.isRegistered(pt.RangeSelectionModule)&&this.gridApi.clearRangeSelection(),this.focusController.setFocusedCell(e,o,n,!0)},e.prototype.addRowEditingListeners=function(){var t=this;this.addManagedListener(this.eventService,Wt.EVENT_ROW_EDITING_STARTED,(function(){t.isRowEditing=!0})),this.addManagedListener(this.eventService,Wt.EVENT_ROW_EDITING_STOPPED,(function(){var e=new nu(t.cellValueChanges);t.pushActionsToUndoStack(e),t.isRowEditing=!1}))},e.prototype.addCellEditingListeners=function(){var t=this;this.addManagedListener(this.eventService,Wt.EVENT_CELL_EDITING_STARTED,(function(){t.isCellEditing=!0})),this.addManagedListener(this.eventService,Wt.EVENT_CELL_EDITING_STOPPED,(function(){if(t.isCellEditing=!1,!t.isRowEditing&&!t.isPasting&&!t.isFilling){var e=new nu(t.cellValueChanges);t.pushActionsToUndoStack(e)}}))},e.prototype.addPasteListeners=function(){var t=this;this.addManagedListener(this.eventService,Wt.EVENT_PASTE_START,(function(){t.isPasting=!0})),this.addManagedListener(this.eventService,Wt.EVENT_PASTE_END,(function(){var e=new nu(t.cellValueChanges);t.pushActionsToUndoStack(e),t.isPasting=!1}))},e.prototype.addFillListeners=function(){var t=this;this.addManagedListener(this.eventService,Wt.EVENT_FILL_START,(function(){t.isFilling=!0})),this.addManagedListener(this.eventService,Wt.EVENT_FILL_END,(function(e){var o=new iu(t.cellValueChanges,e.initialRange,e.finalRange);t.pushActionsToUndoStack(o),t.isFilling=!1}))},e.prototype.pushActionsToUndoStack=function(t){this.undoStack.push(t),this.cellValueChanges=[],this.redoStack.clear()},e.prototype.getRowNode=function(t){switch(t.rowPinned){case ht.PINNED_TOP:return this.pinnedRowModel.getPinnedTopRowData()[t.rowIndex];case ht.PINNED_BOTTOM:return this.pinnedRowModel.getPinnedBottomRowData()[t.rowIndex];default:return this.rowModel.getRow(t.rowIndex)}},au([it("focusController")],e.prototype,"focusController",void 0),au([it("gridApi")],e.prototype,"gridApi",void 0),au([it("rowModel")],e.prototype,"rowModel",void 0),au([it("pinnedRowModel")],e.prototype,"pinnedRowModel",void 0),au([et],e.prototype,"init",null),e=au([nt("undoRedoService")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),pu=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},uu=(function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.componentsMappedByName={},e}lu(e,t),e.prototype.setupComponents=function(t){var e=this;t&&t.forEach((function(t){return e.addComponent(t)}))},e.prototype.addComponent=function(t){var e=t.componentName.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase().toUpperCase();this.componentsMappedByName[e]=t.componentClass},e.prototype.getComponentClass=function(t){return this.componentsMappedByName[t]},e=pu([nt("agStackComponentsRegistry")],e)}(Mt),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),cu=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},du=(function(t){function e(){return null!==t&&t.apply(this,arguments)||this}uu(e,t),e.prototype.findHeader=function(t,e){var o,n,i;if(t.column instanceof mt?(n="getDisplayedGroup"+e,o=this.columnController[n](t.column)):(i="getDisplayedCol"+e,o=this.columnController[i](t.column)),o)return{column:o,headerRowIndex:t.headerRowIndex}},e.prototype.findColAtEdgeForHeaderRow=function(t,e){var o=this.columnController.getAllDisplayedColumns(),n=o["start"===e?0:o.length-1];if(n){var i=this.headerNavigationService.getHeaderContainer(n.getPinned()).getRowComps()[t];return(i&&i.getType())==os.COLUMN_GROUP?{headerRowIndex:t,column:this.columnController.getColumnGroupAtLevel(n,t)}:{headerRowIndex:i?t:-1,column:n}}},cu([it("columnController")],e.prototype,"columnController",void 0),cu([it("headerNavigationService")],e.prototype,"headerNavigationService",void 0),e=cu([nt("headerPositionUtils")],e)}(Mt),function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s}),hu=(function(){function t(){}t.prototype.buildColumnDefs=function(t,e,o){var n=this,i=[],r={};return t.forEach((function(t){for(var s=!0,a=n.createDefFromColumn(t,e,o),l=t;l.getParent();){var p=l.getParent(),u=null;if(p.isPadding())l=p;else{var c=r[p.getGroupId()];if(c){c.children.push(a),s=!1;break}(u=n.createDefFromGroup(p))&&(u.children=[a],r[u.groupId]=u,a=u,l=p)}}s&&i.push(a)})),i},t.prototype.createDefFromGroup=function(t){var e=_(t.getColGroupDef(),["children"]);return e&&(e.groupId=t.getGroupId()),e},t.prototype.createDefFromColumn=function(t,e,o){var n=_(t.getColDef());return n.colId=t.getColId(),n.width=t.getActualWidth(),n.rowGroup=t.isRowGroupActive(),n.rowGroupIndex=t.isRowGroupActive()?e.indexOf(t):null,n.pivot=t.isPivotActive(),n.pivotIndex=t.isPivotActive()?o.indexOf(t):null,n.aggFunc=t.isValueActive()?t.getAggFunc():null,n.hide=!t.isVisible()||void 0,n.pinned=t.isPinned()?t.getPinned():null,n.sort=t.getSort()?t.getSort():null,n.sortIndex=null!=t.getSortIndex()?t.getSortIndex():null,n},t=du([nt("columnDefFactory")],t)}(),function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s}),fu=(function(){function t(){}t.prototype.getInitialRowClasses=function(t){var o=[];return e(t.extraCssClass)&&o.push(t.extraCssClass),o.push("ag-row"),o.push(t.rowFocused?"ag-row-focus":"ag-row-no-focus"),t.fadeRowIn&&o.push("ag-opacity-zero"),o.push(t.rowIsEven?"ag-row-even":"ag-row-odd"),t.rowNode.isRowPinned()&&o.push("ag-row-pinned"),t.rowNode.isSelected()&&o.push("ag-row-selected"),t.rowNode.footer&&o.push("ag-row-footer"),o.push("ag-row-level-"+t.rowLevel),t.rowNode.stub&&o.push("ag-row-loading"),t.fullWidthRow&&o.push("ag-full-width-row"),t.expandable&&(o.push("ag-row-group"),o.push(t.rowNode.expanded?"ag-row-group-expanded":"ag-row-group-contracted")),t.rowNode.dragging&&o.push("ag-row-dragging"),w(o,this.processClassesFromGridOptions(t.rowNode,t.scope)),w(o,this.preProcessRowClassRules(t.rowNode,t.scope)),o.push(t.printLayout?"ag-row-position-relative":"ag-row-position-absolute"),t.firstRowOnPage&&o.push("ag-row-first"),t.lastRowOnPage&&o.push("ag-row-last"),o},t.prototype.processClassesFromGridOptions=function(t,e){var o=[],n=function(t){"string"==typeof t?o.push(t):Array.isArray(t)&&t.forEach((function(t){return o.push(t)}))},i=this.gridOptionsWrapper.getRowClass();if(i){if("function"==typeof i)return console.warn("AG Grid: rowClass should not be a function, please use getRowClass instead"),[];n(i)}var r=this.gridOptionsWrapper.getRowClassFunc();r&&n(r({data:t.data,node:t,rowIndex:t.rowIndex,$scope:e,api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi(),context:this.gridOptionsWrapper.getContext()}));return o},t.prototype.preProcessRowClassRules=function(t,e){var o=[];return this.processRowClassRules(t,e,(function(t){o.push(t)}),(function(t){})),o},t.prototype.processRowClassRules=function(t,e,o,n){var i={data:t.data,node:t,rowIndex:t.rowIndex,api:this.gridOptionsWrapper.getApi(),columnApi:this.gridOptionsWrapper.getColumnApi(),$scope:e,context:this.gridOptionsWrapper.getContext()};this.stylingService.processClassRules(this.gridOptionsWrapper.rowClassRules(),i,o,n)},t.prototype.calculateRowLevel=function(t){return t.group?t.level:t.parent?t.parent.level+1:0},hu([it("stylingService")],t.prototype,"stylingService",void 0),hu([it("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),t=hu([nt("rowCssClassCalculator")],t)}(),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),gu=function(t){function e(o){var n=t.call(this)||this;return n.state=e.STATE_WAITING_TO_LOAD,n.version=0,n.id=o,n}return fu(e,t),e.prototype.getId=function(){return this.id},e.prototype.load=function(){this.state=e.STATE_LOADING,this.loadFromDatasource()},e.prototype.getVersion=function(){return this.version},e.prototype.setStateWaitingToLoad=function(){this.version++,this.state=e.STATE_WAITING_TO_LOAD},e.prototype.getState=function(){return this.state},e.prototype.pageLoadFailed=function(t){this.isRequestMostRecentAndLive(t)&&(this.state=e.STATE_FAILED,this.processServerFail()),this.dispatchLoadCompleted(!1)},e.prototype.success=function(t,e){this.successCommon(t,e)},e.prototype.pageLoaded=function(t,e,o){this.successCommon(t,{rowData:e,rowCount:o})},e.prototype.isRequestMostRecentAndLive=function(t){var e=t===this.version,o=this.isAlive();return e&&o},e.prototype.successCommon=function(t,o){this.dispatchLoadCompleted(),this.isRequestMostRecentAndLive(t)&&(this.state=e.STATE_LOADED,this.processServerResult(o))},e.prototype.dispatchLoadCompleted=function(t){void 0===t&&(t=!0);var o={type:e.EVENT_LOAD_COMPLETE,success:t,block:this};this.dispatchEvent(o)},e.EVENT_LOAD_COMPLETE="loadComplete",e.STATE_WAITING_TO_LOAD="needsLoading",e.STATE_LOADING="loading",e.STATE_LOADED="loaded",e.STATE_FAILED="failed",e}(Mt),yu=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),vu=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},mu=function(t,e){return function(o,n){e(o,n,t)}},Cu=(function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.activeBlockLoadsCount=0,e.blocks=[],e.active=!0,e}var o;yu(e,t),o=e,e.prototype.postConstruct=function(){this.maxConcurrentRequests=this.gridOptionsWrapper.getMaxConcurrentDatasourceRequests();var t=this.gridOptionsWrapper.getBlockLoadDebounceMillis();t&&t>0&&(this.checkBlockToLoadDebounce=bn.debounce(this.performCheckBlocksToLoad.bind(this),t))},e.prototype.setBeans=function(t){this.logger=t.create("RowNodeBlockLoader")},e.prototype.addBlock=function(t){this.blocks.push(t),t.addEventListener(gu.EVENT_LOAD_COMPLETE,this.loadComplete.bind(this)),this.checkBlockToLoad()},e.prototype.removeBlock=function(t){bn.removeFromArray(this.blocks,t)},e.prototype.destroy=function(){t.prototype.destroy.call(this),this.active=!1},e.prototype.loadComplete=function(){this.activeBlockLoadsCount--,this.checkBlockToLoad(),0==this.activeBlockLoadsCount&&this.dispatchEvent({type:o.BLOCK_LOADER_FINISHED_EVENT})},e.prototype.checkBlockToLoad=function(){this.checkBlockToLoadDebounce?this.checkBlockToLoadDebounce():this.performCheckBlocksToLoad()},e.prototype.performCheckBlocksToLoad=function(){if(this.active)if(this.printCacheStatus(),null!=this.maxConcurrentRequests&&this.activeBlockLoadsCount>=this.maxConcurrentRequests)this.logger.log("checkBlockToLoad: max loads exceeded");else{var t=null;this.blocks.forEach((function(e){e.getState()===gu.STATE_WAITING_TO_LOAD&&(t=e)})),t&&(t.load(),this.activeBlockLoadsCount++,this.printCacheStatus())}},e.prototype.getBlockState=function(){var t={};return this.blocks.forEach((function(e){var o=e.getBlockStateJson(),n=o.id,i=o.state;t[n]=i})),t},e.prototype.printCacheStatus=function(){this.logger.isLogging()&&this.logger.log("printCacheStatus: activePageLoadsCount = "+this.activeBlockLoadsCount+", blocks = "+JSON.stringify(this.getBlockState()))},e.prototype.isLoading=function(){return this.activeBlockLoadsCount>0},e.BLOCK_LOADER_FINISHED_EVENT="blockLoaderFinished",vu([et],e.prototype,"postConstruct",null),vu([mu(0,at("loggerFactory"))],e.prototype,"setBeans",null),e=o=vu([nt("rowNodeBlockLoader")],e)}(Mt),function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s}),wu=(function(){function t(){}t.prototype.doFullSort=function(t,e){var o=t.map((function(t,e){return{currentPos:e,rowNode:t}}));return o.sort(this.compareRowNodes.bind(this,e)),o.map((function(t){return t.rowNode}))},t.prototype.compareRowNodes=function(t,e,o){for(var n=e.rowNode,i=o.rowNode,r=0,s=t.length;r<s;r++){var a=t[r],l=a.sort===ht.SORT_DESC,p=this.getValue(n,a.column),u=this.getValue(i,a.column),c=void 0,d=a.column.getColDef().comparator;if(0!==(c=d?d(p,u,n,i,l):bn.defaultComparator(p,u,this.gridOptionsWrapper.isAccentedSort())))return a.sort===ht.SORT_ASC?c:-1*c}return e.currentPos-o.currentPos},t.prototype.getValue=function(t,e){return this.valueService.getValue(e,t)},Cu([it("gridOptionsWrapper")],t.prototype,"gridOptionsWrapper",void 0),Cu([it("valueService")],t.prototype,"valueService",void 0),t=Cu([nt("rowNodeSorter")],t)}(),function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}()),Eu=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s};!function(t){function e(o){var n=t.call(this,e.getTemplate(o.cssClass))||this;return n.items=[],n.params=o,o.items&&o.items.forEach((function(t){return n.addItem(t)})),n}wu(e,t),e.getTemplate=function(t){return'<div class="ag-tabs '+t+'">\n <div ref="eHeader" role="menu" class="ag-tabs-header '+(t?t+"-header":"")+'"></div>\n <div ref="eBody" role="presentation" class="ag-tabs-body '+(t?t+"-body":"")+'"></div>\n </div>'},e.prototype.handleKeyDown=function(t){switch(t.keyCode){case jn.RIGHT:case jn.LEFT:if(!this.eHeader.contains(document.activeElement))return;var e=this.items.indexOf(this.activeItem),o=t.keyCode===jn.RIGHT?Math.min(e+1,this.items.length-1):Math.max(e-1,0);if(e===o)return;t.preventDefault();var n=this.items[o];this.showItemWrapper(n),n.eHeaderButton.focus();break;case jn.UP:case jn.DOWN:t.stopPropagation()}},e.prototype.onTabKeyDown=function(t){if(!t.defaultPrevented){var e=this.focusController,o=this.eHeader,n=this.eBody,i=this.activeItem,r=document.activeElement;if(t.preventDefault(),o.contains(r))e.focusInto(n,t.shiftKey);else if(e.isFocusUnderManagedComponent(n))i.eHeaderButton.focus();else{var s=e.findNextFocusableElement(n,!1,t.shiftKey);s?s.focus():i.eHeaderButton.focus()}}},e.prototype.setAfterAttachedParams=function(t){this.afterAttachedParams=t},e.prototype.getMinDimensions=function(){var t=this.getGui().cloneNode(!0),e=t.querySelector('[ref="eBody"]');t.style.position="fixed",this.getGui().appendChild(t);var o=0,n=0;return this.items.forEach((function(i){Je(e);var r=i.tabbedItem.bodyPromise.resolveNow(null,(function(t){return t.cloneNode(!0)}));null!=r&&(e.appendChild(r),o<t.offsetWidth&&(o=t.offsetWidth),n<t.offsetHeight&&(n=t.offsetHeight))})),this.getGui().removeChild(t),{height:n,width:o}},e.prototype.showFirstItem=function(){this.items.length>0&&this.showItemWrapper(this.items[0])},e.prototype.addItem=function(t){var e=document.createElement("span");e.setAttribute("tabIndex","-1"),e.setAttribute("role","menuitem"),e.appendChild(t.title),Me(e,"ag-tab"),this.eHeader.appendChild(e),Io(e,t.titleLabel);var o={tabbedItem:t,eHeaderButton:e};this.items.push(o),e.addEventListener("click",this.showItemWrapper.bind(this,o))},e.prototype.showItem=function(t){var e=a(this.items,(function(e){return e.tabbedItem===t}));e&&this.showItemWrapper(e)},e.prototype.showItemWrapper=function(t){var e=this;this.params.onItemClicked&&this.params.onItemClicked({item:t.tabbedItem}),this.activeItem!==t?(Je(this.eBody),t.tabbedItem.bodyPromise.then((function(o){e.eBody.appendChild(o);var n=!e.focusController.isKeyboardMode();e.focusController.focusInto(e.eBody,!1,n),t.tabbedItem.afterAttachedCallback&&t.tabbedItem.afterAttachedCallback(e.afterAttachedParams)})),this.activeItem&&xe(this.activeItem.eHeaderButton,"ag-tab-selected"),Me(t.eHeaderButton,"ag-tab-selected"),this.activeItem=t):Z(this.params.onActiveItemClicked)},Eu([Wn("eHeader")],e.prototype,"eHeader",void 0),Eu([Wn("eBody")],e.prototype,"eBody",void 0)}(Zn);!function(t){t.StoreNotFound="StoreNotFound",t.StoreLoading="StoreLoading",t.StoreWaitingToLoad="StoreWaitingToLoad",t.StoreLoadingFailed="StoreLoadingFailed",t.StoreWrongType="StoreWrongType",t.Applied="Applied",t.Cancelled="Cancelled"}(vp||(vp={}));
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
var Ru,Ou,Pu,Su=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),bu=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s};!function(t){function e(o,n){void 0===o&&(o="default"),void 0===n&&(n="listbox");var i=t.call(this,e.getTemplate(o),!0)||this;return i.cssIdentifier=o,i.ariaRole=n,i.renderedRows=new Map,i.rowHeight=20,i.isDestroyed=!1,i}Su(e,t),e.prototype.postConstruct=function(){this.addScrollListener(),this.rowHeight=this.getItemHeight(),this.addResizeObserver(),t.prototype.postConstruct.call(this)},e.prototype.addResizeObserver=function(){var t=this.drawVirtualRows.bind(this),e=this.resizeObserverService.observeResize(this.getGui(),t);this.addDestroyFunc(e)},e.prototype.focusInnerElement=function(t){this.focusRow(t?this.model.getRowCount()-1:0)},e.prototype.onFocusIn=function(e){t.prototype.onFocusIn.call(this,e);var o=e.target;He(o,"ag-virtual-list-item")&&(this.lastFocusedRowIndex=No(o)-1)},e.prototype.onFocusOut=function(e){t.prototype.onFocusOut.call(this,e),this.getFocusableElement().contains(e.relatedTarget)||(this.lastFocusedRowIndex=null)},e.prototype.handleKeyDown=function(t){switch(t.keyCode){case jn.UP:case jn.DOWN:this.navigate(t.keyCode===jn.UP)&&t.preventDefault()}},e.prototype.onTabKeyDown=function(t){this.navigate(t.shiftKey)?t.preventDefault():this.focusController.focusInto(this.getGui(),!t.shiftKey)},e.prototype.navigate=function(t){if(null==this.lastFocusedRowIndex)return!1;var e=this.lastFocusedRowIndex+(t?-1:1);return!(e<0||e>=this.model.getRowCount())&&(this.focusRow(e),!0)},e.prototype.getLastFocusedRow=function(){return this.lastFocusedRowIndex},e.prototype.focusRow=function(t){var e=this;this.ensureIndexVisible(t),window.setTimeout((function(){var o=e.renderedRows.get(t);o&&o.eDiv.focus()}),10)},e.prototype.getComponentAt=function(t){var e=this.renderedRows.get(t);return e&&e.rowComponent},e.getTemplate=function(t){return'\n <div class="ag-virtual-list-viewport ag-'+t+'-virtual-list-viewport" role="listbox">\n <div class="ag-virtual-list-container ag-'+t+'-virtual-list-container" ref="eContainer"></div>\n </div>'},e.prototype.getItemHeight=function(){return this.gridOptionsWrapper.getListItemHeight()},e.prototype.ensureIndexVisible=function(t){var e=this.model.getRowCount();if("number"!=typeof t||t<0||t>=e)console.warn("invalid row index for ensureIndexVisible: "+t);else{var o=t*this.rowHeight,n=o+this.rowHeight,i=this.getGui(),r=i.scrollTop,s=i.offsetHeight,a=r+s<n;if(r>o)i.scrollTop=o;else if(a){var l=n-s;i.scrollTop=l}}},e.prototype.setComponentCreator=function(t){this.componentCreator=t},e.prototype.getRowHeight=function(){return this.rowHeight},e.prototype.getScrollTop=function(){return this.getGui().scrollTop},e.prototype.setRowHeight=function(t){this.rowHeight=t,this.refresh()},e.prototype.refresh=function(){var t=this;if(null!=this.model&&!this.isDestroyed){var e=this.model.getRowCount();this.eContainer.style.height=e*this.rowHeight+"px",setTimeout((function(){t.isDestroyed||(t.clearVirtualRows(),t.drawVirtualRows())}),0)}},e.prototype.clearVirtualRows=function(){var t=this;this.renderedRows.forEach((function(e,o){return t.removeRow(o)}))},e.prototype.drawVirtualRows=function(){var t=this.getGui(),e=t.scrollTop,o=e+t.offsetHeight,n=Math.floor(e/this.rowHeight),i=Math.floor(o/this.rowHeight);this.ensureRowsRendered(n,i)},e.prototype.ensureRowsRendered=function(t,e){var o=this;this.renderedRows.forEach((function(n,i){(i<t||i>e)&&i!==o.lastFocusedRowIndex&&o.removeRow(i)}));for(var n=t;n<=e;n++)this.renderedRows.has(n)||n<this.model.getRowCount()&&this.insertRow(n)},e.prototype.insertRow=function(t){var e=this,o=this.model.getRow(t),n=document.createElement("div");if(Me(n,"ag-virtual-list-item"),Me(n,"ag-"+this.cssIdentifier+"-virtual-list-item"),n.setAttribute("role","tree"===this.ariaRole?"treeitem":"option"),Wo(n,this.model.getRowCount()),ko(n,t+1),n.setAttribute("tabindex","-1"),"function"==typeof this.model.isRowSelected){var i=this.model.isRowSelected(t);Qo(n,!!i),$o(n,i)}n.style.height=this.rowHeight+"px",n.style.top=this.rowHeight*t+"px";var r=this.componentCreator(o,n);r.addGuiEventListener("focusin",(function(){return e.lastFocusedRowIndex=t})),n.appendChild(r.getGui()),this.renderedRows.has(t-1)?this.renderedRows.get(t-1).eDiv.insertAdjacentElement("afterend",n):this.renderedRows.has(t+1)?this.renderedRows.get(t+1).eDiv.insertAdjacentElement("beforebegin",n):this.eContainer.appendChild(n),this.renderedRows.set(t,{rowComponent:r,eDiv:n})},e.prototype.removeRow=function(t){var e=this.renderedRows.get(t);this.eContainer.removeChild(e.eDiv),this.destroyBean(e.rowComponent),this.renderedRows.delete(t)},e.prototype.addScrollListener=function(){var t=this;this.addGuiEventListener("scroll",(function(){return t.drawVirtualRows()}))},e.prototype.setModel=function(t){this.model=t},e.prototype.destroy=function(){this.isDestroyed||(this.clearVirtualRows(),this.isDestroyed=!0,t.prototype.destroy.call(this))},bu([it("resizeObserverService")],e.prototype,"resizeObserverService",void 0),bu([Wn("eContainer")],e.prototype,"eContainer",void 0)}(Zn);!function(t){t.Full="full",t.Partial="partial"}(Ru||(Ru={})),function(t){t.Column="column",t.GroupedColumn="groupedColumn",t.StackedColumn="stackedColumn",t.NormalizedColumn="normalizedColumn",t.Bar="bar",t.GroupedBar="groupedBar",t.StackedBar="stackedBar",t.NormalizedBar="normalizedBar",t.Line="line",t.Scatter="scatter",t.Bubble="bubble",t.Pie="pie",t.Doughnut="doughnut",t.Area="area",t.StackedArea="stackedArea",t.NormalizedArea="normalizedArea",t.Histogram="histogram"}(Ou||(Ou={})),function(t){t.Top="top",t.Right="right",t.Bottom="bottom",t.Left="left"}(Pu||(Pu={}));
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
var Du="undefined"==typeof global?{}:global;Du.HTMLElement="undefined"==typeof HTMLElement?{}:HTMLElement,Du.HTMLButtonElement="undefined"==typeof HTMLButtonElement?{}:HTMLButtonElement,Du.HTMLSelectElement="undefined"==typeof HTMLSelectElement?{}:HTMLSelectElement,Du.HTMLInputElement="undefined"==typeof HTMLInputElement?{}:HTMLInputElement,Du.Node="undefined"==typeof Node?{}:Node,Du.MouseEvent="undefined"==typeof MouseEvent?{}:MouseEvent;var Au=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Tu=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},_u=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.watermarkMessage=void 0,e}var o;return Au(e,t),o=e,e.prototype.validateLicense=function(){if(bn.missingOrEmpty(o.licenseKey))this.outputMissingLicenseKey();else if(o.licenseKey.length>32){var t=o.extractLicenseComponents(o.licenseKey),e=t.md5,n=t.license,i=t.version,r=t.isTrial;e===this.md5.md5(n)?bn.exists(i)&&i?this.validateLicenseKeyForVersion(i,!!r,n):this.validateLegacyKey(n):this.outputInvalidLicenseKey()}else this.outputInvalidLicenseKey()},e.extractExpiry=function(t){var e=t.substring(t.lastIndexOf("_")+1,t.length);return new Date(parseInt(o.decode(e),10))},e.extractLicenseComponents=function(t){var e=t.replace(/[\u200B-\u200D\uFEFF]/g,""),n=(e=e.replace(/\r?\n|\r/g,"")).length-32,i=e.substring(n),r=e.substring(0,n),s=o.extractBracketedInformation(e);return{md5:i,license:r,version:s[0],isTrial:s[1]}},e.prototype.getLicenseDetails=function(t){var e=o.extractLicenseComponents(t),n=e.md5,i=e.license,r=e.version,s=e.isTrial,a=n===this.md5.md5(i),l=null;return a&&(l=o.extractExpiry(i),a=!isNaN(l.getTime())),{licenseKey:t,valid:a,expiry:a?o.formatDate(l):null,version:r||"legacy",isTrial:s}},e.prototype.isDisplayWatermark=function(){return!bn.missingOrEmpty(this.watermarkMessage)},e.prototype.getWatermarkMessage=function(){return this.watermarkMessage||""},e.formatDate=function(t){var e=t.getDate(),o=t.getMonth(),n=t.getFullYear();return e+" "+["January","February","March","April","May","June","July","August","September","October","November","December"][o]+" "+n},e.getGridReleaseDate=function(){return new Date(parseInt(o.decode(o.RELEASE_INFORMATION),10))},e.decode=function(t){for(var e,n,i,r,s,a,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",p="",u=0,c=t.replace(/[^A-Za-z0-9+/=]/g,"");u<c.length;)e=l.indexOf(c.charAt(u++))<<2|(r=l.indexOf(c.charAt(u++)))>>4,n=(15&r)<<4|(s=l.indexOf(c.charAt(u++)))>>2,i=(3&s)<<6|(a=l.indexOf(c.charAt(u++))),p+=String.fromCharCode(e),64!=s&&(p+=String.fromCharCode(n)),64!=a&&(p+=String.fromCharCode(i));return p=o.utf8_decode(p)},e.utf8_decode=function(t){t=t.replace(/rn/g,"n");for(var e="",o=0;o<t.length;o++){var n=t.charCodeAt(o);n<128?e+=String.fromCharCode(n):n>127&&n<2048?(e+=String.fromCharCode(n>>6|192),e+=String.fromCharCode(63&n|128)):(e+=String.fromCharCode(n>>12|224),e+=String.fromCharCode(n>>6&63|128),e+=String.fromCharCode(63&n|128))}return e},e.setLicenseKey=function(t){o.licenseKey=t},e.extractBracketedInformation=function(t){var e=t.split("[").filter((function(t){return t.indexOf("]")>-1})).map((function(t){return t.split("]")[0]}));if(!e||0===e.length)return[null,null];var o=1===e.filter((function(t){return"TRIAL"===t})).length;return[e.filter((function(t){return 0===t.indexOf("v")})).map((function(t){return t.replace(/^v/,"")}))[0],o]},e.prototype.validateLicenseKeyForVersion=function(t,e,o){"2"===t&&(e?this.validateForTrial(o):this.validateLegacyKey(o))},e.prototype.validateLegacyKey=function(t){var e=o.getGridReleaseDate(),n=o.extractExpiry(t),i=!1,r=!1;if(isNaN(n.getTime())||(i=!0,r=e<n),i){if(!r){var s=o.formatDate(n),a=o.formatDate(e);this.outputIncompatibleVersion(s,a)}}else this.outputInvalidLicenseKey()},e.prototype.validateForTrial=function(t){var e=o.extractExpiry(t),n=new Date,i=!1,r=!1;if(isNaN(e.getTime())||(i=!0,r=e>n),i){if(!r){var s=o.formatDate(e);this.outputExpiredTrialKey(s)}}else this.outputInvalidLicenseKey()},e.prototype.outputInvalidLicenseKey=function(){console.error("*****************************************************************************************************************"),console.error("***************************************** AG Grid Enterprise License ********************************************"),console.error("********************************************* Invalid License ***************************************************"),console.error("* Your license for AG Grid Enterprise is not valid - please contact [email protected] to obtain a valid license. *"),console.error("*****************************************************************************************************************"),console.error("*****************************************************************************************************************"),this.watermarkMessage="Invalid License"},e.prototype.outputExpiredTrialKey=function(t){console.error("****************************************************************************************************************"),console.error("***************************************** AG Grid Enterprise License *******************************************"),console.error("***************************************** Trial Period Expired. *******************************************"),console.error("* Your license for AG Grid Enterprise expired on "+t+". *"),console.error("* Please email [email protected] to purchase a license. *"),console.error("****************************************************************************************************************"),console.error("****************************************************************************************************************"),this.watermarkMessage="Trial Period Expired"},e.prototype.outputMissingLicenseKey=function(){console.error("****************************************************************************************************************"),console.error("***************************************** AG Grid Enterprise License *******************************************"),console.error("****************************************** License Key Not Found ***********************************************"),console.error("* All AG Grid Enterprise features are unlocked. *"),console.error("* This is an evaluation only version, it is not licensed for development projects intended for production. *"),console.error("* If you want to hide the watermark, please email [email protected] for a trial license. *"),console.error("****************************************************************************************************************"),console.error("****************************************************************************************************************"),this.watermarkMessage="For Trial Use Only"},e.prototype.outputIncompatibleVersion=function(t,e){console.error("****************************************************************************************************************************"),console.error("****************************************************************************************************************************"),console.error("* AG Grid Enterprise License *"),console.error("* License not compatible with installed version of AG Grid Enterprise. *"),console.error("* *"),console.error("* Your AG Grid License entitles you to all versions of AG Grid that we release within the time covered by your license *"),console.error("* - typically we provide one year licenses which entitles you to all releases / updates of AG Grid within that year. *"),console.error("* Your license has an end (expiry) date which stops the license key working with versions of AG Grid released after the *"),console.error("* license end date. The license key that you have expires on "+t+", however the version of AG Grid you *"),console.error("* are trying to use was released on "+e+". *"),console.error("* *"),console.error("* Please contact [email protected] to renew your subscription to new versions and get a new license key to work with this *"),console.error("* version of AG Grid. *"),console.error("****************************************************************************************************************************"),console.error("****************************************************************************************************************************"),this.watermarkMessage="License Expired"},e.RELEASE_INFORMATION="MTYxMzQ2MjUzMTEzNw==",Tu([it("md5")],e.prototype,"md5",void 0),Tu([tt],e.prototype,"validateLicense",null),e=o=Tu([nt("licenseManager")],e)}(Mt),Fu=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Nu=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Lu=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.ieCompatibility=!1,e}return Fu(e,t),e.prototype.init=function(){this.ieCompatibility="5d41402abc4b2a76b9719d911017c592"!=this.md5("hello")},e.prototype.md5cycle=function(t,e){var o=t[0],n=t[1],i=t[2],r=t[3];o=this.ff(o,n,i,r,e[0],7,-680876936),r=this.ff(r,o,n,i,e[1],12,-389564586),i=this.ff(i,r,o,n,e[2],17,606105819),n=this.ff(n,i,r,o,e[3],22,-1044525330),o=this.ff(o,n,i,r,e[4],7,-176418897),r=this.ff(r,o,n,i,e[5],12,1200080426),i=this.ff(i,r,o,n,e[6],17,-1473231341),n=this.ff(n,i,r,o,e[7],22,-45705983),o=this.ff(o,n,i,r,e[8],7,1770035416),r=this.ff(r,o,n,i,e[9],12,-1958414417),i=this.ff(i,r,o,n,e[10],17,-42063),n=this.ff(n,i,r,o,e[11],22,-1990404162),o=this.ff(o,n,i,r,e[12],7,1804603682),r=this.ff(r,o,n,i,e[13],12,-40341101),i=this.ff(i,r,o,n,e[14],17,-1502002290),n=this.ff(n,i,r,o,e[15],22,1236535329),o=this.gg(o,n,i,r,e[1],5,-165796510),r=this.gg(r,o,n,i,e[6],9,-1069501632),i=this.gg(i,r,o,n,e[11],14,643717713),n=this.gg(n,i,r,o,e[0],20,-373897302),o=this.gg(o,n,i,r,e[5],5,-701558691),r=this.gg(r,o,n,i,e[10],9,38016083),i=this.gg(i,r,o,n,e[15],14,-660478335),n=this.gg(n,i,r,o,e[4],20,-405537848),o=this.gg(o,n,i,r,e[9],5,568446438),r=this.gg(r,o,n,i,e[14],9,-1019803690),i=this.gg(i,r,o,n,e[3],14,-187363961),n=this.gg(n,i,r,o,e[8],20,1163531501),o=this.gg(o,n,i,r,e[13],5,-1444681467),r=this.gg(r,o,n,i,e[2],9,-51403784),i=this.gg(i,r,o,n,e[7],14,1735328473),n=this.gg(n,i,r,o,e[12],20,-1926607734),o=this.hh(o,n,i,r,e[5],4,-378558),r=this.hh(r,o,n,i,e[8],11,-2022574463),i=this.hh(i,r,o,n,e[11],16,1839030562),n=this.hh(n,i,r,o,e[14],23,-35309556),o=this.hh(o,n,i,r,e[1],4,-1530992060),r=this.hh(r,o,n,i,e[4],11,1272893353),i=this.hh(i,r,o,n,e[7],16,-155497632),n=this.hh(n,i,r,o,e[10],23,-1094730640),o=this.hh(o,n,i,r,e[13],4,681279174),r=this.hh(r,o,n,i,e[0],11,-358537222),i=this.hh(i,r,o,n,e[3],16,-722521979),n=this.hh(n,i,r,o,e[6],23,76029189),o=this.hh(o,n,i,r,e[9],4,-640364487),r=this.hh(r,o,n,i,e[12],11,-421815835),i=this.hh(i,r,o,n,e[15],16,530742520),n=this.hh(n,i,r,o,e[2],23,-995338651),o=this.ii(o,n,i,r,e[0],6,-198630844),r=this.ii(r,o,n,i,e[7],10,1126891415),i=this.ii(i,r,o,n,e[14],15,-1416354905),n=this.ii(n,i,r,o,e[5],21,-57434055),o=this.ii(o,n,i,r,e[12],6,1700485571),r=this.ii(r,o,n,i,e[3],10,-1894986606),i=this.ii(i,r,o,n,e[10],15,-1051523),n=this.ii(n,i,r,o,e[1],21,-2054922799),o=this.ii(o,n,i,r,e[8],6,1873313359),r=this.ii(r,o,n,i,e[15],10,-30611744),i=this.ii(i,r,o,n,e[6],15,-1560198380),n=this.ii(n,i,r,o,e[13],21,1309151649),o=this.ii(o,n,i,r,e[4],6,-145523070),r=this.ii(r,o,n,i,e[11],10,-1120210379),i=this.ii(i,r,o,n,e[2],15,718787259),n=this.ii(n,i,r,o,e[9],21,-343485551),t[0]=this.add32(o,t[0]),t[1]=this.add32(n,t[1]),t[2]=this.add32(i,t[2]),t[3]=this.add32(r,t[3])},e.prototype.cmn=function(t,e,o,n,i,r){return e=this.add32(this.add32(e,t),this.add32(n,r)),this.add32(e<<i|e>>>32-i,o)},e.prototype.ff=function(t,e,o,n,i,r,s){return this.cmn(e&o|~e&n,t,e,i,r,s)},e.prototype.gg=function(t,e,o,n,i,r,s){return this.cmn(e&n|o&~n,t,e,i,r,s)},e.prototype.hh=function(t,e,o,n,i,r,s){return this.cmn(e^o^n,t,e,i,r,s)},e.prototype.ii=function(t,e,o,n,i,r,s){return this.cmn(o^(e|~n),t,e,i,r,s)},e.prototype.md51=function(t){var e,o=t.length,n=[1732584193,-271733879,-1732584194,271733878];for(e=64;e<=t.length;e+=64)this.md5cycle(n,this.md5blk(t.substring(e-64,e)));t=t.substring(e-64);var i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(e=0;e<t.length;e++)i[e>>2]|=t.charCodeAt(e)<<(e%4<<3);if(i[e>>2]|=128<<(e%4<<3),e>55)for(this.md5cycle(n,i),e=0;e<16;e++)i[e]=0;return i[14]=8*o,this.md5cycle(n,i),n},e.prototype.md5blk=function(t){for(var e=[],o=0;o<64;o+=4)e[o>>2]=t.charCodeAt(o)+(t.charCodeAt(o+1)<<8)+(t.charCodeAt(o+2)<<16)+(t.charCodeAt(o+3)<<24);return e},e.prototype.rhex=function(t){for(var e="0123456789abcdef".split(""),o="",n=0;n<4;n++)o+=e[t>>8*n+4&15]+e[t>>8*n&15];return o},e.prototype.hex=function(t){for(var e=0;e<t.length;e++)t[e]=this.rhex(t[e]);return t.join("")},e.prototype.md5=function(t){return this.hex(this.md51(t))},e.prototype.add32=function(t,e){return this.ieCompatibility?this.add32Compat(t,e):this.add32Std(t,e)},e.prototype.add32Std=function(t,e){return t+e&4294967295},e.prototype.add32Compat=function(t,e){var o=(65535&t)+(65535&e);return(t>>16)+(e>>16)+(o>>16)<<16|65535&o},Nu([et],e.prototype,"init",null),e=Nu([nt("md5")],e)}(Mt),Iu=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Gu=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Mu=function(t){function e(){return t.call(this,'<div class="ag-watermark">\n <div ref="eLicenseTextRef" class="ag-watermark-text"></div>\n </div>')||this}return Iu(e,t),e.prototype.postConstruct=function(){var t=this,e=this.shouldDisplayWatermark();bn.addOrRemoveCssClass(this.getGui(),"ag-hidden",!e),e&&(this.eLicenseTextRef.innerText=this.licenseManager.getWatermarkMessage(),window.setTimeout((function(){return t.addCssClass("ag-opacity-zero")}),0),window.setTimeout((function(){return t.addCssClass("ag-hidden")}),5e3))},e.prototype.shouldDisplayWatermark=function(){var t=this.licenseManager.isDisplayWatermark(),e=null!=location.hostname.match("^127.0.0.1|localhost|www.ag-grid.com$");return!!location.pathname&&-1!==location.pathname.indexOf("forceWatermark")||t&&!e},Gu([it("licenseManager")],e.prototype,"licenseManager",void 0),Gu([Wn("eLicenseTextRef")],e.prototype,"eLicenseTextRef",void 0),Gu([et],e.prototype,"postConstruct",null),e}(xn),xu={moduleName:pt.EnterpriseCoreModule,beans:[_u,Lu],agStackComponents:[{componentName:"AgWatermark",componentClass:Mu}]},Vu=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Hu=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Wu=function(t){function e(){var e=t.call(this)||this;return e.allComponents={},e}return Vu(e,t),e.prototype.registerStatusPanel=function(t,e){this.allComponents[t]=e},e.prototype.getStatusPanel=function(t){return this.allComponents[t]},e=Hu([nt("statusBarService")],e)}(Mt),ku=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),Bu=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},ju=function(t){function e(){return t.call(this,e.TEMPLATE)||this}return ku(e,t),e.prototype.postConstruct=function(){if(this.gridOptions.statusBar&&this.gridOptions.statusBar.statusPanels){var t=this.gridOptions.statusBar.statusPanels.filter((function(t){return"left"===t.align}));this.createAndRenderComponents(t,this.eStatusBarLeft);var e=this.gridOptions.statusBar.statusPanels.filter((function(t){return"center"===t.align}));this.createAndRenderComponents(e,this.eStatusBarCenter);var o=this.gridOptions.statusBar.statusPanels.filter((function(t){return!t.align||"right"===t.align}));this.createAndRenderComponents(o,this.eStatusBarRight)}else this.setDisplayed(!1)},e.prototype.createAndRenderComponents=function(t,e){var o=this,n=[];t.forEach((function(t){var e={api:o.gridOptionsWrapper.getApi(),columnApi:o.gridOptionsWrapper.getColumnApi(),context:o.gridOptionsWrapper.getContext()},i=o.userComponentFactory.newStatusPanelComponent(t,e);n.push({key:t.key||t.statusPanel,promise:i})})),Tn.all(n.map((function(t){return t.promise}))).then((function(){n.forEach((function(t){t.promise.then((function(n){var i=function(){o.getContext().destroyBean(n)};o.isAlive()?(o.statusBarService.registerStatusPanel(t.key,n),e.appendChild(n.getGui()),o.addDestroyFunc(i)):i()}))}))}))},e.TEMPLATE='<div class="ag-status-bar">\n <div ref="eStatusBarLeft" class="ag-status-bar-left"></div>\n <div ref="eStatusBarCenter" class="ag-status-bar-center"></div>\n <div ref="eStatusBarRight" class="ag-status-bar-right"></div>\n </div>',Bu([it("gridOptions")],e.prototype,"gridOptions",void 0),Bu([it("userComponentFactory")],e.prototype,"userComponentFactory",void 0),Bu([it("statusBarService")],e.prototype,"statusBarService",void 0),Bu([Wn("eStatusBarLeft")],e.prototype,"eStatusBarLeft",void 0),Bu([Wn("eStatusBarCenter")],e.prototype,"eStatusBarCenter",void 0),Bu([Wn("eStatusBarRight")],e.prototype,"eStatusBarRight",void 0),Bu([et],e.prototype,"postConstruct",null),e}(xn),Uu=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),zu=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Ku=function(t){function e(){return t.call(this,e.TEMPLATE)||this}return Uu(e,t),e.prototype.setLabel=function(t,e){this.setDisplayed(!1);var o=this.gridOptionsWrapper.getLocaleTextFunc();this.eLabel.innerHTML=o(t,e)},e.prototype.setValue=function(t){this.eValue.innerHTML=t},e.TEMPLATE='<div class="ag-status-name-value">\n <span ref="eLabel"></span>: \n <span ref="eValue" class="ag-status-name-value-value"></span>\n </div>',zu([Wn("eLabel")],e.prototype,"eLabel",void 0),zu([Wn("eValue")],e.prototype,"eValue",void 0),e}(xn),Yu=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),qu=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Xu=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Yu(e,t),e.prototype.postConstruct=function(){"clientSide"===this.gridApi.getModel().getType()?(this.setLabel("totalAndFilteredRows","Rows"),this.addCssClass("ag-status-panel"),this.addCssClass("ag-status-panel-total-and-filtered-row-count"),this.setDisplayed(!0),this.addManagedListener(this.eventService,Wt.EVENT_MODEL_UPDATED,this.onDataChanged.bind(this))):console.warn("AG Grid: agTotalAndFilteredRowCountComponent should only be used with the client side row model.")},e.prototype.onDataChanged=function(){var t=bn.formatNumberCommas(this.getFilteredRowCountValue()),e=bn.formatNumberCommas(this.getTotalRowCount());if(t===e)this.setValue(t);else{var o=this.gridOptionsWrapper.getLocaleTextFunc();this.setValue(t+" "+o("of","of")+" "+e)}},e.prototype.getFilteredRowCountValue=function(){var t=0;return this.gridApi.forEachNodeAfterFilter((function(e){e.group||t++})),t},e.prototype.getTotalRowCount=function(){var t=0;return this.gridApi.forEachNode((function(e){e.group||t++})),t},e.prototype.init=function(){},e.prototype.destroy=function(){t.prototype.destroy.call(this)},qu([it("gridApi")],e.prototype,"gridApi",void 0),qu([et],e.prototype,"postConstruct",null),e}(Ku),Qu=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),$u=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},Zu=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qu(e,t),e.prototype.postConstruct=function(){if(this.setLabel("filteredRows","Filtered"),"clientSide"===this.gridApi.getModel().getType()){this.addCssClass("ag-status-panel"),this.addCssClass("ag-status-panel-filtered-row-count"),this.setDisplayed(!0);var t=this.onDataChanged.bind(this);this.addManagedListener(this.eventService,Wt.EVENT_MODEL_UPDATED,t)}else console.warn("AG Grid: agFilteredRowCountComponent should only be used with the client side row model.")},e.prototype.onDataChanged=function(){var t=this.getTotalRowCountValue(),e=this.getFilteredRowCountValue();this.setValue(bn.formatNumberCommas(e)),this.setDisplayed(t!==e)},e.prototype.getTotalRowCountValue=function(){var t=0;return this.gridApi.forEachNode((function(e){return t+=1})),t},e.prototype.getFilteredRowCountValue=function(){var t=0;return this.gridApi.forEachNodeAfterFilter((function(e){e.group||(t+=1)})),t},e.prototype.init=function(){},e.prototype.destroy=function(){t.prototype.destroy.call(this)},$u([it("gridApi")],e.prototype,"gridApi",void 0),$u([et],e.prototype,"postConstruct",null),e}(Ku),Ju=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),tc=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},ec=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Ju(e,t),e.prototype.postConstruct=function(){this.setLabel("totalRows","Total Rows"),"clientSide"===this.gridApi.getModel().getType()?(this.addCssClass("ag-status-panel"),this.addCssClass("ag-status-panel-total-row-count"),this.setDisplayed(!0),this.addManagedListener(this.eventService,Wt.EVENT_MODEL_UPDATED,this.onDataChanged.bind(this))):console.warn("AG Grid: agTotalRowCountComponent should only be used with the client side row model.")},e.prototype.onDataChanged=function(){this.setValue(bn.formatNumberCommas(this.getRowCountValue()))},e.prototype.getRowCountValue=function(){var t=0;return this.gridApi.forEachLeafNode((function(e){return t+=1})),t},e.prototype.init=function(){},e.prototype.destroy=function(){t.prototype.destroy.call(this)},tc([it("gridApi")],e.prototype,"gridApi",void 0),tc([et],e.prototype,"postConstruct",null),e}(Ku),oc=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),nc=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},ic=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return oc(e,t),e.prototype.postConstruct=function(){if(this.isValidRowModel()){this.setLabel("selectedRows","Selected"),this.addCssClass("ag-status-panel"),this.addCssClass("ag-status-panel-selected-row-count");var t=this.gridApi.getSelectedRows().length;this.setValue(bn.formatNumberCommas(t)),this.setDisplayed(t>0);var e=this.onRowSelectionChanged.bind(this);this.addManagedListener(this.eventService,Wt.EVENT_MODEL_UPDATED,e),this.addManagedListener(this.eventService,Wt.EVENT_SELECTION_CHANGED,e)}else console.warn("AG Grid: agSelectedRowCountComponent should only be used with the client and server side row model.")},e.prototype.isValidRowModel=function(){var t=this.gridApi.getModel().getType();return"clientSide"===t||"serverSide"===t},e.prototype.onRowSelectionChanged=function(){var t=this.gridApi.getSelectedRows().length;this.setValue(bn.formatNumberCommas(t)),this.setDisplayed(t>0)},e.prototype.init=function(){},e.prototype.destroy=function(){t.prototype.destroy.call(this)},nc([it("gridApi")],e.prototype,"gridApi",void 0),nc([et],e.prototype,"postConstruct",null),e}(Ku),rc=function(){var t=function(e,o){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)e.hasOwnProperty(o)&&(t[o]=e[o])})(e,o)};return function(e,o){function n(){this.constructor=e}t(e,o),e.prototype=null===o?Object.create(o):(n.prototype=o.prototype,new n)}}(),sc=function(t,e,o,n){var i,r=arguments.length,s=r<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,o):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(t,e,o,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(r<3?i(s):r>3?i(e,o,s):i(e,o))||s);return r>3&&s&&Object.defineProperty(e,o,s),s},ac=function(t){function e(){return t.call(this,e.TEMPLATE)||this}return rc(e,t),e.prototype.destroy=function(){t.prototype.destroy.call(this)},e.prototype.postConstruct=function(){this.isValidRowModel()?(this.avgAggregationComp.setLabel("average","Average"),this.countAggregationComp.setLabel("count","Count"),this.minAggregationComp.setLabel("min","Min"),this.maxAggregationComp.setLabel("max","Max"),this.sumAggregationComp.setLabel("sum","Sum"),this.addManagedListener(this.eventService,Wt.EVENT_RANGE_SELECTION_CHANGED,this.onRangeSelectionChanged.bind(this)),this.addManagedListener(this.eventService,Wt.EVENT_MODEL_UPDATED,this.onRangeSelectionChanged.bind(this))):console.warn("AG Grid: agAggregationComponent should only be used with the client and server side row model.")},e.prototype.isValidRowModel=function(){var t=this.gridApi.getModel().getType();return"clientSide"===t||"serverSide"===t},e.prototype.init=function(){},e.prototype.setAggregationComponentValue=function(t,e,o){var n=this.getAggregationValueComponent(t);bn.exists(n)&&n&&(n.setValue(bn.formatNumberTwoDecimalPlacesAndCommas(e)),n.setDisplayed(o))},e.prototype.getAggregationValueComponent=function(t){var e=t+"AggregationComp",o=null,n=bn.exists(this.gridOptions.statusBar)&&this.gridOptions.statusBar?bn.find(this.gridOptions.statusBar.statusPanels,(function(t){return"agAggregationComponent"===t.statusPanel})):null;return bn.exists(n)&&n?(!bn.exists(n.statusPanelParams)||bn.exists(n.statusPanelParams)&&bn.exists(n.statusPanelParams.aggFuncs)&&bn.exists(bn.find(n.statusPanelParams.aggFuncs,(function(e){return e===t}))))&&(o=this[e]):o=this[e],o},e.prototype.onRangeSelectionChanged=function(){var t=this,e=this.rangeController?this.rangeController.getCellRanges():void 0,o=0,n=0,i=0,r=null,s=null,a={};e&&!bn.missingOrEmpty(e)&&e.forEach((function(e){for(var l=t.rangeController.getRangeStartRow(e),p=t.rangeController.getRangeEndRow(e);;){if(bn.missing(l)||!l||t.rowPositionUtils.before(p,l)||!l||!e.columns)break;e.columns.forEach((function(e){if(null!==l){var p=t.cellPositionUtils.createId({rowPinned:l.rowPinned,column:e,rowIndex:l.rowIndex});if(!a[p]){a[p]=!0;var u=t.rowRenderer.getRowNode(l);if(!bn.missing(u)){var c=t.valueService.getValue(e,u);bn.missing(c)||""===c||(c.value&&(c=c.value),"string"==typeof c&&(c=Number(c)),"number"!=typeof c||isNaN(c)||(o+=c,(null===s||c>s)&&(s=c),(null===r||c<r)&&(r=c),i++),n++)}}}})),l=t.cellNavigationService.getRowBelow(l)}}));var l=n>1,p=i>1;this.setAggregationComponentValue("count",n,l),this.setAggregationComponentValue("sum",o,p),this.setAggregationComponentValue("min",r,p),this.setAggregationComponentValue("max",s,p),this.setAggregationComponentValue("avg",o/i,p)},e.TEMPLATE='<div class="ag-status-panel ag-status-panel-aggregations">\n <ag-name-value ref="avgAggregationComp"></ag-name-value>\n <ag-name-value ref="countAggregationComp"></ag-name-value>\n <ag-name-value ref="minAggregationComp"></ag-name-value>\n <ag-name-value ref="maxAggregationComp"></ag-name-value>\n <ag-name-value ref="sumAggregationComp"></ag-name-value>\n </div>',sc([rt("rangeController")],e.prototype,"rangeController",void 0),sc([it("valueService")],e.prototype,"valueService",void 0),sc([it("cellNavigationService")],e.prototype,"cellNavigationService",void 0),sc([it("rowRenderer")],e.prototype,"rowRenderer",void 0),sc([it("gridOptions")],e.prototype,"gridOptions",void 0),sc([it("gridApi")],e.prototype,"gridApi",void 0),sc([it("cellPositionUtils")],e.prototype,"cellPositionUtils",void 0),sc([it("rowPositionUtils")],e.prototype,"rowPositionUtils",void 0),sc([Wn("sumAggregationComp")],e.prototype,"sumAggregationComp",void 0),sc([Wn("countAggregationComp")],e.prototype,"countAggregationComp",void 0),sc([Wn("minAggregationComp")],e.prototype,"minAggregationComp",void 0),sc([Wn("maxAggregationComp")],e.prototype,"maxAggregationComp",void 0),sc([Wn("avgAggregationComp")],e.prototype,"avgAggregationComp",void 0),sc([et],e.prototype,"postConstruct",null),e}(xn),lc={moduleName:pt.StatusBarModule,beans:[Wu],agStackComponents:[{componentName:"AgStatusBar",componentClass:ju},{componentName:"AgNameValue",componentClass:Ku}],userComponents:[{componentName:"agAggregationComponent",componentClass:ac},{componentName:"agSelectedRowCountComponent",componentClass:ic},{componentName:"agTotalRowCountComponent",componentClass:ec},{componentName:"agFilteredRowCountComponent",componentClass:Zu},{componentName:"agTotalAndFilteredRowCountComponent",componentClass:Xu}],dependantModules:[xu]};export{lc as StatusBarModule}; |
client/__tests__/components/User/User.spec.js | amarachukwu-agbo/hello-books | import React from 'react';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { MemoryRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { mount } from 'enzyme';
import User from '../../../components/User/User';
const props = {
match: {
url: '/users',
},
};
const mockStore = configureMockStore([thunk]);
const store = mockStore({});
describe('<User />', () => {
it('should render User component correctly', () => {
const wrapper = mount(<MemoryRouter>
<Provider store = { store } >
<User {...props} />
</Provider>
</MemoryRouter>);
expect(wrapper).toMatchSnapshot();
});
});
|
ajax/libs/material-ui/5.0.0-alpha.14/node/Table/Tablelvl2Context.js | cdnjs/cdnjs | "use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
/**
* @ignore - internal component.
*/
const Tablelvl2Context = /*#__PURE__*/React.createContext();
if (process.env.NODE_ENV !== 'production') {
Tablelvl2Context.displayName = 'Tablelvl2Context';
}
var _default = Tablelvl2Context;
exports.default = _default; |
packages/icons/src/md/social/NotificationsNone.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdNotificationsNone(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M24 44c2.21 0 4-1.79 4-4h-8c0 2.21 1.79 4 4 4zm12-12l4 4v2H8v-2l4-4V22c0-6.15 3.27-11.28 9-12.64V8c0-1.66 1.34-3 3-3s3 1.34 3 3v1.36c5.73 1.36 9 6.49 9 12.64v10zm-4 2V22c0-4.97-3.03-9-8-9-4.97 0-8 4.03-8 9v12h16z" />
</IconBase>
);
}
export default MdNotificationsNone;
|
tests/routes/Counter/components/Counter.spec.js | raviprajna/AttributesValues | import React from 'react'
import { bindActionCreators } from 'redux'
import { Counter } from 'routes/Counter/components/Counter'
import { shallow } from 'enzyme'
describe('(Component) Counter', () => {
let _props, _spies, _wrapper
beforeEach(() => {
_spies = {}
_props = {
counter : 5,
...bindActionCreators({
doubleAsync : (_spies.doubleAsync = sinon.spy()),
increment : (_spies.increment = sinon.spy())
}, _spies.dispatch = sinon.spy())
}
_wrapper = shallow(<Counter {..._props} />)
})
it('renders as a <div>.', () => {
expect(_wrapper.is('div')).to.equal(true)
})
it('renders with an <h2> that includes Counter label.', () => {
expect(_wrapper.find('h2').text()).to.match(/Counter:/)
})
it('renders {props.counter} at the end of the sample counter <h2>.', () => {
expect(_wrapper.find('h2').text()).to.match(/5$/)
_wrapper.setProps({ counter: 8 })
expect(_wrapper.find('h2').text()).to.match(/8$/)
})
it('renders exactly two buttons.', () => {
expect(_wrapper.find('button')).to.have.length(2)
})
describe('Increment', () => {
let _button
beforeEach(() => {
_button = _wrapper.find('button').filterWhere(a => a.text() === 'Increment')
})
it('exists', () => {
expect(_button).to.exist()
})
it('is a primary button', () => {
expect(_button.hasClass('btn btn-primary')).to.be.true()
})
it('Calls props.increment when clicked', () => {
_spies.dispatch.should.have.not.been.called()
_button.simulate('click')
_spies.dispatch.should.have.been.called()
_spies.increment.should.have.been.called()
})
})
describe('Double Async Button', () => {
let _button
beforeEach(() => {
_button = _wrapper.find('button').filterWhere(a => a.text() === 'Double (Async)')
})
it('exists', () => {
expect(_button).to.exist()
})
it('is a secondary button', () => {
expect(_button.hasClass('btn btn-secondary')).to.be.true()
})
it('Calls props.doubleAsync when clicked', () => {
_spies.dispatch.should.have.not.been.called()
_button.simulate('click')
_spies.dispatch.should.have.been.called()
_spies.doubleAsync.should.have.been.called()
})
})
})
|
packages/react/src/components/forms/InputDate/index.js | massgov/mayflower | /**
* InputDate module.
* @module @massds/mayflower-react/InputDate
* @requires module:pikaday/scss/pikaday
* @requires module:@massds/mayflower-assets/scss/00-base/pikaday
* @requires module:@massds/mayflower-assets/scss/01-atoms/input-date
*/
import React from 'react';
import PropTypes from 'prop-types';
import Pikaday from 'pikaday';
class InputDate extends React.Component {
constructor(props) {
super(props);
this.picker = null;
this.startPikaday = this.startPikaday.bind(this);
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
this.startPikaday();
this.picker.setDate(this.props.defaultDate, true);
}
// eslint-disable-next-line camelcase
UNSAFE_componentWillReceiveProps(nextProps) {
this.picker.setDate(nextProps.defaultDate, true);
}
handleChange(date) {
if (typeof this.props.onChangeCallback === 'function') {
this.props.onChangeCallback({ date });
}
}
startPikaday() {
const restrict = this.props.restrict;
const pickerOptions = {
field: this.dateInput,
format: this.props.format,
formatStrict: true,
onSelect: this.handleChange,
setDefaultDate: false
};
if (this.props.defaultDate !== null) {
pickerOptions.defaultDate = this.props.defaultDate;
pickerOptions.setDefaultDate = true;
}
this.picker = new Pikaday(pickerOptions);
this.dateInput.setAttribute('type', 'text');
if (restrict === 'max') {
this.picker.setMaxDate(new Date());
} else if (restrict === 'min') {
this.picker.setMinDate(new Date());
}
}
render() {
const classNames = this.props.required ? 'ma__input-date js-input-date js-is-required' : 'ma__input-date js-input-date ';
return(
<>
<label htmlFor={this.props.id}>{this.props.labelText}</label>
<input
className={classNames}
name={this.props.name}
id={this.props.id}
type="date"
placeholder={this.props.placeholder}
data-type="date"
data-restrict={this.props.restrict}
ref={(input) => { this.dateInput = input; }}
required={this.props.required}
format={this.props.format}
/>
</>
);
}
}
InputDate.propTypes = {
/** The label text above the input field */
labelText: PropTypes.string.isRequired,
/** Whether an input date is required or not */
required: PropTypes.bool,
/** The id on the input date element */
id: PropTypes.string.isRequired,
/** The name of the input date element */
name: PropTypes.string.isRequired,
/** The placeholder text in the input box, prompting users for a value */
placeholder: PropTypes.string,
/** Controls whether the user can pick any date (''), today and prior ('max') or today and future ('min') */
restrict: PropTypes.oneOf(['', 'max', 'min']),
/** Controls the date format of input date . The current option are: 'M/DD/YYYY’, 'MM/DD/YYYY’', 'MMM D YYYY', or 'dddd, MMMM Do YYYY' */
format: PropTypes.oneOf(['M/DD/YYYY', 'MM/DD/YYYY', 'MM-DD-YYYY', 'YYYYMMDD']),
/** Custom onChange function that receives the selected date input */
onChangeCallback: PropTypes.func,
/** The date to set by default */
defaultDate: PropTypes.instanceOf(Date)
};
// Only set defaults for the configuration variables which need to be opted in to activate.
InputDate.defaultProps = {
required: false,
restrict: '',
defaultDate: null,
format: 'M/DD/YYYY'
};
export default InputDate;
|
src/components/Header/Header.js | ynu/res-track-wxe | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Header.css';
import Link from '../Link';
import Navigation from '../Navigation';
import logoUrl from './logo-small.png';
function Header() {
return (
<div className={s.root}>
<div className={s.container}>
<Navigation className={s.nav} />
<Link className={s.brand} to="/">
<img src={logoUrl} width="38" height="38" alt="React" />
<span className={s.brandTxt}>Your Company</span>
</Link>
<div className={s.banner}>
<h1 className={s.bannerTitle}>React</h1>
<p className={s.bannerDesc}>Complex web apps made easy</p>
</div>
</div>
</div>
);
}
export default withStyles(s)(Header);
|
modules/Redirect.js | mjw56/react-router | import React from 'react'
import invariant from 'invariant'
import { createRouteFromReactElement } from './RouteUtils'
import { formatPattern } from './PatternUtils'
import { falsy } from './PropTypes'
var { string, object } = React.PropTypes
/**
* A <Redirect> is used to declare another URL path a client should be sent
* to when they request a given URL.
*
* Redirects are placed alongside routes in the route configuration and are
* traversed in the same manner.
*/
var Redirect = React.createClass({
statics: {
createRouteFromReactElement(element) {
var route = createRouteFromReactElement(element)
if (route.from)
route.path = route.from
// TODO: Handle relative pathnames, see #1658
invariant(
route.to.charAt(0) === '/',
'<Redirect to> must be an absolute path. This should be fixed in the future'
)
route.onEnter = function (nextState, replaceState) {
var { location, params } = nextState
var pathname = route.to ? formatPattern(route.to, params) : location.pathname
replaceState(
route.state || location.state,
pathname,
route.query || location.query
)
}
return route
}
},
propTypes: {
path: string,
from: string, // Alias for path
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
render() {
invariant(
false,
'<Redirect> elements are for router configuration only and should not be rendered'
)
}
})
export default Redirect
|
src/frame/rePCUI/tabs/base-tabs/SwipeableInkTabBar.js | gejialun8888/shop-react | import React from 'react';
import createReactClass from 'create-react-class';
import classnames from 'classnames';
import InkTabBarMixin from './InkTabBarMixin';
import SwipeableTabBarMixin from './SwipeableTabBarMixin';
import TabBarMixin from './TabBarMixin';
const SwipeableInkTabBar = createReactClass({
displayName: 'SwipeableInkTabBar',
mixins: [TabBarMixin, InkTabBarMixin, SwipeableTabBarMixin],
getSwipeableTabs() {
const props = this.props;
const children = props.panels;
const activeKey = props.activeKey;
const rst = [];
const prefixCls = props.prefixCls;
const _flexWidth = `${1 / props.pageSize * 100}%`;
const tabStyle = {
WebkitFlexBasis: _flexWidth,
flexBasis: _flexWidth,
};
React.Children.forEach(children, (child) => {
if (!child) {
return;
}
const key = child.key;
const cls = classnames(`${prefixCls}-tab`, {
[`${prefixCls}-tab-active`]: activeKey === key,
[`${prefixCls}-tab-disabled`]: child.props.disabled,
});
let events = {};
if (!child.props.disabled) {
events = {
onClick: this.onTabClick.bind(this, key),
};
}
const refProps = {};
if (activeKey === key) {
refProps.ref = 'activeTab';
}
rst.push(<div
role="tab"
style={tabStyle}
aria-disabled={child.props.disabled ? 'true' : 'false'}
aria-selected={activeKey === key ? 'true' : 'false'}
{...events}
className={cls}
key={key}
{...refProps}
>
{child.props.tab}
</div>);
});
return rst;
},
render() {
const inkBarNode = this.getInkBarNode();
const tabs = this.getSwipeableTabs();
const scrollbarNode = this.getSwipeBarNode([inkBarNode, tabs]);
return this.getRootNode(scrollbarNode);
},
});
export default SwipeableInkTabBar;
|
src/parser/warlock/destruction/modules/features/Havoc.js | FaideWW/WoWAnalyzer | import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Enemies from 'parser/shared/modules/Enemies';
import Events from 'parser/core/Events';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import { formatNumber, formatPercentage } from 'common/format';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
class Havoc extends Analyzer {
static dependencies = {
enemies: Enemies,
};
damage = 0;
constructor(...args) {
super(...args);
this.addEventListener(Events.damage.by(SELECTED_PLAYER), this.onDamage);
}
onDamage(event) {
const enemy = this.enemies.getEntity(event);
if (!enemy || !enemy.hasBuff(SPELLS.HAVOC.id, event.timestamp)) {
return;
}
this.damage += event.amount + (event.absorbed || 0);
}
// TODO: this could perhaps be reworked somehow to be more accurate but not sure how yet. Take it as a Havoc v1.0
statistic() {
if (this.damage === 0) {
return null;
}
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.HAVOC.id} />}
value={`${formatNumber(this.damage / this.owner.fightDuration * 1000)} DPS`}
label="Damage cleaved"
tooltip={`You cleaved ${formatNumber(this.damage)} damage (${formatPercentage(this.owner.getPercentageOfTotalDamageDone(this.damage))} %) to targets afflicted by your Havoc.<br /><br />Note: This number might be higher than it should be, as it also counts the damage you did directly to the Havoc target (not just the cleaved damage).`}
/>
);
}
statisticOrder = STATISTIC_ORDER.CORE(4);
}
export default Havoc;
|
app/context/WalletConnect/WalletConnectContext.js | CityOfZion/neon-wallet | // @flow
import React, { useCallback, useContext, useEffect, useState } from 'react'
import Client, { CLIENT_EVENTS } from '@walletconnect/client'
import { ERROR } from '@walletconnect/utils'
import KeyValueStorage from 'keyvaluestorage'
import { SessionTypes, AppMetadata } from '@walletconnect/types'
import {
formatJsonRpcError,
JsonRpcRequest,
JsonRpcResponse,
} from '@json-rpc-tools/utils'
type CtxOptions = {
appMetadata: AppMetadata,
chainIds: string[],
logger?: string,
methods: string[],
relayServer: string,
}
// $FlowFixMe
export const WalletConnectContext = React.createContext({})
export const WalletConnectContextProvider = ({
options,
children,
}: {
options: CtxOptions,
children: any,
}) => {
// $FlowFixMe
const [wcClient, setWcClient] = useState(undefined)
// $FlowFixMe
const [storage, setStorage] = useState(undefined)
// $FlowFixMe
const [sessionProposals, setSessionProposals] = useState([])
// $FlowFixMe
const [initialized, setInitialized] = useState(false)
// eslint-disable-next-line
// eslint-disable-next-line $FlowFixMe
const [chains, setChains] = useState(options.chainIds)
// $FlowFixMe
const [accounts, setAccounts] = useState([])
// $FlowFixMe
const [sessions, setSessions] = useState([])
// $FlowFixMe
const [requests, setRequests] = useState([])
// $FlowFixMe
const [results, setResults] = useState([])
// $FlowFixMe
const [onRequestCallback, setOnRequestCallback] = useState(undefined)
const [autoAcceptCallback, setAutoAcceptCallback] = useState(undefined)
// $FlowFixMe
const [txHash, setTxHash] = useState('')
// $FlowFixMe
const [messageVerification, setMessageVerificationResult] = useState({})
// $FlowFixMe
const [error, setError] = useState(false)
const init = async () => {
if (!wcClient) {
const st = new KeyValueStorage()
setStorage(st)
const clientOptions = {
controller: true,
relayProvider: options.relayServer,
storage: st,
}
if (process.env.NODE_ENV === 'development') {
// $FlowFixMe
clientOptions.logger = 'debug'
}
setWcClient(await Client.init(clientOptions))
}
}
const clearStorage = async () => {
const arr = []
// eslint-disable-next-line
for (let i = 0; i < localStorage.length; i++) {
// eslint-disable-next-line
// eslint-disable-next-line $FlowFixMe
if (localStorage.key(i).substring(0, 2) === 'wc') {
arr.push(localStorage.key(i))
}
}
// eslint-disable-next-line
for (let i = 0; i < arr.length; i++) {
// eslint-disable-next-line
// eslint-disable-next-line $FlowFixMe
localStorage.removeItem(arr[i])
}
}
useEffect(() => {
init()
clearStorage()
}, [])
const resetApp = async () => {
try {
if (sessions.length) {
await Promise.all(
sessions.map(
session =>
wcClient &&
wcClient.disconnect({
topic: session.topic,
reason: ERROR.USER_DISCONNECTED.format(),
}),
),
)
}
// BUG: for some reason when this reset app method
// was being invoked 'sessions' was an empty array.
// The check below will guarantee that all sessions
// are disconnected by checking storage.
if (
wcClient &&
wcClient.session.values &&
wcClient.session.values.length
) {
await Promise.all(
wcClient.session.values.map(
session =>
wcClient &&
wcClient.disconnect({
topic: session.topic,
reason: ERROR.USER_DISCONNECTED.format(),
}),
),
)
}
clearStorage()
setWcClient(undefined)
setSessionProposals([])
setInitialized(false)
setAccounts([])
setSessions([])
setRequests([])
setResults([])
} catch (e) {
console.error({ e })
}
}
const checkPersistedState = useCallback(
async () => {
if (typeof wcClient === 'undefined') {
throw new Error('Client is not initialized')
}
setSessions(wcClient.session.values)
setRequests(wcClient.session.history.pending)
setInitialized(true)
},
[wcClient],
)
// ---- MAKE REQUESTS AND SAVE/CHECK IF APPROVED ------------------------------//
const onRequestListener = (listener: any) => {
setOnRequestCallback(() => listener)
}
const autoAcceptIntercept = (listener: any) => {
setAutoAcceptCallback(() => listener)
}
const makeRequest = useCallback(
async (request: JsonRpcRequest) => {
const [namespace, reference, address] = accounts[0].split(':')
const chainId = `${namespace}:${reference}`
if (!onRequestCallback) {
throw new Error('There is no onRequestCallback')
}
const results = await onRequestCallback(address, chainId, request).catch(
e => {
console.error(e)
return setError(`An unkown error occurred please try again.`)
},
)
if (
results &&
results.result &&
!results.result.error &&
!results.result.isTest &&
!results.isMessage
) {
setTxHash(results.result)
} else if (
results &&
results.result &&
!results.result.error &&
!results.result.isTest &&
results.isMessage
) {
setMessageVerificationResult({ ...results, method: request.method })
} else {
const { result } = results
setError(
result ? result.error : 'An unkown error occurred please try again.',
)
}
return results
},
[accounts],
)
const approveAndMakeRequest = async (
requestEvent: SessionTypes.RequestEvent,
) => {
// $FlowFixMe
storage.setItem(`request-${JSON.stringify(requestEvent.request)}`, true)
return makeRequest(requestEvent)
}
const checkApprovedRequest = useCallback(
async (request: JsonRpcRequest) =>
// $FlowFixMe
storage.getItem(`request-${JSON.stringify(request)}`),
[storage],
)
const respondRequest = useCallback(
async (topic: string, response: JsonRpcResponse) => {
if (typeof wcClient === 'undefined') {
throw new Error('Client is not initialized')
}
await wcClient.respond({ topic, response })
},
[wcClient],
)
const subscribeToEvents = useCallback(
() => {
if (!accounts.length) {
return
}
if (typeof wcClient === 'undefined') {
throw new Error('Client is not initialized')
}
wcClient.on(
CLIENT_EVENTS.session.proposal,
(proposal: SessionTypes.Proposal) => {
if (typeof wcClient === 'undefined') {
throw new Error('Client is not initialized')
}
const supportedNamespaces: string[] = []
chains.forEach(chainId => {
const [namespace] = chainId.split(':')
if (!supportedNamespaces.includes(namespace)) {
supportedNamespaces.push(namespace)
}
})
const unsupportedChains: string[] = []
proposal.permissions.blockchain.chains.forEach(chainId => {
if (chains.includes(chainId)) return
unsupportedChains.push(chainId)
})
if (unsupportedChains.length) {
return wcClient.reject({ proposal })
}
const unsupportedMethods: string[] = []
proposal.permissions.jsonrpc.methods.forEach(method => {
if (options.methods.includes(method)) return
unsupportedMethods.push(method)
})
if (unsupportedMethods.length) {
return wcClient.reject({ proposal })
}
setSessionProposals(old => [...old, proposal])
return null
},
)
wcClient.on(
CLIENT_EVENTS.session.request,
async (requestEvent: SessionTypes.RequestEvent) => {
const askApproval = () => {
setRequests(old => [
...old.filter(i => i.request.id !== requestEvent.request.id),
requestEvent,
])
}
const approve = async () => {
const response = await makeRequest(requestEvent.request)
await respondRequest(requestEvent.topic, response)
}
const reject = async (message: string) => {
const response = formatJsonRpcError(
requestEvent.request.id,
message,
)
await respondRequest(requestEvent.topic, response)
}
try {
const alreadyApproved = await checkApprovedRequest(
requestEvent.request,
)
if (alreadyApproved) {
await approve()
} else if (autoAcceptCallback) {
let address
let chainId
if (accounts.length) {
const [namespace, reference, addr] = accounts[0].split(':')
address = addr
chainId = `${namespace}:${reference}`
}
const autoAccepted = autoAcceptCallback(
address,
chainId,
requestEvent.request,
)
if (autoAccepted) {
await approve()
} else {
await askApproval()
}
} else {
await askApproval()
}
} catch (e) {
await reject(e.message)
}
},
)
wcClient.on(CLIENT_EVENTS.session.created, () => {
if (typeof wcClient === 'undefined') {
throw new Error('Client is not initialized')
}
setSessions(wcClient.session.values)
})
wcClient.on(CLIENT_EVENTS.session.deleted, () => {
if (typeof wcClient === 'undefined') {
throw new Error('Client is not initialized')
}
setSessions(wcClient.session.values)
})
},
[
chains,
checkApprovedRequest,
makeRequest,
respondRequest,
wcClient,
accounts,
autoAcceptCallback,
options.methods,
],
)
useEffect(
() => {
if (wcClient) {
subscribeToEvents()
checkPersistedState()
}
},
[wcClient, subscribeToEvents, checkPersistedState],
)
const onURI = async (data: any) => {
const uri = typeof data === 'string' ? data : ''
if (!uri) return
if (typeof wcClient === 'undefined') {
throw new Error('Client is not initialized')
}
await wcClient.pair({ uri })
}
const getPeerOfRequest = async (requestEvent: JsonRpcRequest) => {
if (typeof wcClient === 'undefined') {
throw new Error('Client is not initialized')
}
const { peer } = await wcClient.session.get(requestEvent.topic)
return peer
}
const approveSession = async (proposal: SessionTypes.Proposal) => {
if (typeof wcClient === 'undefined') {
throw new Error('Client is not initialized')
}
if (typeof accounts === 'undefined') {
throw new Error('Accounts is undefined')
}
const accs = accounts.filter(account => {
const [namespace, reference] = account.split(':')
const chainId = `${namespace}:${reference}`
return proposal.permissions.blockchain.chains.includes(chainId)
})
const response = {
state: { accounts: accs },
metadata: options.appMetadata,
}
const session = await wcClient.approve({ proposal, response })
// $FlowFixMe
setSessionProposals(old => old.filter(i => i !== proposal))
setSessions([session])
}
const rejectSession = async (proposal: SessionTypes.Proposal) => {
if (typeof wcClient === 'undefined') {
throw new Error('Client is not initialized')
}
await wcClient.reject({ proposal })
setSessionProposals(old => old.filter(i => i !== proposal))
}
const disconnect = async (topic: string) => {
if (typeof wcClient === 'undefined') {
throw new Error('Client is not initialized')
}
await wcClient.disconnect({
topic,
reason: ERROR.USER_DISCONNECTED.format(),
})
}
const removeFromPending = async (requestEvent: JsonRpcRequest) => {
// $FlowFixMe
setRequests(requests.filter(x => x.request.id !== requestEvent.request.id))
}
const approveRequest = async (requestEvent: SessionTypes.RequestEvent) => {
if (typeof wcClient === 'undefined') {
throw new Error('Client is not initialized')
}
try {
const response = await approveAndMakeRequest(requestEvent)
await wcClient.respond({
topic: requestEvent.topic,
response,
})
} catch (error) {
console.error(error)
await wcClient.respond({
topic: requestEvent.topic,
response: formatJsonRpcError(
requestEvent.request.id,
'Failed or Rejected Request',
),
})
}
await removeFromPending(requestEvent)
}
const rejectRequest = async (requestEvent: JsonRpcRequest) => {
if (typeof wcClient === 'undefined') {
throw new Error('Client is not initialized')
}
await wcClient.respond({
topic: requestEvent.topic,
response: formatJsonRpcError(
requestEvent.request.id,
'Failed or Rejected Request',
),
})
await removeFromPending(requestEvent)
}
const addAccountAndChain = (address: string, chain: string) => {
setAccounts(oldAccs => [...oldAccs, `${chain}:${address}`])
}
const removeAccountAndChain = (address: string, chain: string) => {
setAccounts(oldAccs => [
...oldAccs.filter(acc => acc !== `${chain}:${address}`),
])
}
const clearAccountAndChain = () => {
setAccounts([])
}
const contextValue = {
wcClient,
setWcClient,
storage,
setStorage,
sessionProposals,
setSessionProposals,
initialized,
setInitialized,
chains,
setChains,
sessions,
setSessions,
requests,
setRequests,
results,
setResults,
init,
resetApp,
subscribeToEvents,
checkPersistedState,
approveAndMakeRequest,
makeRequest,
checkApprovedRequest,
onURI,
getPeerOfRequest,
approveSession,
rejectSession,
disconnect,
removeFromPending,
respondRequest,
approveRequest,
rejectRequest,
onRequestListener,
autoAcceptIntercept,
addAccountAndChain,
removeAccountAndChain,
clearAccountAndChain,
error,
setError,
txHash,
setTxHash,
setMessageVerificationResult,
messageVerification,
}
return (
<WalletConnectContext.Provider value={contextValue}>
{children}
</WalletConnectContext.Provider>
)
}
export const useWalletConnect = () => useContext(WalletConnectContext)
|